简体   繁体   English

Spring Boot JWT身份验证:登录和注销后触发方法

[英]Spring Boot JWT Authentication: trigger a method after login and logout

I am implementing a REST API with Spring Boot and I am securing it with JWT and Oauth 2. 我正在使用Spring Boot实现REST API,并通过JWT和Oauth 2保护它。

I have no problems with authentication and producing an access token. 身份验证和生成访问令牌没有问题。

Now, I want to perform an action after the user gets authenticated and another different action when the access token is expired and/or user logs out. 现在,我想在用户获得身份验证之后执行一个操作,并在访问令牌到期和/或用户注销时执行另一个不同的操作。

How can I trigger a method after login and logout/access token expiry in Spring Boot? 在Spring Boot中登录和注销/访问令牌到期后,如何触发方法?

Any help would be appreciated. 任何帮助,将不胜感激。

Spring boot has built-in support for ApplicationEvent s and ApplicationListener s. Spring Boot内置了对ApplicationEventApplicationListener的支持。 If you need them to be async you can use ApplicationEventMulticaster to "emit" the event, eg see https://www.baeldung.com/spring-events . 如果需要它们异步,则可以使用ApplicationEventMulticaster来“发出”事件,例如,请参见https://www.baeldung.com/spring-events

For example, upon logout, you can have applicationEventMulticaster.multicastEvent(new OnLogoutCustomEvent(param1, param2)) (where applicationEventMulticaster is an autowired ApplicationEventMulticaster and OnLogoutCustomEvent extends ApplicationEvent ) and then have a LogoutCustomListener (implements ApplicationListener<OnLogoutCustomEvent> ) to handle the event. 例如,注销后,您可以让applicationEventMulticaster.multicastEvent(new OnLogoutCustomEvent(param1, param2)) (其中applicationEventMulticaster是自动装配的ApplicationEventMulticasterOnLogoutCustomEvent扩展ApplicationEvent ),然后让LogoutCustomListener(实现ApplicationListener<OnLogoutCustomEvent> )来处理事件。

For the token timeout I think you need something like ScheduledExecutorService to trigger your logic at the time of expiry. 对于令牌超时,我认为您需要诸如ScheduledExecutorService以在到期时触发您的逻辑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM