Last updated by loldrup 2 years ago
Installing Spring Security in a mint Grails installation: ========================================================= (inspired by )

Install Spring Security in your Grails-installation (some stuff will go in your Grails-app, so you have to be located in your Grails-apps folder):

cd path_to_your_grails_app grails install-plugin spring-security-core

Now create the domain classes needed for Spring Security plugin:

grails s2-quickstart com.myApp com.myApp.User com.myApp.Role

Now you need to change a couple of URL mappings so that the login and logout controllers can be reached. That's simple enough to fix by adding the following two lines to UrlMappings.groovy:

"/login/$action?"(controller: "login") "/logout/$action?"(controller: "logout")

Now you need to add some roles. We will add 'user' and 'admin' roles in the file .../com.myApp/grails-app/conf/Config.groovy like so:

import org.example.SecRole

class BootStrap { def init = { … def userRole = Role.findByAuthority('ROLE_USER') ?: new Role(authority: 'ROLE_USER').save(failOnError: true) def adminRole = Role.findByAuthority('ROLE_ADMIN') ?: new Role(authority: 'ROLE_ADMIN').save(failOnError: true) … } }

Now you need to make sure that at least one user is always created. We will make it so that 'admin' is created, by adding some code to the file /grails/com.myApp/grails-app/conf/Config.groovy like so:

class BootStrap { def springSecurityService

def init = { … def adminUser = User.findByUsername('admin') ?: new User( username: 'admin', password: springSecurityService.encodePassword('admin'), enabled: true).save(failOnError: true)

if (!adminUser.authorities.contains(adminRole)) { UserRole.create adminUser, adminRole } … } }