当我未在 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();
}
最佳答案
您看到的行为是 /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/