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:

    1
    
    grails create-app mongo-security
    

  2. Install Spring Security Core plugin:

    1
    
    grails install-plugin spring-security-core
    

  3. Generate User and Role domain classes:

    1
    
    grails s2-quickstart com.example User Role
    

  4. Add code to create user on grails application startup:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    
    // 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 = {
        }
    }
    

  5. Add code snippet to index.gsp right before controller-list div for showing whether user is logged in or not:

    1
    2
    3
    4
    5
    6
    
    <sec:ifLoggedIn>  
    Logged in as <sec:username/>  
    </sec:ifLoggedIn>  
    <sec:ifNotLoggedIn>  
    Please login  
    </sec:ifNotLoggedIn>
    

  6. Start grails application and try to login with admin/admin and logout

    1
    
    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:

    1
    
    grails install-plugin mongodb
    

  2. We also need to specify that our domain classes should be persisted into MongoDB, add the following line inside each domain class:

    1
    
    static mapWith = "mongo"
    

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.

Victor Vlasenko,
SysGears

Comments