spring-security Sping Boot -如何在使用AuthenticationFailureBadCredentialsEvent时获得IP地址?

jk9hmnmh  于 2022-11-11  发布在  Spring
关注(0)|答案(1)|浏览(155)

请告诉我如何在使用AuthenticationFailureBadCredentialsEvent时获得IP地址?

@Autowired
private LoginAttemptService loginAttemptService;

@EventListener
public void onAuthenticationFailure(AuthenticationFailureBadCredentialsEvent event) {

    // How can I get the ip address here?

    }

下面显示的选项不起作用。

WebAuthenticationDetails auth = (WebAuthenticationDetails) event.getAuthentication();
    auth.getRemoteAddress();
ojsjcaue

ojsjcaue1#

基于javax.servlet.ServletRequest接口具有关于远程主机的信息这一事实,我将给予两种可能的解决方案(我还没有测试它们)。

1.使用AuthenticationFailureHandler

接口AuthenticationFailureHandler具有方法onAuthenticationFailure​(HttpServletRequest, HttpServletResponse, AuthenticationException),该方法具有可用的请求javax.servlet.http.HttpServletRequest

public class CustomAuthenticationFailureHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest req, HttpServletResponse res, AuthenticationException e) throws IOException, ServletException {

        // implementation
    }
}

2.正在调用RequestContextHolder

这个上下文保持器能够通过方法currentRequestAttributes获得包含当前绑定到线程的servlet请求的请求属性。

ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
ServletRequest servletRequest = attributes.getRequest();

相关问题