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?
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.
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With