Reputation: 359
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
Upvotes: 10
Views: 25185
Reputation: 2774
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
}
Upvotes: 9
Reputation: 11827
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.
Upvotes: 4