为了账号安全,请及时绑定邮箱和手机立即绑定

使用翻新功能刷新OAuth令牌,而无需修改所有调用

使用翻新功能刷新OAuth令牌,而无需修改所有调用

萧十郎 2019-10-04 15:46:41
我们正在Android应用中使用Retrofit,以与OAuth2安全服务器进行通信。一切正常,我们使用RequestInterceptor在每个调用中都包含访问令牌。但是,有时访问令牌将过期,并且令牌需要刷新。当令牌过期时,下一个调用将返回未经授权的HTTP代码,因此易于监控。我们可以通过以下方式修改每个Retrofit调用:在失败回调中,检查错误代码,如果错误代码等于Unauthorized,则刷新OAuth令牌,然后重复Retrofit调用。但是,为此,应修改所有调用,这不是一个易于维护的好的解决方案。有没有一种方法可以在不修改所有Retrofit调用的情况下进行此操作?
查看完整描述

3 回答

?
繁花如伊

TA贡献2012条经验 获得超12个赞

如果您使用的是Retrofit > =,1.9.0则可以使用OkHttp的新Interceptor(已在中引入)OkHttp 2.2.0。您可能需要使用Application Interceptor,它允许您进行以下操作retry and make multiple calls。


您的拦截器可能类似于以下伪代码:


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) {


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

    }


}

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


    OkHttpClient okHttpClient = new OkHttpClient();

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

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


    RestService restService = new RestAdapter().Builder

            ...

            .setClient(new OkClient(okHttpClient))

            .create(RestService.class);

警告:由于Jesse Wilson(从广场)提到这里,这是权力的危险量。


话虽如此,我绝对认为这是现在处理此类问题的最佳方法。如果您有任何疑问,请随时在评论中提问。


查看完整回答
反对 回复 2019-10-04
  • 3 回答
  • 0 关注
  • 592 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信