Tuesday, February 22, 2022

SecurityContext and SecurityContextHolder in Spring Security.

Main purpose of SecurityContext to hold the currently authenticated user information as
principal and make sure this principal will be available all the method in same thread.
To get authenticated user details SecurityContextHolder will be used.


from principle? Here my spring boot project structure. From this principal we can get the currently logged in user. How can we get the user detail.



I have added spring-boot-starter-security jar in my pom.xml. This to set a default login screen for my application. 

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
If you add this dependency, spring boot will generate the password for your application on
server startup.

You can see the password in console log: Here generated security is below and default username will be 'user',
Using generated security password: e3660fc9-941c-4012-ba6d-8d1870a177d6. If you restart the server then new password will be generate.

Let we check the principal for default user and password for security context.



Here we are able to get the username of currently logged in user using securitycontext and securitycontextholder. 

We cannot every time copy the password from console. Spring provide the properties to set username and password. Here I used them for my application security. Let we check principal after change this property change.

spring.security.user.name=username
spring.security.user.password=User@123

Let login the application using new username and password, check the securityContext 
userdetails,




Let check with other method call and find the username for securitycontext.
let me call my getUser() to fetch particular user detail from db,

let me call : http://localhost:8084/getUser?userId=101

Here we can see the username from securityContext. Usually we need to have
securityContextHolder to get securityContext, from securityContext we can get authentication
from there we can get principal.

Here code snippet:

Object principalObject = SecurityContextHolder.getContext().
                                    getAuthentication().getPrincipal();

if(principalObject instanceof org.springframework.security.core.userdetails.User)
{
String userName = ((org.springframework.security.core.userdetails.User)principalObject)
                                                                               .getUsername();
System.out.println("logged in user: " + userName);
}

Main purpose of SecurityContext to hold the currently authenticated user information as
principal and make sure this principal will be available all the method in same thread.
To get authenticated user details SecurityContextHolder will be used.


From this principal we can get the currently logged in user. How can we get the user detail
from principle? Here my spring boot project structure.

No comments:

Post a Comment