Sunday, April 20, 2014

Default Login Screen with Spring Security

The spring security plugin enables some amount of default application security without any substantial coding. Here was my 30 minute experiment tonight:

> grails create-app sectest

>cd sectest

In grails-app/conf/BuildConfig.groovy I added the following under the "repositories" section:

mavenRepo "http://repo.spring.io/milestone/"

and under the "plugins" section added:

compile ':spring-security-core:2.0-RC2'

Then:

> grails run-app

I did this to import the plugin. I probably could have just build it. Anyway with the plugin installed I did:

> grails stop-app

> grails s2-quickstart com.homesteadgaming User Role

> grails run-app

Then browsing to localhost:8080/sectest, I saw the login controller listed. Clicking on the login controller gave me this default screen:

My login attempts failed with a sensible error, which is expected since there are no users in my default database.

So next I populated a default user which I hear you can do by editing BootStrap.groovy. That looks like this:

class BootStrap {

    def init = { servletContext ->

    def adminUser = new com.homesteadgaming.User(
                username: 'admin',
                password: 'admin',
                enabled: true).save(failOnError: true)
    }
    def destroy = {
    }
}

And now after restarting the app again, I can login with admin/admin. That's nice.


5 comments:

  1. I tried to do the exact same steps Sten did above. All went well until I tried doing "grails start-app" after running the s2-quickstart script. When I did that, instead of the app starting as it did before, I got this:

    $ grails start-app
    | Script 'StartApp' not found, did you mean:
    1) TestApp
    2) S2Quickstart
    3) Stats
    4) StopApp
    5) DbmStatus
    > Please make a selection or enter Q to quit:

    Not sure what happened there...


    P.S. How did Sten embed links in his post, and format some text in a monospace "typewriter" font?

    ReplyDelete
    Replies
    1. Hey, I got it! That "grails start-app" in Sten's post looks like it might be a typo -- at least, when I did "grails run-app" instead, it worked, as did the remaining steps in his post. Cool.

      Delete
    2. Yes, 'grails run-app'. Thanks display_name. I will update the post.

      Delete
  2. It is pretty cool. I was able to follow your instructions and get a login page. The logout controller gives me an error though. Is that expected?

    ReplyDelete
    Replies
    1. Work around for this issues is at the following location:

      http://jhtechservices.com/2014/07/grails-spring-security-plugin-adding-a-logout-link/

      Delete