We are using Retrofit in our Android app, to communicate with an OAuth2 secured server. Everything works great, we use the RequestInterceptor to include the access token with each call. However there will be times, when the access token will expire, and the token needs to be refreshed. When the token expires, the next call will return with an Unauthorized HTTP code, so that's easy to monitor. We could modify each Retrofit call the following way: In the failure callback, check for the error code, if it equals Unauthorized, refresh the OAuth token, then repeat the Retrofit call. However, for this, all calls should be modified, which is not an easily maintainable, and good solution. Is there a way to do this without modifying all Retrofit calls?


当前回答

使用像@theblang answer这样的TokenAuthenticator是处理refresh_token的正确方法。

这是我的工具(我已经使用Kotlin, Dagger, RX,但你可以使用这个想法来实现你的情况) TokenAuthenticator

class TokenAuthenticator @Inject constructor(private val noneAuthAPI: PotoNoneAuthApi, private val accessTokenWrapper: AccessTokenWrapper) : Authenticator {

    override fun authenticate(route: Route, response: Response): Request? {
        val newAccessToken = noneAuthAPI.refreshToken(accessTokenWrapper.getAccessToken()!!.refreshToken).blockingGet()
        accessTokenWrapper.saveAccessToken(newAccessToken) // save new access_token for next called
        return response.request().newBuilder()
                .header("Authorization", newAccessToken.token) // just only need to override "Authorization" header, don't need to override all header since this new request is create base on old request
                .build()
    }
}

为了防止像@Brais Gabin评论这样的依赖循环,我创建了2个接口

interface PotoNoneAuthApi { // NONE authentication API
    @POST("/login")
    fun login(@Body request: LoginRequest): Single<AccessToken>

    @POST("refresh_token")
    @FormUrlEncoded
    fun refreshToken(@Field("refresh_token") refreshToken: String): Single<AccessToken>
}

and

interface PotoAuthApi { // Authentication API
    @GET("api/images")
    fun getImage(): Single<GetImageResponse>
}

AccessTokenWrapper经济舱

class AccessTokenWrapper constructor(private val sharedPrefApi: SharedPrefApi) {
    private var accessToken: AccessToken? = null

    // get accessToken from cache or from SharePreference
    fun getAccessToken(): AccessToken? {
        if (accessToken == null) {
            accessToken = sharedPrefApi.getObject(SharedPrefApi.ACCESS_TOKEN, AccessToken::class.java)
        }
        return accessToken
    }

    // save accessToken to SharePreference
    fun saveAccessToken(accessToken: AccessToken) {
        this.accessToken = accessToken
        sharedPrefApi.putObject(SharedPrefApi.ACCESS_TOKEN, accessToken)
    }
}

AccessToken类

data class AccessToken(
        @Expose
        var token: String,

        @Expose
        var refreshToken: String)

我的拦截器

class AuthInterceptor @Inject constructor(private val accessTokenWrapper: AccessTokenWrapper): Interceptor {

    override fun intercept(chain: Interceptor.Chain): Response {
        val originalRequest = chain.request()
        val authorisedRequestBuilder = originalRequest.newBuilder()
                .addHeader("Authorization", accessTokenWrapper.getAccessToken()!!.token)
                .header("Accept", "application/json")
        return chain.proceed(authorisedRequestBuilder.build())
    }
}

最后,在创建服务PotoAuthApi时向OKHttpClient添加拦截器和验证器

Demo

https://github.com/PhanVanLinh/AndroidMVPKotlin

Note

Authenticator flow

Example API getImage() return 401 error code authenticate method inside TokenAuthenticator will fired Synchronize noneAuthAPI.refreshToken(...) called After noneAuthAPI.refreshToken(...) response -> new token will add to header getImage() will AUTO called with new header (HttpLogging WILL NOT log this call) (intercept inside AuthInterceptor WILL NOT CALLED) If getImage() still failed with error 401, authenticate method inside TokenAuthenticator will fired AGAIN and AGAIN then it will throw error about call method many time(java.net.ProtocolException: Too many follow-up requests). You can prevent it by count response. Example, if you return null in authenticate after 3 times retry, getImage() will finish and return response 401 If getImage() response success => we will result the result normally (like you call getImage() with no error)

希望能有所帮助

其他回答

您可以尝试为所有的加载器创建一个基类,在这个基类中您可以捕获特定的异常,然后根据需要进行操作。 让所有不同的加载器从基类扩展,以传播行为。

使用像@theblang answer这样的TokenAuthenticator是处理refresh_token的正确方法。

这是我的工具(我已经使用Kotlin, Dagger, RX,但你可以使用这个想法来实现你的情况) TokenAuthenticator

class TokenAuthenticator @Inject constructor(private val noneAuthAPI: PotoNoneAuthApi, private val accessTokenWrapper: AccessTokenWrapper) : Authenticator {

    override fun authenticate(route: Route, response: Response): Request? {
        val newAccessToken = noneAuthAPI.refreshToken(accessTokenWrapper.getAccessToken()!!.refreshToken).blockingGet()
        accessTokenWrapper.saveAccessToken(newAccessToken) // save new access_token for next called
        return response.request().newBuilder()
                .header("Authorization", newAccessToken.token) // just only need to override "Authorization" header, don't need to override all header since this new request is create base on old request
                .build()
    }
}

为了防止像@Brais Gabin评论这样的依赖循环,我创建了2个接口

interface PotoNoneAuthApi { // NONE authentication API
    @POST("/login")
    fun login(@Body request: LoginRequest): Single<AccessToken>

    @POST("refresh_token")
    @FormUrlEncoded
    fun refreshToken(@Field("refresh_token") refreshToken: String): Single<AccessToken>
}

and

interface PotoAuthApi { // Authentication API
    @GET("api/images")
    fun getImage(): Single<GetImageResponse>
}

AccessTokenWrapper经济舱

class AccessTokenWrapper constructor(private val sharedPrefApi: SharedPrefApi) {
    private var accessToken: AccessToken? = null

    // get accessToken from cache or from SharePreference
    fun getAccessToken(): AccessToken? {
        if (accessToken == null) {
            accessToken = sharedPrefApi.getObject(SharedPrefApi.ACCESS_TOKEN, AccessToken::class.java)
        }
        return accessToken
    }

    // save accessToken to SharePreference
    fun saveAccessToken(accessToken: AccessToken) {
        this.accessToken = accessToken
        sharedPrefApi.putObject(SharedPrefApi.ACCESS_TOKEN, accessToken)
    }
}

AccessToken类

data class AccessToken(
        @Expose
        var token: String,

        @Expose
        var refreshToken: String)

我的拦截器

class AuthInterceptor @Inject constructor(private val accessTokenWrapper: AccessTokenWrapper): Interceptor {

    override fun intercept(chain: Interceptor.Chain): Response {
        val originalRequest = chain.request()
        val authorisedRequestBuilder = originalRequest.newBuilder()
                .addHeader("Authorization", accessTokenWrapper.getAccessToken()!!.token)
                .header("Accept", "application/json")
        return chain.proceed(authorisedRequestBuilder.build())
    }
}

最后,在创建服务PotoAuthApi时向OKHttpClient添加拦截器和验证器

Demo

https://github.com/PhanVanLinh/AndroidMVPKotlin

Note

Authenticator flow

Example API getImage() return 401 error code authenticate method inside TokenAuthenticator will fired Synchronize noneAuthAPI.refreshToken(...) called After noneAuthAPI.refreshToken(...) response -> new token will add to header getImage() will AUTO called with new header (HttpLogging WILL NOT log this call) (intercept inside AuthInterceptor WILL NOT CALLED) If getImage() still failed with error 401, authenticate method inside TokenAuthenticator will fired AGAIN and AGAIN then it will throw error about call method many time(java.net.ProtocolException: Too many follow-up requests). You can prevent it by count response. Example, if you return null in authenticate after 3 times retry, getImage() will finish and return response 401 If getImage() response success => we will result the result normally (like you call getImage() with no error)

希望能有所帮助

如果你正在使用Retrofit >= 1.9.0,那么你可以使用OkHttp的新拦截器,它是在OkHttp 2.2.0中引入的。您可能希望使用Application Interceptor,它允许您重试并进行多个调用。

你的拦截器可以看起来像这样的伪代码:

public class CustomInterceptor implements Interceptor {

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();

        // try the request
        Response response = chain.proceed(request);

        if (response shows expired token) {
            // close previous response
            response.close()

            // get a new token (I use a synchronous Retrofit call)

            // create a new request and modify it accordingly using the new token
            Request newRequest = request.newBuilder()...build();

            // retry the request
            return chain.proceed(newRequest);
        }

        // otherwise just pass the original response on
        return response;
    }

}

定义拦截器之后,创建OkHttpClient并将拦截器添加为应用程序拦截器。

    OkHttpClient okHttpClient = new OkHttpClient();
    okHttpClient.interceptors().add(new CustomInterceptor());

最后,在创建RestAdapter时使用这个OkHttpClient。

    RestService restService = new RestAdapter().Builder
            ...
            .setClient(new OkClient(okHttpClient))
            .create(RestService.class);

警告:正如杰西威尔逊(来自Square)在这里提到的,这是一个危险的电量。

话虽如此,我绝对认为这是现在处理这种事情的最好方法。如果你有任何问题,请不要犹豫在评论中提问。

TokenAuthenticator依赖于服务类。服务类依赖于OkHttpClient实例。要创建OkHttpClient,我需要TokenAuthenticator。我该如何打破这个循环?两个不同的OkHttpClients?它们将有不同的连接池..

如果你有一个你需要在你的Authenticator内部的Retrofit TokenService,但是你只想建立一个OkHttpClient,你可以使用TokenServiceHolder作为TokenAuthenticator的依赖项。您必须在应用程序(单例)级别维护对它的引用。如果你使用匕首2,这很容易,否则只是在你的应用程序中创建类字段。

在TokenAuthenticator.java

public class TokenAuthenticator implements Authenticator {

    private final TokenServiceHolder tokenServiceHolder;

    public TokenAuthenticator(TokenServiceHolder tokenServiceHolder) {
        this.tokenServiceHolder = tokenServiceHolder;
    }

    @Override
    public Request authenticate(Proxy proxy, Response response) throws IOException {

        //is there a TokenService?
        TokenService service = tokenServiceHolder.get();
        if (service == null) {
            //there is no way to answer the challenge
            //so return null according to Retrofit's convention
            return null;
        }

        // Refresh your access_token using a synchronous api request
        newAccessToken = service.refreshToken().execute();

        // Add new header to rejected request and retry it
        return response.request().newBuilder()
                .header(AUTHORIZATION, newAccessToken)
                .build();
    }

    @Override
    public Request authenticateProxy(Proxy proxy, Response response) throws IOException {
        // Null indicates no attempt to authenticate.
        return null;
    }

在TokenServiceHolder.java:

public class TokenServiceHolder {

    TokenService tokenService = null;

    @Nullable
    public TokenService get() {
        return tokenService;
    }

    public void set(TokenService tokenService) {
        this.tokenService = tokenService;
    }
}

客户端设置:

//obtain instance of TokenServiceHolder from application or singleton-scoped component, then
TokenAuthenticator authenticator = new TokenAuthenticator(tokenServiceHolder);
OkHttpClient okHttpClient = new OkHttpClient();    
okHttpClient.setAuthenticator(tokenAuthenticator);

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("https://api.github.com/")
    .client(okHttpClient)
    .build();

TokenService tokenService = retrofit.create(TokenService.class);
tokenServiceHolder.set(tokenService);

如果你正在使用Dagger 2或类似的依赖注入框架,这里有一些例子可以回答这个问题

我知道这是一条老帖子,但以防有人无意中发现。

TokenAuthenticator依赖于服务类。服务类依赖于OkHttpClient实例。要创建OkHttpClient,我需要TokenAuthenticator。我该如何打破这个循环?两个不同的OkHttpClients?它们将有不同的连接池..

我也面临着同样的问题,但我想只创建一个OkHttpClient因为我不认为我需要另一个TokenAuthenticator本身,我用Dagger2,所以我最终提供服务类TokenAuthenticator懒惰的注入,你可以阅读更多关于懒惰匕首2中注入,但基本上就像说匕首TokenAuthenticator所需的不去创建服务。

你可以参考这个SO线程的示例代码:如何解决一个循环依赖,同时仍然使用Dagger2?