Get current logged in user from Spring when SessionCreationPolicy.STATELESS is used


I want to implement this example using Keyclock server with Spring Security 5.

I’m going to use OAuth2.0 authentication with JWT token. I’m interested how I can get the current logged in user into the Rest Endpoint?

I have configured Spring Security not to store user sessions using http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);.

One possible way is to use this code:

Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
if (principal instanceof UserDetails) {
  String username = ((UserDetails)principal).getUsername();
} else {
  String username = principal.toString();
}

But I don’t know is it going to work. Can someone give some advice for that case?