OkHttp Authenticator 在成功刷新令牌请求后循环

OkHttp Authenticator looping after successful refresh token request

我已经实施了 class 扩展 okhttp3.Authenticator 以及 Retrofit 2 来处理我的 android 应用程序中的 401 错误。它应该调用 refreshToken 请求,然后如果成功,则使用新的访问令牌调用所需的请求。问题是在成功获取刷新令牌后,我的 TokenAuthenticator... 一次又一次地刷新令牌,直到达到某个限制。你知道发生了什么事吗?

TokenAuthenticatorclass:

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())
    }

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