Creating a Secure Grails Application Powered by MongoDB

There is a twist: use more specific data storage engines than an RDBMS. 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 a basic secure Grails application powered by MongoDB.

Let’s start by creating a basic secure Grails application using Hibernate, then adapt it to MongoDB. This is a very easy task that can be accomplished with the following steps:

  1. Create a basic Grails application:
grails create-app mongo-security
  1. Install Spring Security Core plugin:
grails install-plugin spring-security-core
  1. Generate the User and Role domain classes:
grails s2-quickstart com.example User Role
  1. Add code to create a user on the 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 = {
    }
}
  1. Add code snippet to index.gsp right before the controller-list div for showing whether the user is logged in or not:
<sec:ifLoggedIn>  
Logged in as <sec:username/>  
</sec:ifLoggedIn>  
<sec:ifNotLoggedIn>  
Please login  
</sec:ifNotLoggedIn>  
  1. Start the Grails application and try to log in with admin/admin and log out
grails run-app

Now, let’s try to make this application work on top of MongoDB instead of the Hibernate in-memory database.

  1. For this, we will need the MongoDB Grails plugin. Let’s 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"

Then, check that you can log in with admin again and that the MongoDB database is created with a document for the admin user in the users collection.