1

这是我在使用 kotlin ad retrofit 2 的 android 应用程序中用于刷新令牌的代码。

gradle: _

implementation "com.squareup.retrofit2:retrofit:2.9.0"
implementation "com.squareup.retrofit2:converter-moshi:retrofit:2.9.0"

并且 Authenticator 是:

class OAuthAuthenticator(
        private val refreshTokenService: Repository,
        private val sessionManager: SessionManager
    ) : Authenticator {
        @Synchronized
        override fun authenticate(route: Route?, response: Response): Request? {
            try {
        //synchronized call to refresh the token
                val refreshTokenResponse =
                    refreshTokenService.refreshJWTToken(sessionManager.getAuthTokens())
                val sessionDataResponseBody = refreshTokenResponse.body()
                if (refreshTokenResponse.isSuccessful && sessionDataResponseBody != null && !sessionDataResponseBody.jwt.isNullOrEmpty()) {
                    sessionManager.jwtToken = sessionDataResponseBody.jwt
                    // retry request with the new tokens (I get 400 error)
                    return response.request()
                        .newBuilder()
                        .addHeader("Authorization", "Bearer ${sessionManager.jwtToken}")
                        .build()
                } else {
                    throw HttpException(refreshTokenResponse)
                }
            } catch (throwable: Throwable) {
                when (throwable) {
                    is HttpException -> {
                        onSessionExpiration()
                        return null
                    }
                }
            }
            return null
        }

        private fun onSessionExpiration() {
            sessionManager.clear()
        }
    }

这是 Repository 课程:

object Repository {
    fun refreshJWTToken(authTokens : AuthTokens) = RetrofitBuilder.userApi.getAuthenticationToken(authTokens).execute()
}

这是API

interface UserAPI {
    @Headers("Cache-Control: no-cache")
    @POST(AUTH_TOKENS_URL)
    fun getAuthenticationToken(
        @Header("Accept")  accept : String,
        @Header("Content-Type")  contentType : String,
        @Body params: AuthTokens
    ): Call<AuthTokenResponse>
}

retrofit builder: _

init {
    val connectivityManager =
        context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
    val sessionManager = SessionManager.getInstance(context)
    val httpLoggingInterceptor =
        HttpLoggingInterceptor() 
    httpLoggingInterceptor.level = HttpLoggingInterceptor.Level.BODY
    httpClient = OkHttpClient.Builder()
        .addInterceptor(httpLoggingInterceptor)
        .addInterceptor(ConnectivityCheckInterceptor(connectivityManager))
        .addInterceptor(AuthInterceptor(sessionManager))
        .authenticator(OAuth2Authenticator(UserRepository, sessionManager))
        .readTimeout(TIME_OUT, TimeUnit.SECONDS)
        .build()
}

问题:我可以确认代码刷新了 Auth 令牌并成功保存了它。但是,在那之后我得到一个 400 错误。关于我做错了什么有什么建议吗?

4

1 回答 1

0

我知道这个问题很老,但对于每个面临同样问题的人来说,这只是一个简单的错误。

请使用,header(..., ...)而不是addHeader(..., ...)TokenAuthenticator课堂上。

它对我有用。

于 2022-01-26T08:46:50.237 回答