Search

Dark theme | Light theme

March 20, 2009

Create user/roles for Spring Security for Grails in Bootstrap

To secure a Grails application we can write our own code or use one of the available plugins, like the Spring Security plugin. If we use the plugin we can add user and roles to the database, which are used to authenticate the users. The plugin generates web pages we can use to add users and roles, but we can also use the Bootstrap class in the grails-app/conf directory to create users and roles. These users will be present when the application is started.

The code to achieve this is simple, but we need something special. The User object needs an MD5 encoded password. Luckily we can use the AuthenticateService from Spring Security to do this. We simply inject the service in our Bootstrap class and we can encode our password.

class BootStrap {
    def authenticateService
    
    def init = { servletContext ->
         def role = new Role(authority: 'ROLE_ADMIN', description: 'Admin role').save()
         def admin = new User(username: 'admin', userRealName: 'admin', 
                              passwd: authenticateService.encodePassword('admin'), 
                              enabled: true, email: 'admin@servername')
         admin.addToAuthorities(role)
         admin.save()
    }
    def destroy = {
    }
}