Okhttp Authenticator multithreading

后端 未结 5 592
一个人的身影
一个人的身影 2020-12-18 22:11

I am using OkHttp in my android application with several async requests. All requests require a token to be sent with the header. Sometimes I need to refresh th

5条回答
  •  臣服心动
    2020-12-18 22:38

    This is my solution to make sure to refresh token only once in a multi-threading case, using okhttp3.Authenticator:

    class Reauthenticator : Authenticator {
    
        override fun authenticate(route: Route?, response: Response?): Request? {
            if (response == null) return null
            val originalRequest = response.request()
            if (originalRequest.header("Authorization") != null) return null // Already failed to authenticate
            if (!isTokenValid()) { // Check if token is saved locally
                synchronized(this) {
                    if (!isTokenValid()) { // Double check if another thread already saved a token locally
                        val jwt = retrieveToken() // HTTP call to get token
                        saveToken(jwt)
                    }
                }
            }
            return originalRequest.newBuilder()
                    .header("Authorization", getToken())
                    .build()
        }
    
    }
    

    You can even write a unit test for this case, too!

提交回复
热议问题