Skip to content

Enable MethodSecurityInterceptor to publish AuthorizedEvent

I want to audit successful authorisations in a spring-boot 2.X application. So I tried to start listening for AuthorizedEvent but that event isn’t published until AbstractSecurityInterceptor.publishAuthorizationSuccess is set to true.

This application mostly uses @Secured and @PreAuthorize/@PostAuthorize annotations so the interceptor I’m trying to listen to is MethodSecurityInterceptor (It also gives me security roles being authorized against that FilterSecurityInterceptor does not)

I don’t see any way to configure MethodSecurityInterceptor and enable event publishing other than through BeanPostProcessor which feels fragile.

Is there a better way to enable MethodSecurityInterceptor.publishAuthorizationSuccess than through BeanPostProcessor?

Answer

Posted an issue in the spring-security github repo.

According to the reply there is no better way to configure MethodSecurityInterceptor right now and they are making major changes in that part of the code so no point in improving anything right now.

So best way to configure MethodSecurityInterceptor is through a BeanPostProcessor like below:

@Component
public class MethodSecurityInterceptorPostProcessor implements BeanPostProcessor {

    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (bean instanceof MethodSecurityInterceptor) {
            ((MethodSecurityInterceptor) bean).setPublishAuthorizationSuccess(true);
        }
        return bean;
    }
}