When details in principal object of spring security are not sufficient

24 / Jul / 2015 by Lovin Saini 2 comments

Sometimes we need to access details of current logged in user but that will be an additional database query. To save that query we can use principal object of Spring security which provides details of logged in user . But by default principal object have few fields like id, username and password.

If we need to access user’s name / email Id or any other field of user then we have to make a database query. To save this query we can add more details in principal object.

Spring security returns instance of GrailsUser. We can add more fields in grails user by extending it and creating a new class having more fields which are required. To achieve this, following are the changes need to be done:

1. Create a new class which will extend GrailsUser and will have required additional fields.

[code language=”java”]
class MyOwnGrailsUser extends GrailsUser {
String emailId, userNameToDisplay // additional fields
public MyOwnGrailsUser(User user, Collection authorities) {
super(user.username, user.password, user.enabled, !user.accountExpired,
!user.passwordExpired, !user.accountLocked, authorities, user.id);
this.emailId = user.emailId
this.userNameToDisplay = user.userNameToDisplay
}
}
[/code]

2. We need to implement interface GrailsUserDetailsService to return instance of MyOwnGrailsUser.
For implementing GrailsUserDetailsService we need to override loadUserByUsername method which will return instance of MyOwnGrailsUser class.

[code language=”java”]
class MyOwnUserDetailsService implements GrailsUserDetailsService {
UserDetails loadUserByUsername(String username, boolean loadRoles)
throws UsernameNotFoundException {
User user = User.findByUsername(username)
def authorities = user.authorities.collect { new GrantedAuthorityImpl(it.authority) }
return MyOwnGrailsUser(user,authorities)
}
}
[/code]

3. Also update resources.groovy for new bean of MyOwnUserDetailsService.

[code language=”java”]
beans = {
userDetailsService(MyOwnUserDetailsService)
}
[/code]

Now whenever we use springSecurityService.principal to get principal object it will return instance of our MyOwnGrailsUser class with additional fields.

FOUND THIS USEFUL? SHARE IT

comments (2)

  1. Pingback: Diario Grails (Settimana 30 del 2015) | BME

Leave a Reply

Your email address will not be published. Required fields are marked *