Monday 10 August 2015

Adding a logout listener in Grails and spring-security-core

Recently I've had to log certain activities the users were performing in an application. One particular action was logging out.
I'm using spring-security-core plugin to handle authentication and security.
I have done this in the past so I thought I better document this in a way that I don't have to dig up my old code from the annals of... well ~\dev\archived.

Taking advantage of Listeners

I don't want this cluttering my application logic and since Grails is a spring application, I turned my attention to ApplicationListeners. You could argue that I could have made use of filters but if the logout handler already emits an event when a user is successfully logged out, why not use it?
So, lets start our (short) implementation of this. First you will have to tell spring-security to publish http session events so that you can catch them later. In order to do so, add the following line to your grails-app/conf/Config.groovy:
grails.plugin.springsecurity.useHttpSessionEventPublisher = true
Now you have to implement your listener: import org.springframework.context.ApplicationListener import org.springframework.security.core.session.SessionDestroyedEvent public class MyLogoutEventListener implements ApplicationListener<SessionDestroyedEvent> { @Override public void onApplicationEvent(SessionDestroyedEvent event){ /*Your code here*/ } } (If you're not sure where to put it, place it in your src/groovy/ directory)
And then you need to register this bean in grails-app/conf/spring/resources.groovy beans = { myLogoutEventListener(MyLogoutEventListener) } Note: Your MyLogoutEventListener will listen for any SessionDestroyedEvent which means that when someone logs in, the listener will trigger as the anonymous session has been destroyed, so remember to check if the session is anonymous.

No comments:

Post a Comment