我已经实现了扩展okhttp3.Authenticator
的类以及Retrofit 2,用于处理android应用中的401错误。它应该调用refreshToken请求,然后如果成功,则使用新的访问令牌重新调用所需的请求。问题是成功获取刷新令牌后,我的TokenAuthenticator
...会一次又一次刷新令牌,直到达到某个限制。你有什么线索吗?
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())
}
答案 0 :(得分:4)
获得刷新令牌后,需要将其传递到标头中的新请求。
像response.request().newBuilder().header("Authorization", "bearer " + bearer).build()