following post Dagger + Retrofit. Adding auth headers at runtime i'm trying to configure the okHttp & adding the jwt auth key to the okHttp by adding interceptor,for this i have created separate interceptor & added it to the Dagger's component so that it can be exposed anywhere.
Now once i hit the login i get the token,setting it using the setJwtToken() method of JwtAuthenticationInterceptor class & when i'm trying with the next endpoints i'm getting 401 error since jwtToken is coming null even though i have setted it.
Below i'm attaching my interceptor,component & module code snaps.
Module
@Provides
@Singleton
OkHttpClient provideOkhttpClient(Cache cache) {
OkHttpClient.Builder client = new OkHttpClient.Builder();
client.addInterceptor(provideHeaderInterceptor());
client.cache(cache);
return client.build();
}
@Provides
@Singleton
Retrofit provideRetrofit(OkHttpClient okHttpClient) {
return new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(mBaseUrl)
.client(okHttpClient)
.build();
}
@Provides
@Singleton
JwtAuthenticationInterceptor provideHeaderInterceptor(){
return new JwtAuthenticationInterceptor();
}
Component
@Component(modules = {AppModule.class, ApiModule.class, StorageModule.class})
@Singleton
public interface NetComponent {
Retrofit retrofit();
OkHttpClient okHttpClient();
SharedPreferences sharedPreferences();
Gson gson();
Cache cache();
KRITILog log();
JwtAuthenticationInterceptor headerInterceptor();
}
JwtAuthenticationInterceptor.java
@Singleton
public class JwtAuthenticationInterceptor implements Interceptor {
private String jwtToken;
@Inject
public JwtAuthenticationInterceptor() { }
public void setJwtToken(String jwtToken) {
this.jwtToken = jwtToken;
}
@Override
public Response intercept(Chain chain) throws IOException {
Request original = chain.request();
Request.Builder builder = original.newBuilder()
.header("Authorization","Bearer " +jwtToken);
//String.format("Bearer %s", jwtToken));
Request request = builder.build();
return chain.proceed(request);
}
}