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>
server startup.
Here we are able to get the username of currently logged in user using securitycontext and securitycontextholder.
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