Spring AuthenticationFailureHandler 和 WebSecurityConfigurerAdapter loginPage()

2024-02-09

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

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

The 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");

}

我的 Web 应用程序安全类如下所示:

@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.

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


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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Spring AuthenticationFailureHandler 和 WebSecurityConfigurerAdapter loginPage() 的相关文章

随机推荐