Grails 3 Spring Security Core and MongoDB Authentication Tutorial

by Didin J. on Dec 27, 2016 Grails 3 Spring Security Core and MongoDB Authentication Tutorial

How to integrated Grails 3 Spring Security Core and MongoDB plugins for web application authentication in step by step tutorial.

Previously, we have learned how to use Grails 3 with MongoDB. Now, we will continue to add an authentication using Spring Security Core Plugin. This is a combination of Grails 3 Spring Security Core and MongoDB.

1. Creating Application

Will be better if we started from scratch. Let's create the new application, go to project folder then create new Grails application.

grails create-app grails3-authentication

This command will create new Grails application named with "grails3-authentication". Next, go to new project folder created.

cd grails3-authentication

 


2. Configuring Application Plugins

Next, we have to add spring-security-core and mongodb plugins. Open file build.gradle in root of project with your favorite text editor or IDE. Then, add this lines in main depencies.

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

Comment this lines in dependencies.

// compile "org.grails.plugins:hibernate4"
// compile "org.hibernate:hibernate-ehcache"
// runtime "com.h2database:h2"

Also this line in buildscript dependencies.

// classpath "org.grails.plugins:hibernate4:5.0.10"

Compile your project using this command.

grails compile


3. Create User and Role Domain

Next, we have to create user and role domain using this command.

grails s2-quickstart com.djamblog.auth User Authority

This command will create User and Authority domain which Authority is Role. Also, relation between this 2 domain will created with name UserAuthority.

| Creating User class 'User' and Role class 'Authority' in package 'com.djamblog.auth'
| Rendered template Person.groovy.template to destination grails-app/domain/com/djamblog/auth/User.groovy
| Rendered template Authority.groovy.template to destination grails-app/domain/com/djamblog/auth/Authority.groovy
| Rendered template PersonAuthority.groovy.template to destination grails-app/domain/com/djamblog/auth/UserAuthority.groovy
|
************************************************************
* 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.               *
************************************************************

Because we are using MongoDB which not supported many to many relationships, we have to modify some generated files.

1. Delete UserAuthority.groovy, it's not longer used.
2. Remove this lines inside User.groovy.

Set<Authority> getAuthorities() {
  UserAuthority.findAllByUser(this)*.authority
}

3. Add this line to User.groovy in a place where above code removed.

Set authorities

static embedded = ['authorities']

Now, we have to create a test user for that created domain by adding some lines in grails-app/init/Bootstrap.groovy.

def init = { servletContext ->
  def role = Authority.findByAuthority("ROLE_USER")?:new Authority(authority:"ROLE_USER").save(flush:true)
  def user = User.findByUsername("graeme")?:new User(username:"graeme",password:"q1w2e3r4").save(flush:true)

  if (!user.authorities) {
    user.authorities = [role]
    user.save flush:true
  }
}

Don't forget to import that domain in the top of Bootstrap.groovy file.

import com.djamblog.auth.*

In Bootstrap.groovy we have added a role and a user. A role is "ROLE_USER", a role name must be "ROLE_" prefix. User has embedded collection to "ROLE_USER".


4. Configuring Spring Security Core

Now, we have to make a domain that will be secured by Spring Security. It means every access to that domain, controller and view must be authenticated a user. For it, we create the new domain.

grails create-domain-class com.djamblog.Salary

This command will create new domain class named Salary. Fill this domain class with fields below.

package com.djamblog

class Salary {

    String employeeName
    String employeePosition
    Double basicSalary
    Double healthAllowance
    Double positionAllowance
    Double transportAllowance
    Date createDate

    static constraints = {
    }
}

Next, generate controller and views for this domain class.

grails generate-all com.djamblog.Salary

This command will create full function of CRUD by generating controller and views. To make Salary controller secured to "ROLE_USER" add this line in grails-app/conf/Application.groovy.

grails.plugin.springsecurity.controllerAnnotations.staticRules = [
    [pattern: '/',               access: ['permitAll']],
    [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: '/salary/**',        access: ['ROLE_USER']]
]

Next, test your spring security by running application.

grails run-app

Grails 3 Spring Security Core and MongoDB - home page

As you can see, at left bottom of the screen there is salary, login and logout controller. If you click salary controller, it will redirect to login page. Supply username and password that previously added in Bootstrap.groovy.

Grails 3 Spring Security Core and MongoDB - Login page

If you log in with valid credentials, it will be redirected to salary page.


5. Add Logout Function to Page

By default, logout using post. To make logout using standard link add this config inside grails-app/conf/Application.groovy.

grails.plugin.springsecurity.logout.postOnly = false

Now, open grails-app/views/layout/main.gsp then add this tag inside navbar.

<div class="navbar-collapse collapse" aria-expanded="false" style="height: 0.8px;">
    <ul class="nav navbar-nav navbar-right">
        <g:pageProperty name="page.nav" />
        <sec:ifLoggedIn>
          <li><a><sec:username /></a></li>
          <li>
            <g:link controller="logout">Logout</g:link>
          </li>
        </sec:ifLoggedIn>
    </ul>
</div>

Stop the application and run again. Click on salary controller then login again. You can see username name logout button at the right top of the screen.

Grails 3 Spring Security Core and MongoDB - Secured Page

When you click logout button it will return to home page.

Now, you might say these things too easy. Right, this is Grails 3 and it made for boost your web development faster and powerful.

Thanks.

Loading…