You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring认证失败时如何获取输入信息?Spring3升级Spring5后原有方法已废弃

Spring 3 迁移至 Spring 5 后认证失败获取用户凭证的解决方案

根因说明

Spring 4.2 版本正式移除了 AuthenticationException.getAuthentication() 方法,未通过认证的凭证信息不再直接挂载在异常实例中。你之前的尝试存在两处明确错误:

  • request.getParameter(WebAttributes.AUTHENTICATION_EXCEPTION) 用法错误:WebAttributes.AUTHENTICATION_EXCEPTION 是 Spring 存入请求属性的常量,不是请求传参,需要用 getAttribute() 读取
  • request.getSession().getAttribute(name) 未传入正确的 key 值:Spring 默认存储认证异常的 session key 就是 WebAttributes.AUTHENTICATION_EXCEPTION,未定义 name 变量自然无法识别

推荐方案(优先级从高到低)

方案1:自定义 AuthenticationFailureHandler(最稳定)

直接在认证失败的回调逻辑中获取所需信息,不需要后续从请求/会话中二次捞取,适配所有认证场景:

@Component
public class CustomAuthFailureHandler extends SimpleUrlAuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request,
                                        HttpServletResponse response,
                                        AuthenticationException exception)
                                        throws IOException, ServletException {
        // 1. 直接读取本次尝试认证的用户名
        String attemptUsername = request.getParameter("username");
        // 2. 如果需要完整的Authentication对象,从请求属性中获取
        Authentication attemptAuth = (Authentication) request.getAttribute("SPRING_SECURITY_LAST_AUTHENTICATION");
        Object principal = attemptAuth.getPrincipal();
        
        // 此处写入你的业务逻辑,比如记录失败日志、拼接返回信息等
        super.onAuthenticationFailure(request, response, exception);
    }
}

在 Spring Security 配置中注册该处理器即可生效:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .formLogin()
        .failureHandler(customAuthFailureHandler) // 绑定自定义失败处理器
        // 其余配置省略
}

方案2:直接从请求/会话属性读取

如果不需要自定义失败逻辑,也可以在认证失败跳转的接口/页面中直接取值:

// 从请求属性读取认证异常
AuthenticationException authEx = (AuthenticationException) request.getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
// 读取最后一次尝试的用户名
String lastUsername = (String) request.getAttribute("SPRING_SECURITY_LAST_USERNAME");
// 需配置session存储认证信息时,从session读取的写法
AuthenticationException sessionAuthEx = (AuthenticationException) request.getSession().getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);

注意:如果 Spring Security 配置了allowSessionCreation=false,或认证失败后自动清除了会话属性,session 取值会返回 null,优先使用请求属性取值。


内容的提问来源于stack exchange,提问作者Angelo Dente

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 17:15:06