如何刷新jwt并再次请求原始请求并获得响应?

发布于 2025-01-20 22:28:29 字数 675 浏览 3 评论 0原文

当“access_token”过期时,如何处理“刷新令牌”?

我知道它是如何运作的。但我想知道的是实现一次并将其应用于所有 API。

当访问令牌过期时,所有 API 都会被阻止(401),并且需要使用刷新令牌请求新令牌。

因此,我尝试在“拦截器”内执行此操作,因为它可以在发送之前或在应用程序中处理之前处理请求和响应。

过程是这样的。

  1. 请求 API

  2. 捕获响应

  3. 如果是 401,则调用刷新令牌 API

  4. 获取响应并请求我要调用的原始 API。

  5. 从原始 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.

  1. request an API

  2. catch the response

  3. if it's 401, call refresh token API

  4. get the response and request the original API that I was going to call.

  5. 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

幻想少年梦 2025-01-27 22:28:29

刷新令牌而没有从API获得“错误”响应(仅写一次)

我建议您使用Authenticator。 OKHTTP将自动向Authenticator询问响应是401未授权重试与他们重试的最后一次失败请求时的凭据。

  1. 创建一个类myauthenticator并添加以下代码:

     类myauthenticator:authenticator {
    
    
     替代娱乐验证(路线:路线:响应:响应):请求? {
    
         //设置Maixmum重试计数
         if(response.responsecount> = 3){
             返回null //如果我们失败了3次,请放弃。
         }
    
    
        //编写代码以刷新令牌
         val呼叫= myRetrofitClient.myapi()。refreshaccessToken()
         val res = call.execute()
         如果(res.issuccessful){
    
               val newAccessToken = res.body //响应中的新令牌
               //
               Response.Request
                   .newbuilder()
                   。
                   。建造()
    
         }别的{
             返回null
         }
    
         返回null
     }
    
     //
     私人Val响应。ResponseCount:INT
         get()= generateSequence(this){it.priorresponse} .count()
    
    }
     
  2. 现在您可以将此authenticator连接到您的okhttpclient与Interpectors相同的方式

     私人val客户端= okhttpclient.builder()
         .addinterceptor(myinterceptor())
         .authenticator(myauthenticator())//我们创建的身份验证者
         。建造()
     
  3. 最终将此客户端添加到改装构建器中:

      retrofit.builder()
             .baseurl(base_url)
             .client(client)//从第二步开始
             。建造()
     

仅此而已,如果发生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 the Authenticator for credentials when a response is 401 Not Authorized retrying last failed request with them.

  1. Create a class MyAuthenticator and add the following code:

    class MyAuthenticator: Authenticator {
    
    
     override fun authenticate(route: Route?, response: Response): Request? {
    
         // set maixmum retry count
         if (response.responseCount >= 3) {
             return null // If we've failed 3 times, give up.
         }
    
    
        // write code to refresh the token
         val call = MyRetrofitClient.MyApi().refreshAccessToken()
         val res = call.execute()
         if (res.isSuccessful){
    
               val newAccessToken = res.body // your new token from response
               //
               response.request
                   .newBuilder()
                   .header("bearerToken", newAccessToken)
                   .build()
    
         }else{
             return null
         }
    
         return null
     }
    
     //
     private val Response.responseCount: Int
         get() = generateSequence(this) { it.priorResponse }.count()
    
    }
    
  2. Now you can attach this Authenticator to your OkHttpClient the same way you do with Interceptors

    private val client= OkHttpClient.Builder()
         .addInterceptor(MyInterceptor())
         .authenticator(MyAuthenticator()) // authenticator we created
         .build()
    
  3. Finally add this client to the Retrofit Builder:

    Retrofit.Builder()
             .baseUrl(BASE_URL)
             .client(client) // from 2nd step
             .build()
    

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文