I’ve really fallen in love with eventing architectures of late. Fire and forget, and let some other decoupled class (or classes) listen in and do what makes sense to it. I love the extensibility! And the cleanliness!

I’ve been using a lot of the new EE6 Event stuff and applying these kind of ideas for fun and profit. If only there was a Grails equivalent… and there is! It’s found in the Event Bus features of the amazing platform-core plugin!

I’m currently learning and writing about the eventing features of Platform Core for Grails in Action 2 and been having a great time (the messaging chapter will now be “Events, Messaging and Scheduling” to make sure it’s given good coverage). One of the features that I am experimenting with is integrating Spring Security logon events with an Audit Service that is listening for those events (just to get a feel for how messages flow).

Spring Security already has its own eventing magic, and cute ways to listen in, so I’m really just adapting the stuff that’s already in there. First, we raise the event on the Event Bus by wiring up a listener in Config.groovy:

grails.plugins.springsecurity.useSecurityEventListener = true
grails.plugins.springsecurity.onAuthenticationSuccessEvent = { evt, appCtx ->
    appCtx.grailsEvents.event 'security', 'onUserLogin' , evt
}

In this sample I’m raising a new event, with a “security” namespace, and a “onUserLogin” event, and attaching the incoming AuthenticationSuccessEvent event that Spring Security passes in (so you can have access to the ipaddress or any other security magic you might want).

Now it’s just the small matter of wiring up a listener. Let’s throw together an AuditService to give you a look:

package com.grailsinaction

import org.springframework.security.authentication.event.AuthenticationSuccessEvent

class AuditService {

    @grails.events.Listener(namespace = "security")
    def onUserLogin(AuthenticationSuccessEvent loginEvent){
        log.error "We appeared to have logged in a user: ${loginEvent.authentication.principal.username}"
    }

}

With our Listener annotation marking this method as a listener in the security namespace, the Event Bus will match the method name to the event name, and pass in the argument. Of course, you could do all this with native Spring Security Events with custom code and  handlers, but I really like the was Event Bus is shaping up as a general Grails eventing infrastructure which can be used across your application.

I’d imagine that as the Security features within Platform Core develop, you’ll probably see the security plugins raise these kind of events natively on the bus, but for now, this is a cute little way to glue everything together.

Go forth and event! (and if you want to find out more, you can always sign up to the Grails In Action MEAP)