【问题标题】:How to Call Custom Code Following Successful Spring Security OAuth2 Authentication如何在成功的 Spring Security OAuth2 身份验证后调用自定义代码
【发布时间】:2018-11-09 22:42:28
【问题描述】:
我创建了一个 OAuth2 资源服务器,它接受和验证 JWT 令牌并从声明中提取用户信息,以确定用户信息,例如用户名和权限。我在很大程度上使用spring-security-oauth2-autoconfigure 库完成了这项工作。
用户通过身份验证后,我想调用自定义代码,将消息放在 Kafka 流上以指示用户已登录。在哪里执行此操作最合适?
我可以在OAuth2AuthenticationManager.authenticate 中执行此操作,但我必须扩展该类并覆盖该方法,然后将其连接。看起来 Spring 应该已经有一些东西可以处理这个问题。
【问题讨论】:
标签:
java
spring
spring-security
spring-security-oauth2
【解决方案1】:
OAuth2AuthenticationProcessingFilter,调用问题中提到的authenticate方法,有一个成员叫eventPublisher。它的方法包括publishAuthenticationSuccess,在认证成功后调用。
要将自定义代码与此绑定,请创建一个事件侦听器,该侦听器将被 Spring 作为 bean 拾取。像这样的:
@Component
public class MyAuthenticationEventListener implements ApplicationListener<AuthenticationSuccessEvent> {
private static final Logger logger = LoggerFactory.getLogger(MyAuthenticationEventListener.class);
@Override
public void onApplicationEvent(AuthenticationSuccessEvent authenticationSuccessEvent) {
logger.info("User logged in: " + authenticationSuccessEvent.getAuthentication().getName());
}
}