Spring 安全 OAuth2 身份验证成功后如何调用自定义代码
How to Call Custom Code Following Successful Spring Security OAuth2 Authentication
我创建了一个 OAuth2 资源服务器,它接受并验证 JWT 令牌并从声明中提取用户信息以确定用户信息,例如用户名和权限。我主要使用 spring-security-oauth2-autoconfigure 库来完成此操作。
用户通过身份验证后,我想调用自定义代码,在 Kafka 流上放置一条消息以指示用户已登录。执行此操作最合适的位置在哪里?
我可以在 OAuth2AuthenticationManager.authenticate
中执行此操作,但我必须扩展 class 并覆盖该方法,然后将其连接起来。似乎 Spring 应该有已经有一些东西可以处理这个问题。
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());
}
}
我创建了一个 OAuth2 资源服务器,它接受并验证 JWT 令牌并从声明中提取用户信息以确定用户信息,例如用户名和权限。我主要使用 spring-security-oauth2-autoconfigure 库来完成此操作。
用户通过身份验证后,我想调用自定义代码,在 Kafka 流上放置一条消息以指示用户已登录。执行此操作最合适的位置在哪里?
我可以在 OAuth2AuthenticationManager.authenticate
中执行此操作,但我必须扩展 class 并覆盖该方法,然后将其连接起来。似乎 Spring 应该有已经有一些东西可以处理这个问题。
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());
}
}