Reputation: 303
I am looking for the right way to store and display additional details of a logged-in user through out my application using Spring Security.
For example, I want to show Welcome:Mr.Smith (Administrator, Math Dept) on top of every page. For this I want to obtain the prefix, last name, designation and dept for the logged in user.
I am using a custom UserDetails
service to fetch a user from the database. While browsing, I found that Authentication
has getDetails()
, which can store additional details related to authentication, can I use that method to store additional details?
If yes can you show a simple example? Can I use AuthenticationSuccessHanlder
to do this job, or am I looking at the problem in a completely wrong way? Should I not handle this in the spring security layer? where should I take care of it?
Upvotes: 2
Views: 5423
Reputation: 1974
Besides the need for a custom authentication-provider (an implementation of UserDetailsService
), that you already identified, this can be done customizing the defaults that the framework provides a little further.
The framework provides a UserDetails
interface and some implementations of it like a User
class and other.
In an application of mine I had the need for a person without necessarily being a user of the application.
My way was to extend the already provided Spring Security User
and make my UserDetailsService
implementation return it.
public class RequestUserDetails
extends org.springframework.security.core.userdetails.User {
private static final long serialVersionUID = -6411988532329234916L;
private Integer personId;
public RequestUserDetails(String username, String password, Integer personId,
Collection<? extends GrantedAuthority> authorities) {
super(username, password, authorities);
this.personId = personId;
}
public Integer getPersonId() {
return personId;
}
}
+
@Service
public class UserSecurityService
implements org.springframework.security.core.userdetails.UserDetailsService {
[...]
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
[...]
return new RequestUserDetails(
userCreds.getLogin(),
userCreds.getPassword(),
person.getId(),
getAuthorities(domainUser.getRoles())
);
}
}
Simplistic Usages:
At a controller level with a javax.security.Principal
parameter (not tied to Spring MVC):
( (RequestUserDetails) ((Authentication)principal).getPrincipal() ).getPersonId()
At a controller level tied to Spring MVC @Controller
annotation, with a Authentication
parameter:
( (RequestUserDetails)authentication.getPrincipal() ).getPersonId()
If you need further reference on Spring Security UserDetails
go to API javadocs
Upvotes: 5
Reputation: 30088
The extra details should be properties of a custom UserDetails class that your custom UserDetailsService returns from its loadUserByName method.
Upvotes: 3