I am new to Spring MVC and Spring Security. I have performed log-in and registration functionality using Spring security and MVC. I am not able to find any way for session management .
I want to access some user details on all the pages like (email, name,id,role etc). I want to save these to session object so I can get these on any of the page.
I get the following way for session in spring
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
auth.getPrincipal();
But from the object returned by this I can get only username and password details.
But I need to access more details of that user.
Please help me to get solution for this. Thanks in advance.
I want to get my model class object to be returned from SecurityContextHolder.getContext().getAuthentication().getDetails(); For this what I need to configure.
Regards, Pranav
The HttpServletRequest.getUserPrincipal() will return the result of SecurityContextHolder.getContext().getAuthentication() . This means it is an Authentication which is typically an instance of UsernamePasswordAuthenticationToken when using username and password based authentication.
The UserDetailsService interface is used to retrieve user-related data. It has one method named loadUserByUsername() which can be overridden to customize the process of finding the user. It is used by the DaoAuthenticationProvider to load details about the user during authentication.
public class SecurityContextHolder extends Object. Associates a given SecurityContext with the current execution thread. This class provides a series of static methods that delegate to an instance of SecurityContextHolderStrategy .
You need to make your model class implement the UserDetails interface
class MyUserModel implements UserDetails {
//All fields and setter/getters
//All interface methods implementation
}
Then in your spring controller you can do this:
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
Object myUser = (auth != null) ? auth.getPrincipal() : null;
if (myUser instanceof MyUserModel) {
MyUserModel user = (MyUserModel) myUser;
//get details from model object
}
You can use this to get the UserDetails
(or any implementation with your custom details).
UserDetails userDetails = SecurityContextHolder.getContext().getAuthentication().getDetails();
If there are not available, you can load the user details from the UserDetailsService
.
In both cases, I think you have to save them yourself in a session scope bean.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With