isopropylcyanide / Jwt-Spring-Security-JPA

Backend MVP showcasing JWT (Json Web Token) authentication with multiple login, timeout / refresh / logout (with in memory invalidation) using Spring Security & MySQL JPA.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to get current user?

mjza opened this issue · comments

Is there any API that we could get the current user anywhere?

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

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