Search code examples
springgrailsspring-security

Grails spring-security-core plugin question: password in User class isn't String


I'm working on an application which stores password as byte[] in the db. I can't change the db. So my domain class has the following:

String userId
byte[] userPasswd

I know i can customize the names of the properties in Config.groovy but what about using byte[] instead of String datatype for password property? In case this is not currently supported in the plugin, a work around would be highly appreciated.


Solution

  • There are a few ways, but this seems the cleanest and requires no Config.groovy changes.

    Change the persistent password property to another name like you did (userPasswd) but put in a getter for getPassword() that the plugin will use, and convert the byte array to a String there:

    class User {
    
       String username
       byte[] userPasswd
       boolean enabled
       boolean accountExpired
       boolean accountLocked
       boolean passwordExpired
    
       static constraints = {
          username blank: false, unique: true
          password blank: false
       }
    
       static transients = ['password']
    
       String getPassword() {
          userPasswd ? new String(userPasswd) : null
       }
    
       Set<Role> getAuthorities() {
          UserRole.findAllByUser(this).collect { it.role } as Set
       }
    }
    

    Adding 'password' to the transients list is important since the real persistent field is userPasswd.

    This will affect how you create users, e.g.

    def user = new User(username: 'me', enabled: true,
       passwd: springSecurityService.encodePassword('password').bytes).save()