简体   繁体   English

如何阻止Okhttp Authenticator被多次调用?

[英]How to stop Okhttp Authenticator from being called multiple times?

I have an Authenticator like this我有一个像这样的身份验证器

@Singleton
class TokenAutheticator @Inject constructor(private val tokenHolder: Lazy<TokenHolder>,private val tokenInterceptor: TokenInterceptor):Authenticator {
    override fun authenticate(route: Route?, response: Response): Request? {

        val resp = tokenHolder.get().tokenService.relogin(tokenInterceptor.token).execute()
        println("### res "+resp.code())
        if (resp.code()==200) {
            val body = tokenHolder.get().tokenService.relogin(tokenInterceptor.token).execute()?.body()

            val newToken = body?.token
            println("########## authenticator ########## ")
            val url = route?.address()?.url()?.newBuilder()?.addQueryParameter("token", newToken)?.build()


            return response.request().newBuilder().url(url).build()
        }else{
            return null
        }
    }


}

When the resp.code != 200 the Authenticator is called multiple times.resp.code != 200时,会多次调用 Authenticator。 I am plugging it in Okhttp like this我像这样将它插入 Okhttp

@Provides
@Singleton
fun provideOkhttp(tokenInterceptor: TokenInterceptor, tokenAutheticator: TokenAutheticator): OkHttpClient {

    val logging = HttpLoggingInterceptor()
    logging.setLevel(HttpLoggingInterceptor.Level.BODY)
    val client = OkHttpClient.Builder()

            .authenticator(tokenAutheticator)
            .addInterceptor(logging)
            .addInterceptor(tokenInterceptor)
            .build()

    return client
}

So what I want to do is have the Authenticator try it only once and if it is able to get a new token then use the new token from now on and if it can't get a new token then exit.所以我想做的是让 Authenticator 只尝试一次,如果它能够获得新令牌,那么从现在开始使用新令牌,如果它无法获得新令牌,则退出。 But the Authenticator is called multiple times and the API responds with Too many attempts.但是 Authenticator 被多次调用,API 响应尝试次数过多。 Any help is appreciated.任何帮助表示赞赏。 Thanks谢谢

Only when you return null , Authenticator will stop getting called (stop retrying authentication).只有当您返回null时, Authenticator才会停止被调用(停止重试身份验证)。

Since you always return something, when response code is 200, it will get called a few times.因为你总是返回一些东西,当响应代码是 200 时,它会被调用几次。 Luckily, as far I understand, Authenticator detects your endless loop, and breaks out of it eventually.幸运的是,据我所知, Authenticator检测到你的无限循环,并最终打破了它。

Basically, you should use Authenticator to react to 401 (and similar) response code and only add authorization header in that case.基本上,您应该使用Authenticator对 401(和类似)响应代码做出反应,并且在这种情况下仅添加授权 header。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM