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:
Create basic grails application:
1grails create-app mongo-securityInstall Spring Security Core plugin:
1grails install-plugin spring-security-coreGenerate User and Role domain classes:
1grails s2-quickstart com.example User RoleAdd 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 = { } }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>Start grails application and try to login with admin/admin and logout
1grails run-app
Now lets try to make this application work on top of mongodb instead of
hibernate memory database.
For this we will need mongodb grails plugin, lets install it:
1grails install-plugin mongodbWe also need to specify that our domain classes should be persisted into MongoDB, add the following line inside each domain class:
1static 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