It is possible to get the user name using:
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
String username = ((UserDetails)principal).getUsername();
But there is no direct way to get the user id of the authenticated user. Please consider adding that.
Comment From: KyleMoser
There is no direct way to get a username because the Authentication interface doesn't even require that there is a username. It's only possible to get the username the way you did it because your Authentication principal is a UserDetails object. But the principal isn't required to be any specific type, so how would you suggest that the framework implement your requirement?
Comment From: eleftherias
Thank for reaching out. As the poster above mentions, the authentication principal can be any object and is not required to have a username.
Spring Security does provide an @AuthenticationPrincipal annotation, which might be what you're looking for.
It can take a SpEL expression as a parameter to resolve the principal.
For example, the code you shared could be rewritten as follows:
@GetMapping("/test")
public String test(@AuthenticationPrincipal(expression = "username") String name) {
return name;
}