清爽的OAuth使用改造令牌,而无需修改所有来电 [英] Refreshing OAuth token using Retrofit without modifying all calls
问题描述
我们将在我们的Android应用程序中使用设备的改进,与OAuth2安全服务器进行通信。一切的伟大工程,我们使用RequestInterceptor包括与每个呼叫的访问令牌。 然而会有倍,当接入令牌将到期,并且令牌需要被刷新。当令牌到期,下一个电话将有未经授权的HTTP code回报,所以,很容易监测。 我们可以修改每个改造调用方式如下: 在失败的回调,检查错误code,如果它等于未经授权,刷新了OAuth的令牌,然后重复改造通话。 然而,对于这一点,所有呼叫应当被修改,这不是一个容易维护,和良好的解决方案。 有没有办法做到这一点,而无需修改所有的改装电话?
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?
推荐答案
请不要使用拦截
来处理身份验证。
Please do not use Interceptors
to deal with authentication.
来处理身份验证目前最好的方法是使用新的<一个href="http://square.github.io/okhttp/javadoc/com/squareup/okhttp/Authenticator.html"><$c$c>Authenticator$c$c> API,专门为为此的设计。
Current best approach to handle authentication is to use the new Authenticator
API, designed specifically for this purpose.
OkHttp将自动询问的身份验证
的凭据时的响应是 401未授权
重试最后一次失败的请求他们。
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;
}
附加的身份验证
到 OkHttpClient
你用拦截<以同样的方式/ code>
Attach an Authenticator
to an OkHttpClient
the same way you do with Interceptors
OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.setAuthenticator(authAuthenticator);
在创建时使用该客户端的改造
RestAdapter
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint(ENDPOINT)
.setClient(new OkClient(okHttpClient))
.build();
return restAdapter.create(API.class);
这篇关于清爽的OAuth使用改造令牌,而无需修改所有来电的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!