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
相关产品推荐
相关产品推荐

