The ip-address is already present in the Authentication
object (not the UserDetails
).
You can call getDetails()
on the Authentication
object and in a web application and properly configured Spring Security environment this will give you an instance of WebAuthenticationDetails
which has the ip-address inside it. You can call the getRemoteAddress
method to obtain the address. (See the javadoc)..
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
WebAuthenticationDetails details = (WebAuthenticationDetails) auth.getDetails();
String ipAddress = details.getRemoteAddress();
Something along those lines, you could put this behind a utility method or something to obtain the ip-address.
Apparently you want to log authentication attempts, this can be easily achieved by implementing an ApplicationListener
and let that listen to AbstractAuthenticationEvent
s. Spring Security issues those for each authentication attempt, and also includes the Authentication
(containing the IP-address) into it.
public class AuthenticationAttemptLoggerListener implements ApplicationListener<AbstractAuthenticationEvent> {
private final Logger logger = LoggerFactory.getLogger(AuthenticationAttemptLoggerListener.class);
public void onApplicationEvent(AbstractAuthenticationEvent event) {
Authentication auth = event.getAuthentication();
WebAuthenticationDetails details = (WebAuthenticationDetails) auth.getDetails();
String ipAddress = details.getRemoteAddress();
if (event instanceof AbstractAuthenticationFailureEvent) {
logger.warn("Unsuccesful authentication attemped from: {}", ipAddress);
} else {
logger.info("Succesful authentication attemped from: {}", ipAddress);
}
}
}
Something like this should catch and log everything. You might want to take a look at all the available events.