我有一个使用oauth2进行身份验证的spring boot应用程序。我想为此添加一个事件侦听器并执行一些自定义操作。我无法弄清楚在oauth2中的身份验证成功期间触发了什么事件。是AuthenticationSuccessEvent
吗?
答案 0 :(得分: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");
}
}
}