Reputation: 23
I was wondering if it is possible to store the logged in user information (username, firstname,lastname,roles) in the session so I can retrieve it anywhere in the program without doing a database lookup?
Currently, I am doing this in most of my methods in order to get all the required information :
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
UserDetails userDetails = (UserDetails) authentication.getPrincipal();
UsersModel senderUser = userRepository.findByusername(userDetails.getUsername());
However, I would like to avoid doing a database lookup everytime to obtain the user information.
Upvotes: 1
Views: 2679
Reputation: 8203
https://www.baeldung.com/spring-security-authentication-with-a-database
UserDetails
and in this example it is MyUserPrincipal
and make it have all the basic info you need.MyUserPrincipal userDetails = (MyUserPrincipal) authentication.getPrincipal();
Note:
Behind the scene, spring uses HttpSessionSecurityContextRepository
to store your SecurityContext
in http session and restore it back on every request. Since your MyUserPrincipal
is now stored in security context, you are actually indirectly storing it in session. But for whatever reason, you want to store it http session directly, you can retrieve it from security context and store it.
Upvotes: 2