Christoph Hartmann on October 8th, 2008

For my current grails project I use the Spring Security Plugin (formerly Acegi Security) to secure my views and services. A tutorial at the Grails site gives a great overview how to install the grails plugin.

Right after installation I faced some issues:

Secure your Rest Services

This sounds quite easy due to a simple switch within the SecurityConfig.groovy. Just activate the BasicProcessingFilter. Now grails uses the Http Basic Authentification.

/** use basicProcessingFilter */
basicProcessingFilter = true

At the client side the code would like:

import sun.misc.BASE64Encoder
import groovy.util.XmlSlurper
def userid = "john.doe"
def password = "pass"
def url = "http://localhost:8080/CandyStreamServer/rest/gps/"
def conn = new URL(url).openConnection()
if (userid && password) {
	println "set authorization"
	// add HTTP authentication
       String encodedAuth = new BASE64Encoder().encode((userid + ":" + password).getBytes()) 
	conn.setRequestProperty("Authorization", "Basic " + encodedAuth)
def slurper = new XmlSlurper()
conn.requestMethod = "GET"
conn.doOutput = true
println "check connection"
def response
if (conn.responseCode == conn.HTTP_OK) {
	conn.inputStream.withStream {
		response = slurper.parse(it)
} else {
	response = conn.responseCod
println response

Retrieve the Current User

On the server side it may necessary to retrieve the current user. Spring Security offers a SecurityContextHolder. Unfortunately the securityContext.getAuthentication().getPrincipal(); does not return the Groovy user object. Instead the Spring Security Plugin uses its own user implementation that holds the Groovy user object. This is required due to Springs dependency on a specific interface.

The plugin provides a org.codehaus.groovy.grails.plugins.springsecurity.GrailsUser interface that extends the interface. To retrieve your Groovy user object just call getDomainClass()

SecurityContext securityContext = SecurityContextHolder.getContext();
def springUser = securityContext.getAuthentication().getPrincipal();
return springUser.getDomainClass()

Tags: , , ,

2 Responses to “Grails Spring Security”

  1. Hey Chris,

    I was wondering if you have tried deploying your app to a Tomcat server. My app deploys fine to tomcat server 5.5, but when i load my app with acegi security the deployment fails. Any ideas?

  2. Hey Daniel,

    I going to deploy my app to the Glassfish Application Server by next week. I havn’t tried the Tomcat server yet. Have you setup the database properly? What kind of error do you get? Grails use different configurations for test and production deployment. May this be the error?

Leave a Reply