[英]What is the best approach to implement token based authentication
I have a Spring Boot application which acts as a client of a server.我有一个 Spring 引导应用程序,它充当服务器的客户端。 It requests data from the server after being authenticated.
它在通过身份验证后向服务器请求数据。 The server uses token based authentication and changes the token every 15 minutes.
服务器使用基于令牌的身份验证并每 15 分钟更改一次令牌。 What would be the most efficient and cleaner way for my client application to acquire new token?
我的客户端应用程序获取新令牌的最有效和更清洁的方式是什么? By default I use multithreading and in the background of my main application I request new token every 15 minutes, but it is not efficient.
默认情况下,我使用多线程,并且在我的主应用程序的后台,我每 15 分钟请求一次新令牌,但效率不高。 So are there other approaches like reactive programming or etc to do this?
那么是否有其他方法,如反应式编程等来做到这一点? please note that my application needs to send a large number of requests to the server at a time so I cant check the time of acquiring the token every time I send a request.
请注意,我的应用程序需要一次向服务器发送大量请求,因此我无法在每次发送请求时检查获取令牌的时间。
I would use @Retryable
with RetryOperationsInterceptor
or ExceptionClassifierRetryPolicy
.我会将
@Retryable
与RetryOperationsInterceptor
或ExceptionClassifierRetryPolicy
一起使用。
Here's how it goes:事情是这样的:
We have a @Component
singleton to hold authentication token:我们有一个
@Component
singleton 来保存身份验证令牌:
@Component
public class AuthenticationHolder {
private String token;
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
}
Make the @Component
that actually requests data from the server not aware of authentication process.使实际从服务器请求数据的
@Component
不知道身份验证过程。 It only has a reference to your AuthenticationHolder
singleton, and in the method it tries to request data (obviously annotated with @Retryable
, it retrieves the token and makes the request. If it fails with a bad response code from the server, make it throw an exception, and it will retry. In between the retries, make your RetryOperationsInterceptor
renew the authentication token.它只引用了您的
AuthenticationHolder
singleton,并且在它尝试请求数据的方法中(显然用@Retryable
注释,它检索令牌并发出请求。如果它因来自服务器的错误响应代码而失败,让它抛出一个异常,它会重试。在重试之间,让你的RetryOperationsInterceptor
更新身份验证令牌。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.