Единственный способ, с помощью которого я смог это сделать, - это пользовательский TokenEndpointAuthenticationFilter
:
AuthenticationManagerProvider
Это необходимо, потому что вам нужен AuthenticationManager
для создания экземпляраa TokenEndpointAuthenticationFilter
и вы хотите, чтобы экземпляр Spring был создан автоматически.
@Configuration // @Order(99) is important so this bean is initialized before the
@Order(99) // AuthorizationServerConfigurer at 100
public class AuthenticationManagerProvider extends WebSecurityConfigurerAdapter {
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
}
AuthorizationServerConfigurerAdapter
@Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
AuthenticationManager authenticationManager = authenticationManagerProvider.authenticationManagerBean();
DefaultOAuth2RequestFactory oAuth2RequestFactory = new DefaultOAuth2RequestFactory(clientDetailsService);
CustomAuthenticationFilter filter = new CustomAuthenticationFilter(authenticationManager, oAuth2RequestFactory);
security.tokenKeyAccess("permitAll()") //
.checkTokenAccess("isAuthenticated()") //
.allowFormAuthenticationForClients() //
.addTokenEndpointAuthenticationFilter(filter);
}
CustomAuthenticationFilter
Вы, вероятно, могли бы специально переопределить успешные и неудачные попытки аутентификации, но в моем случае мне нужно обработать оба, чтобы сбросить количество неудачных попыток на успешную и заблокировать учетную запись, когда достигнут максимум, поэтому я решил переопределить doFilter()
напрямую.
Просто не забудьте вызвать супер реализацию в конце, иначе ваш клиент не получит токен!
public class CustomAuthenticationFilter extends TokenEndpointAuthenticationFilter {
public CustomAuthenticationFilter(AuthenticationManager authenticationManager, OAuth2RequestFactory oAuth2RequestFactory) {
super(authenticationManager, oAuth2RequestFactory);
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
// do your thing, then call super-implementation to continue normal authentication flow
super.doFilter(request, response, chain);
}
}