Я пытался реализовать сервер аутентификации OAuth2, используя руководства Дэйва Сайера, вдохновленные JHipster. Но я не могу понять, как все это работает вместе.
Похоже, что настройка безопасности с использованием WebSecurityConfigurerAdapter перезаписывается, когда я использую ResourceServerConfigurerAdapter.
@Configuration
@EnableResourceServer
public class OAuth2ResourceConfig extends ResourceServerConfigurerAdapter {
private TokenExtractor tokenExtractor = new BearerTokenExtractor();
@Override
public void configure(HttpSecurity http) throws Exception {
http
.addFilterAfter(contextClearer(), AbstractPreAuthenticatedProcessingFilter.class)
.authorizeRequests()
.anyRequest().authenticated().and().httpBasic();
}
private OncePerRequestFilter contextClearer() {
return new OncePerRequestFilter() {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
if (tokenExtractor.extract(request) == null) {
SecurityContextHolder.clearContext();
}
filterChain.doFilter(request, response);
}
};
}
@Component
public class CustomWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
private final AuthenticationManager authenticationManager;
@Autowired
public CustomWebSecurityConfigurerAdapter(AuthenticationManager authenticationManager) {
this.authenticationManager = authenticationManager;
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.parentAuthenticationManager(authenticationManager);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.formLogin()
.loginPage("/login").permitAll()
.and()
.authorizeRequests().antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
.and()
.requestMatchers().antMatchers("/login", "/oauth/authorize", "/oauth/confirm_access")
.and()
.authorizeRequests().anyRequest().authenticated();
}
}
Это код, взятый из нескольких разных примеров, поэтому они могут не так хорошо смешиваться. Но я не могу найти хороший список документации / примеров для OAuth2 (в отличие от Spring Boot, у которого есть отличная документация), поэтому у меня проблемы с пониманием того, как все они сочетаются друг с другом. Если я не добавлю loginForm в ResourceServerConfigurerAdapter, он просто выдаст мне несанкционированный доступ. Но я определил его в WebSecurityConfigurererAdapter как permissionAll ().
Это AuthorizationServerConfigurerAdapter:
@Configuration
@EnableAuthorizationServer
public class OAuth2AuthorizationConfig extends AuthorizationServerConfigurerAdapter {
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private JwtAccessTokenConverter jwtAccessTokenConverter;
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient("acme")
.secret("acmesecret")
.authorizedGrantTypes("authorization_code", "refresh_token",
"password").scopes("openid");
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.authenticationManager(authenticationManager).accessTokenConverter(jwtAccessTokenConverter);
}
@Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
oauthServer.tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()");
}
}
Что я делаю не так? Нужно ли мне настраивать всю безопасность в ResourceServerConfigurerAdapter? Нужен ли мне вообще WebSecurityConfigurerAdapter?
Если кто-нибудь знает какие-либо руководства, учебные пособия, блоги или что-то подобное, что может помочь мне понять, как это работает, я был бы очень признателен.
С уважением, Кеннет.
OAuth2ResourceConfig
лишний. Просто говорю. - person Dave Syer   schedule 19.02.2015