How to refresh ACCESS-TOKEN in Retrofit2/rxJava

java android rx-java retrofit2

483 观看

1回复

374 作者的声誉

I make a request (any, authorization, registration, etc.) and only then I find out that I need to update the ACCESS-TOKEN, that is, I get the error 401.

Here is the authorization request:

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)){
                        // Action on error 401
                    }

                    onSignInFinishedCallback.onLoginFailure(e.getMessage());
                }
            });

The API requests:

@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);

For example, the request for authorization is request 1, the request to receive TOKEN is query 2.

Question: How can I update TOKEN if I get an error in query 1 and after query 2 succeeds, back to do query 1?

作者: No Name 的来源 发布者: 2017 年 12 月 27 日

回应 1


0

391 作者的声誉

I'm not sure how you receive the new token, since the return type of getAccessToken() is Single<UserProfile>. I suppose it should be Single<String> instead. Maybe this is not the case and you receive the token in a header or as a field of UserProfile. In either case, you can get an idea from the below solution and adjust it to your case.

The approach is that we create a new observable from your original one that uses a token store, which holds the most up-to-date token. We handle the 401 error using compose and onErrorResumeNext so that a token refresh request is made, the new token is saved to the token store, and the original request is retried with the new token this time.

For a more detailed explanation, see the comments in the code below:

public void signIn(final Map<String, String> body) {
    Single
            // Wrap the original request with a "defer" so that the access token is
            // evaluated each time it is called. This is important because the refreshed
            // access token should be used the second time around.
            .defer(new Callable<SingleSource<UserProfile>>() {
                @Override
                public SingleSource<UserProfile> call() throws Exception {
                    return BaseApplication.getApiClient()
                            .signIn(accessTokenStore.getAccessToken(), body);
                }
            })
            // Compose it with a transformer that refreshes the token in the token store and
            // retries the original request, this time with the refreshed token.
            .compose(retryOnNotAuthorized(body))

            // The code remains the same from here.
            .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)) {
                        // Action on error 401
                    }

                    onSignInFinishedCallback.onLoginFailure(e.getMessage());
                }
            });
}

@NonNull
private SingleTransformer<UserProfile, UserProfile> retryOnNotAuthorized(final Map<String, String> body) {
    return new SingleTransformer<UserProfile, UserProfile>() {
        @Override
        public SingleSource<UserProfile> apply(final Single<UserProfile> upstream) {
            // We use onErrorResumeNext to continue our Single stream with the token refresh
            // and the retrial of the request.
            return upstream.onErrorResumeNext(new Function<Throwable, SingleSource<? extends UserProfile>>() {
                @Override
                public SingleSource<UserProfile> apply(Throwable throwable) throws Exception {
                    if (throwable instanceof HttpException
                            && ((HttpException) throwable).code() == 401) {
                        return BaseApplication.getApiClient().getAccessToken(body)
                                // I always use doOnSuccess() for non-Rx side effects, such as caching the token.
                                // I think it's clearer than doing the caching in a map() or flatMap().
                                .doOnSuccess(new Consumer<String>() {
                                    @Override
                                    public void accept(String accessToken) throws Exception {
                                        // Save the access token to the store for later use.
                                        accessTokenStore.storeAccessToken(accessToken);
                                    }
                                })
                                // We don't need the result of getAccessToken() any more, so I
                                // think it's cleaner to convert the stream to a Completable.
                                .toCompletable()

                                // After the token is refreshed and stored, the original request
                                // should be repeated.
                                .andThen(upstream);
                    }

                    // If the error was not 401, pass through the original error
                    return Single.error(throwable);
                }
            });
        }
    };
}

Update: The token store is just a regular interface with a get and a store method. You should implement it either as a POJO (storing the token in a field) or you could store the token in a shared preference so that the token survives app restarts.

作者: Janos Breuer 发布者: 2017 年 12 月 31 日
32x32