[英]OAUTH2 user service with Custom Authentication Providers
I am new to Spring Security and Oauth2.我是 Spring 安全和 Oauth2 的新手。 In my spring boot application, I have implemented authentication with Oauth2 with following set of changes:
在我的 spring 启动应用程序中,我已经使用 Oauth2 实现了身份验证,并进行了以下更改:
Custom Ouath2 User service is as follows:自定义 Ouath2 用户服务如下:
@Component
public class CustomOAuth2UserService extends DefaultOAuth2UserService {
private UserRepository userRepository;
@Autowired
public void setUserRepository(UserRepository userRepository) {
this.userRepository = userRepository;
}
public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException {
...
}
}
Security Configuration is as follows:安全配置如下:
@EnableWebSecurity
@Import(SecurityProblemSupport.class)
@ConditionalOnProperty(
value = "myapp.authentication.type",
havingValue = "oauth",
matchIfMissing = true
)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
private final CustomOAuth2UserService customOAuth2UserService;
public SecurityConfiguration(CustomOAuth2UserService customOAuth2UserService) {
this.customOAuth2UserService = customOAuth2UserService;
}
@Override
public void configure(WebSecurity web) {
web.ignoring()
.antMatchers(HttpMethod.OPTIONS, "/**")
.antMatchers("/app/**/*.{js,html}")
.antMatchers("/bundle.js")
.antMatchers("/slds-icons/**")
.antMatchers("/assets/**")
.antMatchers("/i18n/**")
.antMatchers("/content/**")
.antMatchers("/swagger-ui/**")
.antMatchers("/swagger-resources")
.antMatchers("/v2/api-docs")
.antMatchers("/api/redirectToHome")
.antMatchers("/test/**");
}
public void configure(HttpSecurity http) throws Exception {
RequestMatcher csrfRequestMatcher = new RequestMatcher() {
private RegexRequestMatcher requestMatcher =
new RegexRequestMatcher("/api/", null);
@Override
public boolean matches(HttpServletRequest request) {
return requestMatcher.matches(request);
}
};
http.csrf()
.requireCsrfProtectionMatcher(csrfRequestMatcher)
.and()
.authorizeRequests()
.antMatchers("/login**").permitAll()
.antMatchers("/manage/**").permitAll()
.antMatchers("/api/auth-info").permitAll()
.antMatchers("/api/**").authenticated()
.antMatchers("/management/health").permitAll()
.antMatchers("/management/info").permitAll()
.antMatchers("/management/prometheus").permitAll()
.antMatchers("/management/**").hasAuthority(AuthoritiesConstants.ADMIN)
.anyRequest().authenticated()//.and().oauth2ResourceServer().jwt()
.and()
.oauth2Login()
.redirectionEndpoint()
.baseUri("/oauth2**")
.and()
.failureUrl("/api/redirectToHome")
.userInfoEndpoint().userService(oauth2UserService())
;
http.cors().disable();
}
private OAuth2UserService<OAuth2UserRequest, OAuth2User> oauth2UserService() {
return customOAuth2UserService;
}
}
Content of application.properties is as follows: application.properties 的内容如下:
spring.security.oauth2.client.registration.keycloak.client-id=abcd
spring.security.oauth2.client.registration.keycloak.client-name=Auth Server
spring.security.oauth2.client.registration.keycloak.scope=api
spring.security.oauth2.client.registration.keycloak.provider=keycloak
spring.security.oauth2.client.registration.keycloak.client-authentication-method=basic
spring.security.oauth2.client.registration.keycloak.authorization-grant-type=authorization_code
myapp.oauth2.path=https://internal.authprovider.com/oauth2/
spring.security.oauth2.client.provider.keycloak.token-uri=${myapp.oauth2.path}token
spring.security.oauth2.client.provider.keycloak.authorization-uri=${myapp.oauth2.path}authorize
spring.security.oauth2.client.provider.keycloak.user-info-uri=${myapp.oauth2.path}userinfo
spring.security.oauth2.client.provider.keycloak.user-name-attribute=name
myapp.authentication.type=oauth
Now, with the existing authentication mechanism, I would like to add support for multiple authentication providers: LDAP, Form-Login, etc.现在,借助现有的身份验证机制,我想添加对多个身份验证提供程序的支持:LDAP、Form-Login 等。
In this regard, I have gone through a few articles:在这方面,我浏览了几篇文章:
But, I am not getting any concrete idea regarding what changes should I do in the existing code base in order to achieve this.但是,对于我应该在现有代码库中进行哪些更改以实现这一目标,我没有任何具体的想法。
Could anyone please help here?有人可以帮忙吗? Thanks.
谢谢。
I've created a simplified setup starting from your code with support for both OAuth2 and Basic Auth.我从您的代码开始创建了一个简化的设置,同时支持 OAuth2 和 Basic Auth。
/basic/**
will start a basic authentication. /basic/**
将启动基本身份验证。 /**
(everything else) triggers an OAuth2 Authorization Code authentication. /**
(其他所有内容)触发 OAuth2 授权码身份验证。
The key to achieve this is to have one @Configuration
class per authentication type.实现这一点的关键是每个身份验证类型都有一个
@Configuration
class。
Let's start with the controllers:让我们从控制器开始:
BasicHomeController基本家庭控制器
@Controller
public class BasicHomeController {
@GetMapping("/basic/home")
public @ResponseBody String home() {
return "basichome";
}
}
RestHomeController RestHome控制器
@RestController
public class RestHomeController {
@GetMapping("/api/home")
public String home() {
return "home";
}
}
Now, the configuration classes:现在,配置类:
OAuth2SecurityConfiguration OAuth2SecurityConfiguration
@Configuration
public class OAuth2SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/login**").permitAll()
.antMatchers("/manage/**").permitAll()
.antMatchers("/api/auth-info").permitAll()
.antMatchers("/api/**").authenticated()
.antMatchers("/management/health").permitAll()
.antMatchers("/management/info").permitAll()
.antMatchers("/management/prometheus").permitAll()
.antMatchers("/management/**").hasAuthority("ADMIN")
.antMatchers("/api/**").authenticated()
.and()
.oauth2Login()
.and()
.cors()
.disable();
}
}
BasicSecurityConfiguration (Notice the @Order(90)
, that's important BasicSecurityConfiguration (注意
@Order(90)
,这很重要
@Order(90)
@Configuration
public class BasicSecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.requestMatcher(new AntPathRequestMatcher("/basic/**"))
.csrf()
.disable()
.authorizeRequests()
.antMatchers("/basic/**").hasAuthority("BASIC_USER")
.and()
.httpBasic();
http.cors().disable();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user")
.password("{noop}password")
.roles("BASIC_USER");
}
}
Finally the configuration:最后配置:
spring:
security:
oauth2:
client:
registration:
keycloak:
client-id: myclient
client-secret: c6dce03e-ea13-4b76-8aab-c876f5c2c1d9
provider:
keycloak:
issuer-uri: http://localhost:8180/auth/realms/myrealm
With this in place, if we hit http://localhost:8080/basic/home
, will be prompted with the basic auth popup:有了这个,如果我们点击
http://localhost:8080/basic/home
,将提示基本身份验证弹出窗口:
Trying with http://localhost:8080/api/home
sends you to Keycloak's login form:尝试使用
http://localhost:8080/api/home
会将您发送到 Keycloak 的登录表单:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.