Search code examples
spring-bootspring-security-oauth2

Spring Boot - What event fired during Oauth2 authorization success


I have a spring boot app that uses oauth2 for authentication. I want to add an event listener to this and perform some custom action. I am unable to figure out what event is fired during the auth success in oauth2. Is it AuthenticationSuccessEvent?


Solution

  • The event triggered during OAuth2 Authorization Success is AuthorizedEvent. This is triggered in Spring code here. But in order to get this event, you need set the publishAuthorizationSuccess to true. The following can be done to get this working:

    The configuration changes:

    @EnableWebSecurity
    @EnableGlobalMethodSecurity(prePostEnabled = true)
    @Configuration
    public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    
    ....
        @Override
        protected void configure(HttpSecurity httpSecurity) throws Exception {
            http
            .authorizeRequests()
            .withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() {
                public <O extends FilterSecurityInterceptor> O postProcess(O fsi) {
                    fsi.setPublishAuthorizationSuccess(true);
                    return fsi;
                }
            })
        }
    ....
    }
    

    The code listeners:

    @Component
    @Slf4j
    public class HttpSessionEventListener {
     
        @EventListener(value = {AbstractAuthorizationEvent.class})
        public void onApplicationEvent(ApplicationEvent event) {
            if (event instanceof AuthenticationSuccessEvent) {
                Authentication auth = ((AuthenticationSuccessEvent) event).getAuthentication();
                if (auth.getPrincipal() instanceof UserCredential) {
                    log.debug("Login success with AuthenticationSuccessEvent");
                }
            } else if (event instanceof InteractiveAuthenticationSuccessEvent) {
                Authentication auth =  ((InteractiveAuthenticationSuccessEvent)event).getAuthentication();
                log.debug("Login success with InteractiveAuthenticationSuccessEvent");
            } else if (event instanceof AbstractAuthenticationFailureEvent) {
                Authentication auth = ((AbstractAuthenticationFailureEvent) event).getAuthentication();
                log.debug("Login failed with AbstractAuthenticationFailureEvent");
            } else if (event instanceof AuthorizedEvent) {
                Authentication auth =  ((AuthorizedEvent)event).getAuthentication();
                log.debug("Login success with AuthorizedEvent");
            } else if (event instanceof AuthorizationFailureEvent) {
                Authentication auth =  ((AuthorizationFailureEvent)event).getAuthentication();
                log.debug("Login fail with AuthorizationFailureEvent");
            }
        }
    }