Creating secure Grails application powered by MongoDB

There is some twist to use more specific data storage engines than RDBMS. The mongodb is a modern feature-rich non-RDBMS database. It can be used with grails quite well, though some special care should be taken. In this post we will create base secure grails application powered by mongodb.

Lets start with creating basic secure grails application using hibernate and then adopt it to using mongo db. This is very easy task which can be accomplished using the following steps:

  1. Create basic grails application:
grails create-app mongo-security
  1. Install Spring Security Core plugin:
grails install-plugin spring-security-core
  1. Generate User and Role domain classes:
grails s2-quickstart com.example User RoleCode language: CSS (css)
  1. Add code to create user on grails application startup:
// BootStrap.groovy
import com.example.User

class BootStrap {
    def init = { servletContext ->
        def admin = User.findByUsername("admin") ?:
            new User(username: "admin",
                    password: "admin",
                    enabled: true, accountLocked: false,
                    accountExpired: false, passwordExpired: false).save(flush: true)

        if (admin.hasErrors()) {
            admin.errors.each { println it }
        }
    }

    def destroy = {
    }
}Code language: JavaScript (javascript)
  1. Add code snippet to index.gsp right before controller-list div for showing whether user is logged in or not:
<sec:ifLoggedIn>  
Logged in as <sec:username/>  
</sec:ifLoggedIn>  
<sec:ifNotLoggedIn>  
Please login  
</sec:ifNotLoggedIn>  Code language: HTML, XML (xml)
  1. Start grails application and try to login with admin/admin and logout
grails run-app



Now lets try to make this application work on top of mongodb instead of hibernate memory database.

  1. For this we will need mongodb grails plugin, lets install it:
grails install-plugin mongodb
  1. We also need to specify that our domain classes should be persisted into MongoDB, add the following line inside each domain class:
static mapWith = "mongo"Code language: JavaScript (javascript)

And after that you can check that you are able to login with admin again and that mongo database is created with document for admin user in user collection.