使用 Retrofit 刷新 OAuth 令牌而不修改所有调用 [英] Refreshing OAuth token using Retrofit without modifying all calls

查看:28
本文介绍了使用 Retrofit 刷新 OAuth 令牌而不修改所有调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们在 Android 应用中使用 Retrofit 与 OAuth2 安全服务器进行通信.一切正常,我们使用 RequestInterceptor 在每次调用中包含访问令牌.但是,有时访问令牌会过期,并且需要刷新令牌.当令牌过期时,下一次调用将返回一个未经授权的 HTTP 代码,以便于监控.我们可以通过以下方式修改每个 Retrofit 调用:在失败回调中,检查错误代码,如果它等于 Unauthorized,则刷新 OAuth 令牌,然后重复 Retrofit 调用.但是,为此,应该修改所有调用,这不是一个易于维护的好解决方案.有没有办法在不修改所有 Retrofit 调用的情况下做到这一点?

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?

推荐答案

请不要使用Interceptors来处理认证.

Please do not use Interceptors to deal with authentication.

目前,处理身份验证的最佳方法是使用新的 Authenticator API,专为这个设计目的.

Currently, the best approach to handle authentication is to use the new Authenticator API, designed specifically for this purpose.

OkHttp 将自动询问Authenticator 的凭据,当响应是401 Not Authorised 重试上次失败的请求和他们在一起.

OkHttp will automatically ask the Authenticator for credentials when a response is 401 Not Authorised retrying last failed request with them.

public class TokenAuthenticator implements Authenticator {
    @Override
    public Request authenticate(Proxy proxy, Response response) throws IOException {
        // Refresh your access_token using a synchronous api request
        newAccessToken = service.refreshToken();

        // 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;
    }

Authenticator 附加到 OkHttpClient,就像使用 Interceptors

Attach an Authenticator to an OkHttpClient the same way you do with Interceptors

OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.setAuthenticator(authAuthenticator);

在创建您的 Retrofit RestAdapter

RestAdapter restAdapter = new RestAdapter.Builder()
                .setEndpoint(ENDPOINT)
                .setClient(new OkClient(okHttpClient))
                .build();
return restAdapter.create(API.class);

这篇关于使用 Retrofit 刷新 OAuth 令牌而不修改所有调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆