Spring Security with Java Configuration: How to handle BadCredentialsException from a custom provider

烈酒焚心 提交于 2019-12-03 17:21:14

The first Filter I created was a subclass of GenericFilterBean and it did not have support for authentication failure handler or success handler. However AbstractAuthenticationProcessingFilter supports success and failure handlers. My filter is as simple as that:

public class TokenAuthenticationProcessingFilter extends
    AbstractAuthenticationProcessingFilter {

public TokenAuthenticationProcessingFilter(
        RequestMatcher requiresAuthenticationRequestMatcher) {
    super(requiresAuthenticationRequestMatcher);
}

@Override
public Authentication attemptAuthentication(HttpServletRequest request,
        HttpServletResponse response) throws AuthenticationException,
        IOException, ServletException {
    Authentication auth = new TokenAuthentication("-1");
    try {
        Map<String, String[]> params = request.getParameterMap();
        if (!params.isEmpty() && params.containsKey("auth_token")) {
            String token = params.get("auth_token")[0];
            if (token != null) {
                auth = new TokenAuthentication(token);
            }
        }
        return this.getAuthenticationManager().authenticate(auth);
    } catch (AuthenticationException ae) {
        unsuccessfulAuthentication(request, response, ae);
    }
    return auth;
}}

and my http security is:

    public static class SecurityConfigForRS extends
        WebSecurityConfigurerAdapter {

    @Autowired
    TokenAuthenticationProvider tokenAuthenticationProvider;

    @Override
    protected void configure(AuthenticationManagerBuilder auth)
            throws Exception {
        auth.authenticationProvider(tokenAuthenticationProvider);
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean()
            throws Exception {
        return super.authenticationManagerBean();
    }

    @Bean
    protected AbstractAuthenticationProcessingFilter getTokenAuthFilter()
            throws Exception {
        TokenAuthenticationProcessingFilter tapf = new TokenAuthenticationProcessingFilter(
                new RegexRequestMatcher("^/rest.*", null));
        tapf.setAuthenticationManager(authenticationManagerBean());
        return tapf;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        super.configure(http);

        http.regexMatcher("^/rest.*")
                .addFilterAfter(getTokenAuthFilter(),
                        BasicAuthenticationFilter.class).csrf().disable();

    }
}

The filter chain order does matter! I placed it after BasicAuthenticationFilter and it works fine. Of course there might be a better solution but for now this works!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!