bezkoder / spring-boot-spring-security-jwt-authentication

Spring Boot + Security: Token Based Authentication example with JWT, Authorization, Spring Data & MySQL
1.32k stars 825 forks source link

SecurityContextHolder #2

Open sohskd opened 4 years ago

sohskd commented 4 years ago

Hi May I ask what is the use of

SecurityContextHolder.getContext().setAuthentication(authentication);

in the AuthController?

I thought JWT was session-less and stateless. Thank you

anu1097 commented 4 years ago

SecurityContextHolder is the most fundamental object where we store details of the present security context of the application (includes details of the principal). Spring Security uses an Authentication object to represent this information and we can query this Authentication object from anywhere in our application:

Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); // currently authenticated user Object principal = authentication.getPrincipal();

Pasting it from author's another detailed blog post on the same- https://bezkoder.com/spring-boot-jwt-mysql-spring-security-architecture/

torres-sonia commented 2 years ago

To clarify, the reason why JWT is considered stateless is because we do not need to store the user's session in the server. Instead, the client is responsible for storing session details in the form of the jwt token.

The line SecurityContextHolder.getContext().setAuthentication(authentication); does not store the session details in a session store, instead it is just simply used to tell Spring Security that the user is authenticated.