相关疑难解决方法(0)

使用Retrofit刷新OAuth令牌而不修改所有调用

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

android oauth-2.0 retrofit

141
推荐指数
4
解决办法
6万
查看次数

Android Retrofit2刷新Oauth 2令牌

我正在使用RetrofitOkHttp库.所以Authenticator如果获得401响应,我有哪个authanticate用户.

build.gradle是这样的:

compile 'com.squareup.retrofit2:retrofit:2.0.0-beta4'
compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta4'
compile 'com.squareup.okhttp3:okhttp:3.1.2'
Run Code Online (Sandbox Code Playgroud)

我的习惯Authenticator在这里:

import java.io.IOException;
import okhttp3.Authenticator;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.Route;

public class CustomAuthanticator  implements Authenticator {
@Override
public Request authenticate(Route route, Response response) throws IOException {

    //refresh access token via refreshtoken

    Retrofit client = new Retrofit.Builder()
            .baseUrl(baseurl)
            .addConverterFactory(GsonConverterFactory.create())
            .build();
    APIService service = client.create(APIService.class);
    Call<RefreshTokenResult> refreshTokenResult=service.refreshUserToken("application/json", "application/json", "refresh_token",client_id,client_secret,refresh_token);
    //this is syncronous retrofit request
    RefreshTokenResult refreshResult= refreshTokenResult.execute().body();
    //check if response equals 400 , …
Run Code Online (Sandbox Code Playgroud)

android oauth-2.0 okhttp retrofit2 okhttp3

26
推荐指数
1
解决办法
2万
查看次数

标签 统计

android ×2

oauth-2.0 ×2

okhttp ×1

okhttp3 ×1

retrofit ×1

retrofit2 ×1