Interceptor Refresh JWT Token with ionic storage(Promise)?

Hello, every one .

I am implementing my refresh token using this post :

I’ve modified and my interceptor is :

intercept(req: HttpRequest, next: HttpHandler): Observable<HttpEvent> {
console.log(“InterceptorProvider”);
if (!req.url.includes(‘auth’)) {
let getTsObs = Observable.fromPromise(this.storage.get(‘TOKEN’));

  const tokenObservable = getTsObs.map(token => {
    return req = req.clone({
      setHeaders: {
        Authorization: `Bearer ${token}`
      }
    });
  });
  return tokenObservable.flatMap((req) => {
    console.log("FLATMAP");
    return next.handle(req)
      .do((event: HttpEvent<any>) => {
        if (event instanceof HttpResponse) {
          // do stuff to the response here
          console.log("DOOO event " + this.typeRegister);
        }
      }, error => {
        if (error.status === 403) {
          alert("Error 403");

          let obsGetEmail = Observable.fromPromise(this.storage.get('email'));
          let obsGetPass = Observable.fromPromise(this.storage.get('pass'));

          let email,pass;

          return obsGetEmail.flatMap(email => {
            email=email;
            return obsGetPass
          }).flatMap(pass => {
            pass=pass;
            return this._up.loginEmailObs(email, pass)
          }).mergeMap(refreshedToken => {
            let newToken = refreshedToken.result['access_token'];
            console.log("NEW TOKEN" + newToken);

            let clone = req.clone({
              setHeaders: {
                Accept: `application/json`,
                'Content-Type': `application/json`,
                Authorization: `Bearer ${newToken}`
              }
            });
            return next.handle(clone);
          });

} else if (error.status === 200) {
console.log(“error.status”);
//return Observable.of(response.data);
return Observable.of(event);
} else {
console.log(“error ELSE”);
return Observable.of(event);
//return Observable.throw(error);
}
})
})
}
else {
console.log(“ES AUTH”);
let clone = req.clone({
setHeaders: {
Accept: application/json,
‘Content-Type’: application/json
}
});
return next.handle(clone);
}
}

Could someone help me to achieve that ?

Please don’t store passwords on device. It’s a galactic security risk for your users.

@rapropos I know It’s a galactic security risk but for now I am doing that to get a new token, If i understand how i can achieve that the next step will be change the next line : return this._up.loginEmailObs(email, pass).

On the other hand, what is the correct way to get a new token without login with username and password(using ionic storage) ? I am not the backend, for this reason i want to know that to tell the backend to solve this security risk.

Thank you in advance

The way this should be done is that the username and password are only used ephemerally - never put in storage. You send them (over a secure connection - HTTPS) to the backend, and the backend gives you a token. The token can (more) safely be stored, because the consequences of it being compromised are limited to this particular service. Users tend to reuse passwords across many different services, so storing passwords potentially compromises things far outside the realm of your app.

So the workflow you are attempting is fundamentally flawed, because the “request failed due to lack of token” path needs human interaction at that point. Additionally, the backend should be returning 401 there, not 403. 403 means “I know who you are, and you aren’t authorized to do what you’re trying to do”. 401 means “I don’t know who you are, so please authenticate and maybe we can try this again”.