java - 使用自定义 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();
}
解决方案
您看到的行为是/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()
...
推荐阅读
- c++ - 需要更新 DNS 响应包
- jquery - 获取DataTable中的当前行号
- java - 应用于基本类型的实例时,ObjectInput/OutputStream 和 DataInput/OutputStream 之间有什么区别?
- android - 获取 RecyclerView 项目点击次数
- python - 如何用 {value} 替换 python/django 中三引号中的变量值?
- c# - 如何将带有子属性的 JSON 反序列化为 C# 中的 ONE 对象
- javascript - Flutter webview如何使用evaluateJavascript?
- javascript - 为什么我的导航栏折叠切换在反应中不起作用
- java - FetchType.LAZY 和 Left Join Fetch 的抓取性能是否不同
- python - Django:如何向管理员发送特定用户活动的通知?