YuriMarikov
YuriMarikov

Reputation: 23

Storing User Information into session, Spring Security

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

Answers (1)

https://www.baeldung.com/spring-security-authentication-with-a-database

  1. Create a class that implements UserDetails and in this example it is MyUserPrincipal and make it have all the basic info you need.
  2. Then you can cast it to your class and retrieve the information. (MyUserPrincipal userDetails = (MyUserPrincipal) authentication.getPrincipal();

Note:

Behind the scene, spring uses HttpSessionSecurityContextRepository to store your SecurityContextin 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

Related Questions