Activating Authorization Success Event Publish Feature

Spring Security publishes various authentication and authorization events during its security checks. Spring managed beans which implement ApplicationListener interface or beans with methods annotated with @EventListener can consume those events within the application. One of those security related events is AuthorizedEvent which indicates that user request is allowed to access secure web resource. It is, however, disabled by default.

In this post, I will try to explain to how to activate publishing AuthorizedEvents whenever successful authorization occurs within your system. Authorization events are published by FilterSecurityInterceptor bean which is configured by Spring Security <http> element by default. It has a property setter, namely setPublishSuccessAuthorization(..) through which publishing authorization success events are activated. Unfortunately, Spring Security provides no way to pass value to this property within the <http> element. There are, however, several ways to change this property value into true and let Spring Security to publish events after successful authorization operations as well.

One way is not to employ <http> element at all and configure Spring Security filter chain and and FilterSecurityInterceptor bean via explicit bean definitions. However, we will lose advantages of configuring Spring Security Filter Chain via security namespace elements that way.

The other way is a lot easier. It also exploits Spring’s event mechanism itself. Here we keep regular Spring Security namespace configuration, and only we need to create a bean which handles Spring’s built-in ContextRefreshedEvent. When Spring ApplicationContext is ready to use, built-in ContextRefreshedevent is fired, and we can perform a bean lookup for FilterSecurityInterceptor bean which is already defined via <http> element. When we obtain that bean it is only required to invoke setPublishSuccessAuthorization(..) to enable authorization success events. That’s all!

@Component
public class SecurityConfigurer {

	@Autowired
	private ApplicationContext applicationContext;

	@EventListener
	public void handle(ContextRefreshedEvent event) {
		FilterSecurityInterceptor fsi = applicationContext
				.getBean(FilterSecurityInterceptor.class);
		fsi.setPublishAuthorizationSuccess(true);
	}

	@EventListener
	public void handle(AuthorizedEvent event) {
		System.out.println(event.getSource());
		System.out.println(event.getAuthentication());
		System.out.println(event.getConfigAttributes());
	}
}

I hope, you will like that way, and employ it in your projects whenever you need to activate publishing authorization success events within your system.