How to get current user?
mjza opened this issue · comments
Mahdi Jaberzadeh Ansari commented
Is there any API that we could get the current user anywhere?
Aman Garg commented
Hi. Not sure what you mean by anywhere. You can create any API and pass the current user context.
Read about AuthenticationPrincipal here.
In the current codebase, there's a @CurrentUser
annotation that we use to obtain the current user. It simply is a wrapper over the AuthenticationPrincipal
. You can check the usage in UserController#me
API
Mahdi Jaberzadeh Ansari commented
I found this way also:
import org.springframework.security.core.context.SecurityContextHolder;
// Extract current user
private CustomUserDetails getCurrentUser() {
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
CustomUserDetails customUserDetails = null;
if (principal instanceof CustomUserDetails) {
customUserDetails = (CustomUserDetails) principal;
}
return customUserDetails;
}