Step by step tutorial on using spring security core with Grails 3.2.5 and Mongodb

Step 1: Create new project based on Grails 3.2.5.

Make sure you have Jdk 8 installed on your system. The configuration should look like this when you type grails -version on your command line.

Create Grails project using the command given below:

grails create-app sample

sample is the name of the application. Once the application dependencies are downloaded follow the below steps.

Step 2: Install the mongodb and spring security using gradle dependency management which can be done by editinng the file gradle.build file in the root of the project.

compile 'org.grails.plugins:mongodb:6.0.7'
compile 'org.grails.plugins:spring-security-core:3.1.1'

Copy and paste the above code inside the dependencies block. Make sure Mongodb is installed and its server instance is up.

Step 3: Configure the mongodb connection.

grails:
    mongodb:
        host: "localhost"
        port: 27017
        username: "username"
        password: "password"
        databaseName: "databasename"

 

Copy and paste the above code by editing the file grails-app/conf/application.yml.

Step 4: Configure Spring Security Core.

grails s2-quickstart com.example SecUser SecRole

 

Run the above code from the project root, if everything goes well you will see the below response on the terminal along with this 3 domain class will be created name as SecUser, SecRole, SecUserSecRole inside the package com.example.

************************************************************

* Created security-related domain classes. Your            *

* grails-app/conf/application.groovy has been updated with *

* the class names of the configured domain classes;        *

* please verify that the values are correct.               *

************************************************************

 

Next edit the grails-app/conf/application.groovy file and paste the configuration code mentioned below:

grails.plugin.springsecurity.logout.afterLogoutUrl = '/'
grails.plugin.springsecurity.logout.postOnly = false
grails.plugin.springsecurity.successHandler.defaultTargetUrl = '/home'
grails.plugin.springsecurity.successHandler.ajaxSuccessUrl = '/home'
grails.plugin.springsecurity.securityConfigType = 'InterceptUrlMap'
grails.plugin.springsecurity.interceptUrlMap = [
               [pattern: '/',               access: ['permitAll']],
               [pattern: '/home/**',        access: ['ROLE_USER']],
               [pattern: '/error',          access: ['permitAll']],
               [pattern: '/index',          access: ['permitAll']],
               [pattern: '/index.gsp',      access: ['permitAll']],
               [pattern: '/shutdown',       access: ['permitAll']],
               [pattern: '/assets/**',      access: ['permitAll']],
               [pattern: '/**/js/**',       access: ['permitAll']],
               [pattern: '/**/css/**',      access: ['permitAll']],
               [pattern: '/**/images/**',   access: ['permitAll']],
               [pattern: '/**/favicon.ico', access: ['permitAll']],
               [pattern:  '/login/**', access:['IS_AUTHENTICATED_ANONYMOUSLY']],
               [pattern: '/**',         access: ['IS_AUTHENTICATED_FULLY']],
]

 

Step 4: Edit the domain class so that we can use it with mongdb.

You can delete the third file name as SecUserSecRole.groovy file since Mongodb doesn’t support many to many releationship, edit the SecUser.groovy file as described below:

class SecUser implements Serializable {

        static mapWith = "mongo" // when using hibernate and mongodb both we need to include this property

        private static final long serialVersionUID = 1
        transient springSecurityService
        String username
        String password
        boolean enabled = true
        boolean accountExpired
        boolean accountLocked
        boolean passwordExpired
        Set<SecRole> authorities // A Set for storing role
        static embedded = ['authorities'] // mongodb supports embedded document

        Set<SecRole> getAuthorities() {
//             SecUserSecRole.findAllBySecUser(this)*.secRole // delete the old code
               this.authorities // use this code
        }

 

Edited lines are having proper comments. Make sure that you edit SecRole.groovy file and add static mapWith = "mongo" property.

Step 5: Create sample user and role on application startup by editing bootstrap.groovy file.

def init = { servletContext ->

     def adminRole = new SecRole(authority: 'ROLE_ADMIN').save()
     def userRole = new SecRole(authority: 'ROLE_USER').save()
     new SecUser(username: 'admin', password: 'password',
                email: 'test@email.com', authorities: [adminRole,userRole]).save(flush:true)
     new SecUser(username: 'test', password: 'password',
                email: 'test@email.com', authorities: [adminRole,userRole]).save(flush:true)

}

 

Step 6: Create a controller named home using the command described below:

grails create-controller com.example.home // com.example will be the package and home will become the controller name

Edit the home controller and paste the code given below:

def index() {
     def response = ['message':'hello world']
     render response as JSON
}

Next will can run the application using grails run-app command from the project root. Open the application on the browser and try to navigate to http://localhost:8080/home

You will be asked to provide the credential

Provide the username and password set in the bootstrap file, once successfully done you will be redirected to home page.

To logout you can directly hit the url http://localhost:8080/logout