首页 > 解决方案 > 使用自定义 AuthenticationFailureHandler 时为 302 而不是 200

问题描述

当我没有AuthenticationFailureHandler在 my 中指定自定义时WebSecurityConfigurerAdapter,请求将重定向到状态为 200 的默认“/login?error”。当我添加仅将处理身份验证失败的自定义实现委托给默认实现时:

public class SomeCustomHandler implements AuthenticationFailureHandler {

  private final SimpleUrlAuthenticationFailureHandler authenticationFailureHandler = new SimpleUrlAuthenticationFailureHandler("/login?error");

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

WebSecurityConfigurerAdapter:

@Override
protected void configure(HttpSecurity http) throws Exception {
  http
      .requestMatchers()
      .antMatchers("/login", "/oauth/authorize")
    .and()
      .authorizeRequests()
      .anyRequest().authenticated()
    .and()
      .formLogin()
      .loginPage("/login")
      .failureHandler(new SomeCustomHandler())
    .permitAll();

}

我收到 302 并重定向到无错误登录页面。谁能解释为什么? 在此处输入图像描述

标签: javaspringspring-mvcredirectspring-security

解决方案


您看到的行为是/login?error重定向到,/login因为它是安全的。

当您没有自定义失败处理程序时,Spring Security 会知道您的登录 URL 和登录失败 URL。
通过添加.permitAll()到您的配置中,Spring Security 将允许对登录 URL 和登录失败 URL 的所有请求,因为它知道它们都是什么。

当您添加自定义失败处理程序时,Spring 不知道您的登录失败 URL 将是什么,甚至您是否会有失败 URL,因为您自己处理该逻辑。
因此.permitAll()仅适用于登录 URL。
如果您不想/login?error受到保护,则必须自己设置该配置。您可以执行以下操作:

http
    .authorizeRequests()
        .antMatchers("/login*").permitAll()
        .anyRequest().authenticated()
...

推荐阅读