Spring Boot-Oauth2授权成功期间触发了什么事件

问题描述 投票:0回答:1

我有一个使用oauth2进行身份验证的spring boot应用程序。我想为此添加一个事件侦听器并执行一些自定义操作。我无法弄清楚在oauth2中的身份验证成功期间触发了什么事件。是AuthenticationSuccessEvent吗?

spring-boot spring-security-oauth2
1个回答
1
投票

OAuth2授权成功期间触发的事件为AuthorizedEvent。这在Spring代码here中触发。但是为了获得此事件,需要将publishAuthorizationSuccess设置为true。要使此工作正常,可以执行以下操作:

配置更改:

@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;
            }
        })
    }
....
}

代码侦听器:

@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 success with AuthorizationFailureEvent");
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.