Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrofit2 Authorization - Global Interceptor for access token

I'm trying to use Retrofit2, I want to add Token to my Header Like this:

Authorization: Bearer Token but the code below doesn't work:

public interface APIService {     @Headers({"Authorization", "Bearer "+ token})     @GET("api/Profiles/GetProfile?id={id}")     Call<UserProfile> getUser(@Path("id") String id); } 

My server is asp.net webApi. Please help what should I do?

like image 896
farshad Avatar asked Dec 10 '16 18:12

farshad


People also ask

How would you handle token expiry while making network calls Android?

If you want to handle the token expiry issue with Fuel, you can save the expiry time also in the shared preferences in addition to the token and token type. Then once an api call request fails with a 401 response code, you can assume that one reason may be the token has expired.

Where are Android access tokens stored?

Android KeyStore should be used for long term storage and retrieval of cryptographic keys which will be used to encrypt our tokens in order to store them in e.g. SharedPreferences or a database. The keys are not stored within an application's process, so they are harder to be compromised.


1 Answers

You have two choices -- you can add it as a parameter to your call --

@GET("api/Profiles/GetProfile?id={id}") Call<UserProfile> getUser(@Path("id") String id, @Header("Authorization") String authHeader); 

This can be a bit annoying because you will have to pass in the "Bearer" + token on each call. This is suitable if you don't have very many calls that require the token.

If you want to add the header to all requests, you can use an okhttp interceptor --

OkHttpClient client = new OkHttpClient.Builder().addInterceptor(new Interceptor() {       @Override       public Response intercept(Chain chain) throws IOException {         Request newRequest  = chain.request().newBuilder()             .addHeader("Authorization", "Bearer " + token)             .build();         return chain.proceed(newRequest);       }     }).build();  Retrofit retrofit = new Retrofit.Builder()     .client(client)     .baseUrl(/** your url **/)     .addConverterFactory(GsonConverterFactory.create())     .build(); 
like image 124
iagreen Avatar answered Sep 20 '22 15:09

iagreen