Question:
I make a request (any, authorization, registration, etc.) and only then I find out that I need to update TOKEN
, that is, I get a 401
error.
Here is the request for authorization:
BaseApplication.getApiClient()
.signIn(accessToken, body)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new SingleObserver<UserProfile>() {
@Override
public void onSubscribe(Disposable d) {
Log.d("-- SignInOnSubscribe", "Subscribed!");
}
@Override
public void onSuccess(UserProfile userProfile) {
if (userProfile.getErrorDetails() != null) {
onSignInFinishedCallback.onLoginFailure(userProfile.getErrorDetails());
Log.d("-- SignInOnError", userProfile.getErrorDetails());
} else {
onSignInFinishedCallback.onLoginSuccess(userProfile);
profileRepository.updateUserProfile(userProfile);
Log.d("-- SignInOnSuccess", userProfile.getName());
}
}
@Override
public void onError(Throwable e) {
Log.d("-- SignInOnError", e.getMessage());
if (e.getMessage().equals(Constants.CODE_UNAUTHORIZED)){
// Действие при ошибке 401
}
onSignInFinishedCallback.onLoginFailure(e.getMessage());
}
});
The API requests themselves:
@POST("/api/login")
Single<UserProfile> getAccessToken(@Body Map<String, String> requestBody);
@POST("/api/abonent/login")
Single<UserProfile> signIn(@Header("X-ACCESS-TOKEN") String accessToken,
@Body Map<String, String> requestBody);
Let's say authorization запрос 1
is запрос 1
, request to get TOKEN
is запрос 2
.
Question: How to update TOKEN
if I received an error in запросе 1
and after the success of запроса 2
, make запрос 1
?
Answer:
The task of refreshing the token can be solved using OkHttp Interceptors.
What is Interceptor
? This is the class that intercepts all your requests through the given OkHttClient
.
It must be connected to the client, for example:
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(new TokenRefresherInterceptor())
.build();
What to do in an interceptor?
class TokenRefresherInterceptor implements Interceptor {
@Override public Response intercept(Interceptor.Chain chain) throws IOException {
Request request = chain.request(); // получили запрос который вы отправили на сервер.
Response response = chain.proceed(request); //тут выполняется запрос и результат в response.
//далее вы работаете с этим response.
//Проверяете, какой ответ вам пришел.
//Если в нём лежит 401. значит вы формируете запрос на обновление токена, //выполняете его в этом же интерсепторе дальше. и снова проверяете результат.
//если токен рефрешнулся то повторяете изначальный запрос
return response;
}
}
For more details, there are many articles on this topic in google)