Jun 5

Grails AcegiSecurity Create User on BootStrap

Category: grails, j2ee, java

To create users on startup with a blank database:

import org.codehaus.groovy.grails.web.servlet.GrailsApplicationAttributes

class BootStrap {
def init = { servletContext ->
new Role(description:"Administrators", authority:"ROLE_ADMIN").save();
new Role(description:"User", authority:"ROLE_USER").save();
def ctx = servletContext.getAttribute(GrailsApplicationAttributes.APPLICATION_CONTEXT);
def authService =  ctx.getBean("authenticateService");
def pass = authService.passwordEncoder('aPasswordGoesHere');
def config = authService.securityConfig;
def defaultRole = config.security.defaultRole;
def role = Role.findByAuthority(defaultRole);
def adminRole = Role.findByAuthority("ROLE_ADMIN");
def p = new User(username:"admin"
,passwd:pass
,enabled:true
,email:'test@example.com',
,userRealName:"Default Admin");
role.addToPeople(p);
adminRole.addToPeople(p);
if (p.save())
println("Created default admin");
else {
p.errors.allErrors.each {
println it
}
}
}

2 Comments so far

  1. Jan June 6th, 2008 3:16 am

    I had similar code for http://www.grailstutorials.com site. But what I did differently is that in BootStrap I control if admin role already exists because I believe you will get unique constraint exception on tomcat restart.

  2. Vincent Janelle June 6th, 2008 10:51 am

    That’s true.

    I really need to add a if ( Role.findByAuthority(”ROLE_…”) != null ) around that. Right now it works because I’m still in the create-drop phase of the application were the data is repopulated every time.

Leave a comment