In a previous post I explained how the JForum SSO plug-in can be used to secure a JForum application.

In this post I’ll demonstrate how the same principle can be applied in a Grails application.

Basically, just about everything from the previous post is the same, except for how the filtering of requests and the sending of the cookies from the host application is performed.

In Grails it is simple to write web filters. Just create a Groovy class with a name that ends with ‘Filters’ in your conf folder and add closures that define the filtering behaviour:

class MyFilters {
    def filters = {
        myFirstFilter(controller: '*', action: '*') {
            before = {
                  //code here is executed before the controller has been accessed
            }
            after = {
                  //code here is executed after the controller has been accessed
            }
            afterView = {
                  //code here is executed after the view has been rendered
            }
        }
    }
}

in this example, there is a single filter called ‘myFirstFilter’ that will be applied to all actions on all controllers, which illustrates the three filtering points available in Grails.

So given a Grails application service called ‘userService’ that returns us a domain object for the currently logged in user, then we could write a cookie sending filter which uses the SSO plug-in like this:

class SecurityFilters {
  def userService;

  def filters = {
    jForumSecureSSOCookie(controller: '*', action: '*') {
      after = {
        if (userService.getUser()) {
          def user = userService.getUser();
          def encryptedValues = SecurityTools.getInstance().encryptCookieValues(user.email, user.username);

          Cookie c = new Cookie(SecurityTools.FORUM_COOKIE_NAME, encryptedValues)
          c.maxAge = -1;
          c.path = "/"
          c.comment = "SSO cookie for language spider forum"
          response.addCookie(c)
        } else {
          //user is not logged in so kill the cookie
          //(removing cookies does not work reliably in all browsers)
          Cookie c = new Cookie(SecurityTools.FORUM_COOKIE_NAME, "")
          c.maxAge = -1;
          c.path = "/"
          c.comment = "SSO cookie for language spider forum"
          response.addCookie(c)
        }
      }
    }
  }
}

Because, Grails runs in a Java environment, all other configuration, including the JAR file deployment remain as discussed in the previous post.