Android retrofit OAuth2认证中更新token
最近在项目中接入worktile,通过OAuth2授权得到接口。在网络层封装的时候遇到Token的一些问题,现在记录下来,希望大家能够参考,并且提出一些建议
-
为请求的Header添加Token
抵用获取Token接口后,得到Token后。将access_token与refresh_token保存到本地,并且用了静态常量保存access_token,方便后续添加到Header中
利用OKhttp的拦截器Interceptor,拦截请求,加入Token
private static Interceptor mInterceptor = new Interceptor() { @Override public okhttp3.Response intercept(Chain chain) throws IOException { Request request = chain.request() .newBuilder() .addHeader(ACCESS_TOKEN, OauthConstant.access_token) .build(); return chain.proceed(request); } } };
-
当未授权时(401)时,利用Authenticator进行Token失效处理
public static Authenticator sTokenAuthenticator = new Authenticator() { @Override public Request authenticate(Route route,final Response response) throws IOException { service.refreshToken(refresh_token, Constants.Oauth.CLIENT_ID). subscribe(new Observer<Token>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { //TODO refresh token 也失效,返回重新登录 OauthConstant.access_token = ""; } @Override public void onNext(Token token) { OauthConstant.access_token = token.getAccess_token(); SPManager.getInstance().setAccessToken(token.getAccess_token()); SPManager.getInstance().setRefreshToken(token.getRefresh_token()); } }); if (TextUtils.isEmpty(OauthConstant.access_token)){ return null; } Request request = response.request() .newBuilder() .addHeader(ACCESS_TOKEN, OauthConstant.access_token) .build(); return request; } };