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

Spring Boot:如何通过AuthenticationFailureBadCredentialsEvent获取IP地址

正确获取认证失败事件中的客户端IP地址

你之前的问题出在直接把Authentication对象强转为WebAuthenticationDetails了,正确的做法是从Authentication的getDetails()方法中获取WebAuthenticationDetails实例,再调用getRemoteAddress()拿到IP。

完整的实现代码如下:

@Autowired
private LoginAttemptService loginAttemptService;

@EventListener
public void onAuthenticationFailure(AuthenticationFailureBadCredentialsEvent event) {
    // 获取Authentication对象
    Authentication authentication = event.getAuthentication();
    if (authentication != null) {
        Object details = authentication.getDetails();
        // 判断details是否为WebAuthenticationDetails类型
        if (details instanceof WebAuthenticationDetails) {
            WebAuthenticationDetails webDetails = (WebAuthenticationDetails) details;
            String clientIp = webDetails.getRemoteAddress();
            // 拿到IP后可调用业务逻辑,比如记录登录失败次数
            loginAttemptService.registerFailedAttempt(clientIp);
        }
    }
}

补充说明

  • WebAuthenticationDetails是Spring Security为Web环境提供的认证详情类,封装了客户端IP、会话ID等信息,仅在Web环境下会自动注入到Authentication的details属性中。
  • 增加空值和类型判断是为了避免NullPointerException或ClassCastException,比如非Web环境的认证场景中,details可能不是WebAuthenticationDetails类型。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 03:05:20