How to inject the username (not the Authentication)?

slartidan :

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?

Ozay Duman :

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;
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=68616&siteId=1