Skip to content

Instantly share code, notes, and snippets.

@yesitskev
Created June 24, 2019 11:31
Show Gist options
  • Save yesitskev/2a74f13e4c31eeb7f5191535cc27591e to your computer and use it in GitHub Desktop.
Save yesitskev/2a74f13e4c31eeb7f5191535cc27591e to your computer and use it in GitHub Desktop.
TokenAttachingInterceptor for OkHttpClient
import android.support.annotation.NonNull;
import com.jakewharton.rxrelay2.BehaviorRelay;
import java.io.IOException;
import javax.inject.Inject;
import javax.inject.Singleton;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import timber.log.Timber;
@Singleton public class TokenAttachingInterceptor implements Interceptor {
private static final String X_AUTH_TOKEN = "X-AuthToken";
private static final String NO_AUTHENTICATION = "No-Authentication";
private final @TokenRelay BehaviorRelay<String> tokenRelay;
@Inject public TokenAttachingInterceptor(@TokenRelay BehaviorRelay<String> tokenRelay) {
this.tokenRelay = tokenRelay;
}
@Override public Response intercept(@NonNull Chain chain) throws IOException {
Request request = chain.request();
if (request.header(NO_AUTHENTICATION) == null) {
String token = tokenRelay.getValue();
if (token == null) {
return chain.proceed(request);
}
request = request.newBuilder().addHeader(X_AUTH_TOKEN, token).build();
} else {
request = request.newBuilder().removeHeader(NO_AUTHENTICATION).build();
}
return chain.proceed(request);
}
}
@yesitskev
Copy link
Author

This is a basic OkHttpClient interceptor which takes a BehaviorRelay as an input parameter. On each outbound network request, the intercepter will use the latest token within the relay and attach it as an authentication header. This allows you to avoid having to add extra parameters to Retrofit method definitions 💪

Found this in an old project of mine and going with this approach in Jarvis

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment