Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrofit 2.0 headers authentication

private void setUpRestClient() {
       OkHttpClient client = new OkHttpClient();
       client.interceptors().add(new Interceptor() {
           @Override
           public Response intercept(Chain chain) throws IOException {
               Request original = chain.request();
               Request request = original.newBuilder()
                       .header("Accept", "application/pyur.v1")
                       .header("Authorization", new SharedPreferencesUtil(getBaseContext()).getToken())
                       .header("Content-Type", "application/json")
                       .method(original.method(),original.body())
                       .build();
               return chain.proceed(request);
           }
       });
       RestClient.getInstance().configureRestAdapter(this, getResources().getString(R.string.base_url),client);
   }

public void configureRestAdapter(final Context context, String baseUrl, OkHttpClient client) {
    Gson gson = new GsonBuilder()
            .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
            .setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
            .excludeFieldsWithModifiers(Modifier.FINAL, Modifier.TRANSIENT, Modifier.STATIC)
            .create();
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(baseUrl)
            .addConverterFactory(GsonConverterFactory.create(gson))
            .client(client)
            .build();
    service = retrofit.create(NetworkServiceInterface.class);
}

This now gives me a failure return in Retrofit 2.0, originally I had it without the "Authorization" header and it was giving me unauthorized, which is understandable. But now I'm authorizing it with my auth token and it fails. New to Retrofit 2.0, thanks --

like image 669
Cannon Collins Avatar asked Jan 16 '16 00:01

Cannon Collins


1 Answers

You can add Authorization Header for every calls using Interceptor in Retrofit 2, by using the OkHttpClient.Builder class. Like this.

import okhttp3.OkHttpClient;
import okhttp3.Interceptor;

OkHttpClient defaultHttpClient = new OkHttpClient.Builder()
                .addInterceptor(new Interceptor() {
                            @Override
                            public Response intercept(Interceptor.Chain chain) throws IOException {
                            //getAccessToken is your own accessToken(retrieve it by saving in shared preference or any other option )
                                if(getAccessToken().isEmpty()){ 
                                    PrintLog.error("retrofit 2","Authorization header is already present or token is empty....");
                                    return chain.proceed(chain.request());
                                }
                                Request authorisedRequest = chain.request().newBuilder()
                                        .addHeader("Authorization", getAccessToken()).build();
                                PrintLog.error("retrofit 2","Authorization header is added to the url....");
                                return chain.proceed(authorisedRequest);
                            }}).build();

And add this client object to the retrofit object.

retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL) //BaseURL always ends with "/"
                .addConverterFactory(GsonConverterFactory.create())
                .client(defaultHttpClient)
                .build();

Now for every calls that you make using the retrofit object will add the "Authorization" header along with the url. And also we handle the condition that if the authorization value is empty, then we simply omit the Authorization header part for the request call.

like image 112
Stephenraj Avatar answered Jan 01 '23 21:01

Stephenraj