Java 使用自定义AuthenticationFailureHandler时为302而不是200
当我没有在我的WebSecurity配置适配器中指定自定义AuthenticationFailureHandler时,请求将重定向到默认/登录?错误,状态为200。当我添加仅将处理身份验证失败的自定义实现委托给默认实现时:Java 使用自定义AuthenticationFailureHandler时为302而不是200,java,spring,spring-mvc,redirect,spring-security,Java,Spring,Spring Mvc,Redirect,Spring Security,当我没有在我的WebSecurity配置适配器中指定自定义AuthenticationFailureHandler时,请求将重定向到默认/登录?错误,状态为200。当我添加仅将处理身份验证失败的自定义实现委托给默认实现时: public class SomeCustomHandler implements AuthenticationFailureHandler { private final SimpleUrlAuthenticationFailureHandler authentica
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);
}
}
Web安全配置适配器:
@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并重定向到无错误登录页面。有人能解释一下原因吗?
您看到的行为是/login?重定向到/login时出错,因为它是安全的 当您没有自定义失败处理程序时,Spring Security会知道您的登录URL和登录失败URL。 通过将.permitAll添加到您的配置中,Spring Security将允许所有请求同时访问登录URL和登录失败URL,因为它知道它们都是什么 当您添加自定义失败处理程序时,Spring不知道您的登录失败URL是什么,甚至不知道您是否会有失败URL,因为您自己正在处理该逻辑。 因此.permitAll仅应用于登录URL。 如果您不想保护/login?错误,您必须自己设置该配置。您可以执行以下操作:
http
.authorizeRequests()
.antMatchers("/login*").permitAll()
.anyRequest().authenticated()
...