This is actually documented in the site for the Spring Core Security plugin, but I’ve decided to post it anyway 🙂 For the nitty gritty, head to the documentation; I’ll just be providing how I implemented it (most of the code’s from the link too 😉 ).
There was a time that I needed to add details to the user of the system. Now, it’s simple to think that all you had to do was just add the field to the User domain classes that you made. Sadly, it’s not that easy, but the actual implementation is pretty straightforward.
Let’s say we wanted to add a user’s home phone (homeNo
) and mobile phone number (mobile
). Create the following class:
package com.sample.test import org.codehaus.groovy.grails.plugins.springsecurity.GrailsUser import org.springframework.security.core.GrantedAuthority class MyUserDetails extends GrailsUser { // additional details you want the user object to have final String homeNo final String mobile MyUserDetails(String username, String password, boolean enabled, boolean accountNonExpired, boolean credentialsNonExpired, boolean accountNonLocked, Collection authorities, long id, String homeNo, String mobile) { super(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities, id) // pass and assign the values here this.homeNo = homeNo this.mobile = mobile } }
Now, add the service class, which is needed for you to get the details of the user:
package com.sample.test import org.codehaus.groovy.grails.plugins.springsecurity.GrailsUser import org.codehaus.groovy.grails.plugins.springsecurity.GrailsUserDetailsService import org.codehaus.groovy.grails.plugins.springsecurity.SpringSecurityUtils import org.springframework.security.core.authority.GrantedAuthorityImpl import org.springframework.security.core.userdetails.UserDetails import org.springframework.security.core.userdetails.UsernameNotFoundException class MyUserDetailsService implements GrailsUserDetailsService { static final List NO_ROLES = [new GrantedAuthorityImpl(SpringSecurityUtils.NO_ROLE)] UserDetails loadUserByUsername(String username, boolean loadRoles) throws UsernameNotFoundException { return loadUserByUsername(username) } UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { User.withTransaction { status -> User user = User.findByUsername(username) if (!user) throw new UsernameNotFoundException('User not found', username) def authorities = user.authorities.collect { new GrantedAuthorityImpl(it.authority) } // add the fields in the return... return new MyUserDetails(user.username, user.password, user.enabled, !user.accountExpired, !user.passwordExpired, !user.accountLocked, authorities ?: NO_ROLES, user.id, user.homeNo, user.mobile) } } }
Then, don’t forget to register the bean in grails-app/conf/spring/resources.groovy
!!
beans = { userDetailsService(com.sample.test.MyUserDetailsService) }