Spring AuthenticationFailureHandler和WebSecurityConfigurerAdapter loginPage()

时间:2015-01-01 11:34:55

标签: java spring-security spring-boot

编辑:已解决。在这篇文章之后看到我的评论

我目前正在使用Spring-Security实现Web应用程序。我已经实现了一个自定义AuthenticationFailureHandler,用于检查用户是否经常尝试使用错误的凭据登录(并阻止他几分钟)。但是正常的登录失败应该将用户重定向到具有参数错误(/login?error)的登录页面。此页面显示错误消息,例如“您键入的密码错误”

AutenticationFailureHandler看起来像这样(没有无法解释的代码)

public class CustomAuthenticationHandler implements AuthenticationFailureHandler {
// Some variables 

@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {

// some logic here..

request.setAttribute("param", "error");
response.sendRedirect("/login?error");

}

我的WebApplicationSecurity类如下所示:

@Configuration
@EnableWebMvcSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
CustomAuthenticationHandler customAuthenticationHandler;

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

    http.formLogin()
        .loginPage("/login")
        .permitAll()
        .failureHandler(customAuthenticationHandler)
        .and()
        .logout()
        .permitAll();

    http.authorizeRequests()
        .antMatchers("/css/**", "/img/**", "/js/**")
        .permitAll()
        .anyRequest()
        .authenticated();

    http
        .csrf()
        .disable();
}

@Bean
CustomAuthenticationHandler authenticationHandler() {
    return new CustomAuthenticationHandler();
}

@Configuration
protected static class AuthenticationConfiguration extends
        GlobalAuthenticationConfigurerAdapter {

    @Override
    public void init(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
            .withUser("*******")
            .password("*******")
            .roles("USER");
    }
}
}

现在的问题是,AuthenticationFailureHandler重定向到/login?error,但(我不知道为什么)会对/login进行另一次重定向。

你能帮我解决一下我的问题吗?

1 个答案:

答案 0 :(得分:3)

好吧,我通过添加" / login **"解决了这个问题。到http.authorizeRequests().antMatchers("/css/**", "/img/**", "/js/**")