4

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);
    }
}
Pranesh saw
  • 83
  • 1
  • 9

1 Answers1

3

problem is this line

client.addInterceptor(provideHeaderInterceptor());

there you are creating a new instance of the JwtAuthenticationInterceptor, different from the one provided by dagger. JwtAuthenticationInterceptor should be a dependency of that method. Eg

@Provides
@Singleton
OkHttpClient provideOkhttpClient(Cache cache, JwtAuthenticationInterceptor interceptor) {
    OkHttpClient.Builder client = new OkHttpClient.Builder();
    client.addInterceptor(interceptor);
    client.cache(cache);
    return client.build();
}
Blackbelt
  • 156,034
  • 29
  • 297
  • 305