How to get the current user in a Spring Security application

Sitewide-10usd300x250 When developing an application, we sometimes need to access the currently logged in user programmatically. In this post, we’ll discuss how to do it when using Spring Security.

When someone logs in, Spring Security creates an Authentication object, and stores that in the security context. The authentication object has a principal property, which stores the current user.

A reference to the authentication object can be obtained as below:

Authentication auth = SecurityContextHolder
    .getContext().getAuthentication();

To elaborate, SecurityContextHolder.getContext() would return the spring security context, be it in the session or request. You can then retrieve the authentication object from that.

Once you get the authentication object, getting the principal out of it is not difficult. So, the complete code to retrieve the current user could look as below:

public static Optional<User> currentUser() {
	
	Authentication auth = SecurityContextHolder
			.getContext().getAuthentication();
	
	if (auth != null) {
		
		Object principal = auth.getPrincipal();
		
		if (principal instanceof User) // User is your user type that implements UserDetails
			return Optional.of((User) principal);
	}
	
	return Optional.empty();
}

Happy coding!

Leave a Reply

Your email address will not be published. Required fields are marked *