Created
June 24, 2019 11:31
-
-
Save yesitskev/2a74f13e4c31eeb7f5191535cc27591e to your computer and use it in GitHub Desktop.
TokenAttachingInterceptor for OkHttpClient
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is a basic
OkHttpClient
interceptor which takes aBehaviorRelay
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 toRetrofit
method definitions 💪Found this in an old project of mine and going with this approach in Jarvis