Monday, December 31, 2012

HTTP basic authentication in Grails with Spring Security

Setting up HTTP basic authentication in Grails using Spring Security is pretty straightforward. Here's a quick how-to:
  1. grails create-app basicauthdemo
  2. cd basicauthdemo
  3. grails install-plugin spring-security-core
  4. grails s2-quickstart basicauthdemo User Role
  5. Edit grails-app/conf/Config.groovy and add two lines telling the Spring Security plugin to use HTTP basic authentication:
    grails.plugins.springsecurity.useBasicAuth = true
    grails.plugins.springsecurity.basic.realmName = "HTTP Basic Auth Demo"
    
  6. Edit grails-app/conf/BootStrap.groovy to setup a user and role:
    import basicauthdemo.*
    
    class BootStrap {
    
        def init = { servletContext ->
            def userRole = Role.findByAuthority("ROLE_USER") ?: new Role(authority: "ROLE_USER").save(flush: true)
            def user = User.findByUsername("tst") ?: new User(username: "tst", password: "foo", enabled: true).save(flush: true)
            UserRole.create(user, userRole, true)
        }
        def destroy = {
        }
    }
    
  7. grails create-controller hello
  8. Edit grails-app/controllers/basicauthdemo/HelloController.groovy and add a security annotation:
    package basicauthdemo
    
    import grails.plugins.springsecurity.Secured
    
    class HelloController {
    
        @Secured(['ROLE_USER'])
        def index() {
            render "Hello World!"
        }
    }
    
  9. grails run-app
  10. Open http://localhost:8080/basicauthdemo/hello
Presto!

2 comments:

  1. The User and Role classes are generated when you execute the "grails s2-quickstart basicauthdemo User Role" command.

    ReplyDelete