Events can be very useful in application development. When we want to intercept a particular action throughout an application, we can make use of events. Let’s take an example of spring security event InteractiveAuthenticationSuccessEvent. When a user is authenticated successfully, spring security fires InteractiveAuthenticationSuccessEvent which has the Authentication object using which we can fetch user details. It can be used to perform some action when a user is logged in like storing login history of a user, maintaining last login timestamp etc..
Before we capture events, we have to enable spring security events using the following line in Config.groovy :
grails.plugin.springsecurity.useSecurityEventListener = true
Here is a code to capture login event:
package org.jft import org.springframework.context.* import org.springframework.security.authentication.event.InteractiveAuthenticationSuccessEvent class LoginEventListener implements ApplicationListener { @Override void onApplicationEvent(ApplicationEvent event) { if (event instanceof InteractiveAuthenticationSuccessEvent) { String username = (String)event.getAuthentication().getPrincipal() // you code goes here............. } } }
We also need to register our class LoginEventListener as a spring bean in resources.groovy:
import org.jft.LoginEventListener beans = { loginEventListener(LoginEventListener) }
You can write your own implementation in LoginEventListener and see your code in action 😉
Recent Comments