One controller in my app needs to be accessible by users authenticated against an external database.
I have set up a custom user object,
class CustomUserDetails extends GrailsUser {
final String externalId
CustomUserDetails(String username, String password, boolean enabled,
boolean accountNonExpired, boolean credentialsNonExpired,
boolean accountNonLocked,
Collection<GrantedAuthority> authorities,
long id, String externalId) {
super(username, password, enabled, accountNonExpired,
credentialsNonExpired, accountNonLocked, authorities, id)
this.externalId = externalId
}
}
and a custom AuthenticationProvider
class CustomAuthenticationProvider implements AuthenticationProvider {
def springSecurityService
Authentication authenticate(Authentication customAuth) {
/* Do stuff to validate the user's credentials here */
def userDetails = new CustomUserDetails(customAuth.getPrincipal(), customAuth.getCredentials(), true, true, true, true,
[new GrantedAuthorityImpl('ROLE_SPECIAL_USER')], 9999999, "externalDatabaseIdString")
def token = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.authorities)
return token
}
boolean supports(Class authentication) {
return true
}
}
I’ve made entries in Config.groovy to add this to the springsecurity.providerNames list, and added the following to conf/spring/resources.groovy
beans = {
customAuthenticationProvider(info.proadvisors.auth.CustomAuthenticationProvider){ bean -> bean.autowire = "byName" }
userDetailsService(org.codehaus.groovy.grails.plugins.springsecurity.GormUserDetailsService){ bean -> bean.autowire = "byName" }
}
Here’s the problem – in my controller, springSecurityService is being injected but springSecurityService.getCurrentUser() is null, and returns a null pointer exception when I try to access the externalId property that should be on the authenticated user object.
If, in my CustomAuthenticationProvider, instead of creating an instance of CustomUserDetails I use GormUserDetailsService to give me a GrailsUser object and use that to build the token, the controller works properly and getCurrentUser() works.
Any ideas on why this isn’t working?
springSecurityService.getPrincipal() gives me what I’m looking for.
Not sure why getCurrentUser() doesn’t work while getPrincpal() does, but it is what it is.