Search code examples
javaspringspring-bootauthenticationaop

How to inject the username (not the Authentication)?


In my spring boot application, in my rest controllers, I successfully inject an instance of Authentication to get the session's user information.

However, in all of those controllers, I currently call a helper method like this:

@GetMapping
public List<String> getData(Authentication auth) {
    String username = auth.getName().replaceFirst(".*?\\\\", ""); // to remove windows domain name
    // the rest of these methods only use variable `username`, never `auth`
}

How can I reduce this code duplication?


Solution

  • You can create a utility class as follows and then you can use it like this UserUtility.getUsername() wherever you need.

    public class UserUtility {
    
        public static String getUsername(){
            if (SecurityContextHolder.getContext() != null && SecurityContextHolder.getContext().getAuthentication() != null) {
                return SecurityContextHolder.getContext().getAuthentication().getPrincipal());
            }
            return null;
        }
    }