Sushil
Sushil

Reputation: 105

Basic authorization in retrofit

Interface:

@GET("burrowedbooks/")
Call<JsonArray> getCategoryList(@Header("Authorization") String token);

Usage:

    private LibraryAPi service;

    Retrofit retrofit = new Retrofit.Builder()
            //.client(client)
            .baseUrl(String.valueOf(R.string.base_url))
            .addConverterFactory(GsonConverterFactory.create())
            .build();

        service = retrofit.create(LibraryAPi.class);



// Extract token from Shared Preferences.
    SharedPreferences prefs = getActivity().getSharedPreferences(getString(R.string.login_data), MODE_PRIVATE);
    String token = "Bearer "+prefs.getString("token","");


    Call<JsonArray> categoryListResponseCall = service.getCategoryList(token);
    categoryListResponseCall.enqueue(new Callback<JsonArray>() {
        @Override
        public void onResponse(Call<JsonArray> call, Response<JsonArray> response) {
            int statusCode = response.code();

            Toast.makeText(getContext(), ""+statusCode, Toast.LENGTH_SHORT).show();

        }

        @Override
        public void onFailure(Call<JsonArray> call, Throwable t) {

        }
    });

I'm trying to send authentication token stored in shared preferences. The code above is not working. It returns 403 forbidden status code. What is the correct way to send authentication header?

Upvotes: 2

Views: 918

Answers (2)

Cătălin Florescu
Cătălin Florescu

Reputation: 5158

Also you can create a custom interceptor to add your header automatically on new requests.

OkHttpClient.Builder httpClient = new OkHttpClient.Builder();  
httpClient.addInterceptor(new Interceptor() {  
    @Override
    public Response intercept(Interceptor.Chain chain) throws IOException {
        Request original = chain.request();

        Request request = original.newBuilder()
           .header("Authorization", token)
           .method(original.method(), original.body())
           .build();

        return chain.proceed(request);
    }
}

OkHttpClient client = httpClient.build();  
Retrofit retrofit = new Retrofit.Builder()  
    .baseUrl(API_BASE_URL)
    .addConverterFactory(GsonConverterFactory.create())
    .client(client)
    .build();

Also, check if token is received good from SharedPreferences. Looks odd how you read it.

Upvotes: 0

Nabin Bhandari
Nabin Bhandari

Reputation: 16419

You are wrong at .baseUrl(String.valueOf(R.string.base_url))

You should get string from resource using .baseUrl(getActivity().getString(R.string.base_url))

But your code will not send data to the server and onFailure would be called.

If you get the string properly and still are getting 403, you may want to verify your back end implementation using postman.

Upvotes: 1

Related Questions