How to Perform event on successful login via Spring Security in Grails
Some applications require to store and show last login of the user which is quite common. With this feature a user can verify the last login date and time upon successful login.
I would like to explain this through a use case – One of the administrative application on Grails required to hold last login date and time of the user, so that it can be shown to the user at the time of successful login.
Problem: By default spring security does not provide such feature of capturing last login time. Moreover, we did not have such properties in our domain which could persist user specific last login information.
Solution: Fortunately Spring is quite flexible framework so it is not a big deal to achieve this. Spring provides a authentication success listener which can perform specified action upon successful login of user.
Hence with the help of following configurations we can store user’s last login date time after successful authenticated login.
- Add following field’s in your User domain :-
class User
{
Date lastLoginDate
Date currentLoginDate
}
- Add following configurations in your /grails-app/conf/application.groovy (auto generated after installing Spring security Core plugin)
Enable your spring security events:-
grails.plugin.springsecurity.useSecurityEventListener = true
//An event to be triggered after successful authentication and login of user.
Modify your spring security successful authentication events:-
grails.plugin.springsecurity.onInteractiveAuthenticationSuccessEvent = { e, appCtx ->
User.withTransaction {
def user = User.findByIdAndIsDeleted(appCtx.springSecurityService.principal.id, false)
if (!user.isAttached())// Checks whether the domain instance is attached to a currently active Hibernate session.
user.attach()
user.lastLoginDate = user.currentLoginTime // update last login date
user.currentLoginDate = new Date() // update current login date
user.save(flush: true, failOnError: true)
}
}
Incase, you don’t need to retrieve the logged in user details, you can use
onAuthenticationSuccessEvent
3. That’s it, its done!
Now use user.lastLoginDate to show last login time.
Similarly, we can call an event on AuthenticationFailure/Unsuccessful Login via AbstractAuthenticationFailureEvent:
//An event to be triggered on AuthenticationFailure/Unsuccessful Login of user.
grails.plugin.springsecurity.onAbstractAuthenticationFailureEvent = { event, appCtx ->
// Action to be performed (Example : send e-mail)
}
thank you for this howling post, I am glad I noticed this site on yahoo.
This text is worth everyone’s attention. When can I find out more?
Good post! We are linking to this particularly great article on our website. Keep up the great writing.
Every weekend i used to visit this website, for the reason that i wish for enjoyment, for the reason that this this site conations truly pleasant funny information too.