gpt4 book ai didi

android - OkHttp Authenticator 在成功刷新 token 请求后循环

转载 作者:行者123 更新时间:2023-12-02 12:13:48 33 4
gpt4 key购买 nike

我已经实现了类扩展 okhttp3.Authenticator与 Retrofit 2 一起用于处理我的 android 应用程序中的 401 错误。它应该调用 refreshToken 请求,然后如果成功,则使用新的访问 token 调用所需的请求。问题是成功获取刷新 token 后,我的TokenAuthenticator ... 一次又一次地刷新 token ,直到达到某个限制。你有什么线索吗?

TokenAuthenticator 类:

class TokenAuthenticator : Authenticator {

private val notLoggedResponseCode = 401
private val successResponseCode = 200
private val refreshTokenGrantType = "refresh_token"

override fun authenticate(route: Route?, response: okhttp3.Response?): Request? {

if (response?.code() == notLoggedResponseCode) {

val refreshTokenResponse: Response<Authorization> = RestController
.getInstance()
.basicRetrofit
.create(AuthRepository::class.java)
.refreshToken(
Credentials.basic(BuildConfig.CLIENT_ID, BuildConfig.CLIENT_SECRET),
refreshTokenGrantType,
UserSession.getInstance().authorization?.refreshToken!!)
.execute()



return if (refreshTokenResponse.code() == successResponseCode) {
UserSession.getInstance().authorization = refreshTokenResponse.body() //updating token
UserSession.getInstance().saveAuthorizationData()

// Every time flow is here, so new access token is obtained.
// But somehow it starts refresh procedure again...
response
.request()
.newBuilder()
.build()
} else {
null
}
} else {
return null
}
}
}

初始化 OkHttp 客户端进行改造的方法:
    private fun initBaseOkHttpClientBuilder(): OkHttpClient.Builder {
val logging = HttpLoggingInterceptor().apply {
this.level = HttpLoggingInterceptor.Level.BODY
}

return OkHttpClient.Builder()
.connectTimeout(connectionTimeout, TimeUnit.SECONDS)
.readTimeout(connectionTimeout, TimeUnit.SECONDS)
.writeTimeout(connectionTimeout, TimeUnit.SECONDS)
.addInterceptor(logging)
.authenticator(TokenAuthenticator())
.addInterceptor(OAuth2Interceptor())
}

最佳答案

当您获得刷新 token 时,您需要将其传递给 header 中的新请求。
response.request().newBuilder().header("Authorization", "bearer " + bearer).build()

关于android - OkHttp Authenticator 在成功刷新 token 请求后循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52425238/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com