How to handle 401 expired token in Ionic 2 nicely?


#1

Server we connect to uses authentication token (not JWT).
When token expires, we get 401 response.

I’d like to implement the scenario:

1/ any request failed with 401 causes a prompt alert for user password
2/ user enters password
3/ app requests a new token
4/ when token is obtained, app repeats original request with fresh token and continues as if there were no token expired
otherwise app switches to login page

Can you please recommend how to do it nicely with ionic2/ng2?


#2

i would use Subjects, because you can:

  1. subscribe subjects like observables
  2. push new values

So you have a service, which is your baserequest service, any other service that wants to send an request, does not use HTTP directly.

This base request service holds an subject.
A base-component or App subscribes this subject.
If there is an error or 401 to handle --> your service triggers with subject.next() all subscribers.

So now you app knows, when an error occurs and gets informed. Now your base page/component can open an alert with the new credential check. When alert.dismiss(); is called you can check, if logged in or not and handle the redirect.

Your base request service need a flag, that says “hey, i am waiting for credentials”, because there are maybe other requests in the meantime. So you have an Array of pending requests --> if you are logged in again, resend all pending requests.


#3

Thanks. How can app.component redirect to the login page?

I tried this, but when there is a modal opened when forcedLogoutEvents occurs the modal stays open.
Is there a way to close all modals from AppComponent, smth like popToRoot()?

    @Component({
        templateUrl: 'app.html'
    })
    export class AppComponent {

    @ViewChild(Nav) nav: Nav;

    constructor(...) {
        this.subscription = this.coreService.forcedLogoutEvents.subscribe(evt => {
                this.nav.setRoot(LoginPage)
        });

#4

a suggestion.