java - 使用自定义 AuthenticationFailureHandler 时为 302 而不是 200

标签 java spring spring-mvc redirect spring-security

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

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 并重定向到无错误登录页面。有人能解释一下为什么吗? enter image description here

最佳答案

您看到的行为是 /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()
...

关于java - 使用自定义 AuthenticationFailureHandler 时为 302 而不是 200,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57215438/

相关文章:

java - 在 Java 中使用 DatagramPacket

java - 为什么 Spring 提供自己的任务执行器?

spring - @PathVariable 不与 @RequestBody 绑定(bind)

java - 如何使用 MockMvc 测试接收自定义对象的 spring @RequestBody

java - 使用默认程序在 Java 中打开文件时出现问题

java - unicode 字符串的 gson 序列化不起作用

java - 是否可以注入(inject)Spring配置方法?

debugging - 如何开启Spring的组件扫描调试信息?

java - 使用复合键的 Hibernate XML 子类化

Java 构建相互依赖的事件链