Registering Callback Closures

When you want to hook business logic on certain Spring Security Core events, you can edit grails-app/conf/Config.groovy and add something like the following:

When using this, it is important to set grails.plugins.springsecurity.useSecurityEventListener to true as shown in the first line above.
As per the documentation in the plugin docs:
  • When a user authenticates, Spring Security initially fires an AuthenticationSuccessEvent (onAuthenticationSuccessEvent callback). This event fires before the Authentication is registered in the SecurityContextHolder, which means that the springSecurityService methods that access the logged-in user will not work.
  • Later in the processing a second event is fired, an InteractiveAuthenticationSuccessEvent (onInteractiveAuthenticationSuccessEvent callback), and when this happens the SecurityContextHolder will have the Authentication.
  • This means if you don't need to retrieve the logged in user, you can hook toonAuthenticationSuccessEvent. Otherwise, hook withonInteractiveAuthenticationSuccessEvent.

Example

This example will log all successful logins to a database table.
Model
I assume that the model for the user is SecUser as discussed here.
The logs will be saved in SecUserLog data model.

Service:
I created a service to wrap all business logic to the SecUserLog domain. I used a service to show later how to access this inside Config.groovy.
Note that the service securityService is from the Spring Security Core Plugin.
Config.groovy entries
This are the code I added in Config.groovy

The appCtx object is the application context, which can be used to look up Spring managed beans - that includes the services. After that, you can use the service as you please.

No comments:

Post a Comment