How to find users' IPs in Spring Security?

Viewed 24552

I need to find those user who are logged in our application.
We are using Spring Security and there must be a way to find out users' IPs.

I think these information are stored in their sessions. In Spring Security, the current sessions are stored in SessionRegistry. From this class I can have list of authenticated users and some session information. (Using getAllPrincipals , getAllSessions and getSessionInformation)

The question is, how can I have access to current users' IPs? Consider we have to give service to a known region only.
The SessionInformation is not much help as it does not contain much information.

3 Answers

You can get IP address from WebAuthenticationDetails object, which can be obtained from Authentication instance.

Object details =
    SecurityContextHolder.getContext().getAuthentication().getDetails();
if (details instanceof WebAuthenticationDetails)
    ipAddress = ((WebAuthenticationDetails) details).getRemoteAddress();
Related