Spring Security Basics

Example code is available on github.com/vaadin-on-grails/spring-security-basics.

We will create basic classes that are required to work with Spring in Grails application.

The first step before you continue with this tutorial, is to enable OSIV, as described in Open Session In View chapter to allow lazy loading in GORM. If you do not want OSIV in your project, set lazy to false on roles collection in User class.

Step 1

Create Role domain class that will represent a role assigned to a user. For example, a user can have multiple roles, like admin, client and so on.

grails create-domain-class app.security.Role
package app.security

class Role {

    String name

    static constraints = {
    }
}

Step 2

Create User domain class that will represent your user.

Then implement UserDetails interface from Spring Security and provide all the required fields.

Step 3

Because we need a user with some roles during development, create a new user with few roles in BootStrap.

Step 4

Now create UserService that will search for user by name and password in the database.

We will use this to login the users.

Step 5

Create your implementation of AuthenticationManager interface in src/groovy that will authentificate a user.

Open grails-app/conf/spring/resources.groovy and define a new bean. We have to have AuthManager under Spring controll otherwise autowired would not be done automatically.

Step 6

This can be done in many ways, but let's create a helper class Auth that will encapsulate authentification.

We do not have to have the login method defined as static. Instead, we can define a new bean and autoinject or use Grails.get(Auth) where needed.

Last updated

Was this helpful?