Android Retrofit2 Refresh Oauth 2 Token

Yasin Kaçmaz picture Yasin Kaçmaz · Feb 20, 2016 · Viewed 24.8k times · Source

I am using Retrofit and OkHttp libraries. So I have Authenticator which authanticate user if gets 401 response.

My build.gradle is like that :

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'

And my custom Authenticator is here :

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 , mean empty response
    if(refreshResult!=null) {
       //save new access and refresh token
        // than create a new request and modify it accordingly using the new token
        return response.request().newBuilder()
                .header("Authorization", newaccesstoken)
                .build();

    } else {
        //we got empty response and return null
        //if we dont return null this method is trying to make so many request
        //to get new access token
        return null;

    }

}}

This is my APIService class :

public interface APIService {

@FormUrlEncoded
@Headers("Cache-Control: no-cache")
@POST("token")
public Call<RefreshTokenResult> refreshUserToken(@Header("Accept") String accept, 
    @Header("Content-Type") String contentType, @Field("grant_type") String grantType,
    @Field("client_id") String clientId, @Field("client_secret") String clientSecret, 
    @Field("refresh_token") String refreshToken);
}

I am using authanticator like that :

CustomAuthanticator customAuthanticator=new CustomAuthanticator();
OkHttpClient okClient = new OkHttpClient.Builder()
        .authenticator(customAuthanticator)
        .build();
Retrofit client = new Retrofit.Builder()
        .baseUrl(getResources().getString(R.string.base_api_url))
        .addConverterFactory(GsonConverterFactory.create(gson))
        .client(okClient)
        .build();

//then make retrofit request

So my question is : Sometimes I get new access token and continue work, making new requests. But sometimes I get 400 response which means empty response. So my old refresh token invalid and I can't get new token. Normally our refresh token expires in 1 year. So how I can do this. Please help me !

Answer

Yasin Ka&#231;maz picture Yasin Kaçmaz · Feb 25, 2016

Disclaimer : Actually I am using Dagger +RxJava + RxAndroid + Retrofit but I just wanted to provide an answer to demonstrate logic for future visitors. Only difference is use Schedulers.trampoline() or blockingGet() when refreshing your token to block that thread. If you have more questions about these libraries please comment below so maybe I can provide another answer or help you.

Important : If you are making requests from several places your token will refresh multiple times inside TokenAuthenticator class. For example when your app and your service makes requests concurrently. To beat this issue just add synchronized keyword to your TokenAuthenticators authenticate method.

Also inside authenticate method you can check if token already refreshed by comparing request token with stored token to prevent unnecessary refresh

And please do not consider using TokenInterceptor because it is edge case, just focus TokenAuthenticator.

enter image description here

First of all refreshing token is critical process for most apps. Many apps works like that: If refresh token fails logout current user and warn user to re-login.(Maybe retry refresh token couple token before logout user)

Important Notice: Please make synchronous requests when refreshing your token inside Authenticator because you must block that thread until your request finish otherwise your requests executed twice with old and new token.

Anyways I will explain it step by step :

Step 1 : Please refer singleton pattern, we will create one class thats responsible for returning our retrofit instance. Since it is static if there is no instance available it just creates instance only once and when you call it always returns this static instance. This is also basic definition of Singleton design pattern.

public class RetrofitClient {

private static Retrofit retrofit = null;

private RetrofitClient() {
    // private constructor to prevent access
    // only way to access: Retrofit client = RetrofitClient.getInstance();
}

public static Retrofit getInstance() {
    if (retrofit == null) {
        // our authenticator
        TokenAuthenticator tokenAuthenticator = new TokenAuthenticator();

        // !! This interceptor is not required for everyone !!
        // Main purpose is this interceptor is reducing server calls

        // Our token needs to be refreshed after 10 hours
        // We came application after 50 hours and try to make request.
        // Of course token is expired and it will return 401
        // So this interceptor checks time and refreshes token before any 401
        // If this fails and I get 401 then my TokenAuthenticator do his job.
        // if my TokenAuthenticator fails too, basically I just logout user
        TokenInterceptor tokenInterceptor = new TokenInterceptor();

        OkHttpClient okClient = new OkHttpClient.Builder()
                .authenticator(tokenAuthenticator)
                .addInterceptor(tokenInterceptor)
                .build();

        retrofit = new Retrofit.Builder()
                .baseUrl(base_api_url)
                .client(okClient)
                .build();
    }
    return retrofit;
}

}

Step 2 : In my TokenAuthenticator's authenticate method :

@Override
public Request authenticate(Route route, Response response) throws IOException {

    refreshResult=refreshToken();
    if (refreshResult) {
    //refresh is successful, we saved new token to storage
    // get your token from storage and set header
    String newaccess="your new access token";

    // make current request with new access token
    return response.request().newBuilder()
            .header("Authorization", newaccess)
            .build();

    } else {
        // Refresh token failed, you can logout user or retry couple times
        // Returning null is critical here, it will stop current request
        // If you do not return null, the request gets called again and again
        // You will end up in a loop calling refresh again and again
        return null;
    }
}

And refreshToken method, this is just example you can create your own:

public boolean refreshToken() {
    // you can use RxJava with Retrofit and add blockingGet
    // it is up to you how to refresh your token
    RefreshTokenResult result = retrofit.refreshToken();
    int responseCode = result.getResponseCode();

    if(responseCode==200){
        // save new token to sharedpreferences, storage etc.
        return true;
    } else {
        //cannot refresh
        return false;
    } 
}

Step 3: For those who wants to see TokenInterceptor logic:

public class TokenInterceptor implements Interceptor{
SharedPreferences mPrefs;
SharedPreferences.Editor mPrefsEdit;

@Override
public Response intercept(Chain chain) throws IOException {

    Request newRequest=chain.request();

    //get expire time from shared preferences
    long expireTime=mPrefs.getLong("expiretime",0);
    Calendar c = Calendar.getInstance();
    Date nowDate=c.getTime();
    c.setTimeInMillis(expireTime);
    Date expireDate=c.getTime();

    int result=nowDate.compareTo(expireDate);
    // when comparing dates -1 means date passed so we need to refresh token
    if(result==-1) {
        //refresh token here , and get new access token
        TokenResponse tokenResponse = refreshToken();

        // Save refreshed token's expire time :
        integer expiresIn=tokenResponse.getExpiresIn();
        Calendar c = Calendar.getInstance();
        c.add(Calendar.SECOND,expiresIn);
        mPrefsEdit.putLong("expiretime",c.getTimeInMillis());

        String newaccessToken="new access token";
        newRequest=chain.request().newBuilder()
                .header("Authorization", newaccessToken)
                .build();
    }
    return chain.proceed(newRequest);
  }
}

I am making requests at application and background service. Both of them uses same retrofit instance and I can easily manage requests. Please refer this answer and try to create your own client. If you still have issues simply comment below or send mail. I'll try to help. Hope this helps.