java - Spring AuthenticationFailureHandler 和 WebSecurityConfigurerAdapter loginPage()

标签 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.

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

最佳答案

好吧,我通过将“/login**”添加到 http.authorizeRequests().antMatchers("/css/**", "/img/**", "/js/** ")

关于java - Spring AuthenticationFailureHandler 和 WebSecurityConfigurerAdapter loginPage(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27730395/

相关文章:

java - 使用 HandlerInterceptor 或 AbstractAuthenticationProcessingFilter 进行 Spring 身份验证

spring-security - Spring security - 如何同时提及基于表单的身份验证和基本身份验证

grails - 如何使用 Grails Spring Security 插件在访问操作之前要求登录?

spring-boot - java.lang.IllegalStateException : Failed to load ApplicationContext Spring Boot + JUnit test 错误

java - 在不知道属性名称和属性数量的情况下处理 json 对象

java - 可读性分类器采用哪种方法

java - Spring BOOT 错误

java - 将列表写入 .csv 文件

Grails Spring Security RequestMap 不匹配/

java - @Min 和 @Max 验证在 spring boot 中不适用于 hibernate validator 包