如何刷新jwt并再次请求原始请求并获得响应?
当“access_token”过期时,如何处理“刷新令牌”?
我知道它是如何运作的。但我想知道的是实现一次并将其应用于所有 API。
当访问令牌过期时,所有 API 都会被阻止(401),并且需要使用刷新令牌请求新令牌。
因此,我尝试在“拦截器”内执行此操作,因为它可以在发送之前或在应用程序中处理之前处理请求和响应。
过程是这样的。
请求 API
捕获响应
如果是 401,则调用刷新令牌 API
获取响应并请求我要调用的原始 API。
从原始 API 获取正确的响应。
// intercepter
val originalRequest = it.request()
val newRequestBuilder = originalRequest.newBuilder()
val response = it.proceed(newRequestBuilder.build())
if (response.code == 401) {
// TODO: refresh token and request again and get the original response
}
response
How can I handle 'refresh token' when 'access_token' is expired?
I know how it works. But what I want to know is implementing once and apply it to all the APIs.
When access token is expired, all the APIs are blocked(401) and need to request new token with refresh token.
So, I tried to do it within 'intercepter' because it can handle the request and response before sending or before handling in the application.
The process is like this.
request an API
catch the response
if it's 401, call refresh token API
get the response and request the original API that I was going to call.
get the proper response from the original API.
// intercepter
val originalRequest = it.request()
val newRequestBuilder = originalRequest.newBuilder()
val response = it.proceed(newRequestBuilder.build())
if (response.code == 401) {
// TODO: refresh token and request again and get the original response
}
response
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
刷新令牌而没有从API获得“错误”响应(仅写一次)
我建议您使用
Authenticator
。 OKHTTP将自动向Authenticator
询问响应是401未授权重试与他们重试的最后一次失败请求时的凭据。创建一个类
myauthenticator
并添加以下代码:现在您可以将此
authenticator
连接到您的okhttpclient
与Interpectors相同的方式仅此而已,如果发生401错误,
Authenticator
将自动调用,并且将其刷新刷新,并且将继续进行待处理的API,而不会得到错误响应。Refresh tokens without getting "Error" response from API (Write only once)
I would suggest you to use
Authenticator
. OkHttp will automatically ask theAuthenticator
for credentials when a response is 401 Not Authorized retrying last failed request with them.Create a class
MyAuthenticator
and add the following code:Now you can attach this
Authenticator
to yourOkHttpClient
the same way you do with InterceptorsFinally add this client to the Retrofit Builder:
That's all, Now if 401 error occur,
Authenticator
will be called automatically and token will be refreshed and the pending API will be continued without getting error response.