0
votes

Objective- Access token is included in the request to see the user-specific content like profile, orders, etc. Now, when such resources requested from angular app, I'm checking for the validity of the access token and if it is expired then return specific code - ERR_TKN_EXP from my backend, within an interceptor, I check for this error code and accordingly want to trigger a http request to generate a new token on the backend. Here the HTTP request is not being initialized from Interceptor.

What I have tried :

Interceptor:

return next.handle(request).pipe(catchError(err => {

      //const error = err.error.message || err.statusText;

      const resError = err.error;

      // Handle token expired case to generate a new token
      if (err.status === 401 && resError.error.code == 'ERR_TKN_EXP') {
        this.authService.refreshToken();


      }
  }))

AuthService - refreshToken function.

 refreshToken(){

    this.generate_ac_tkn = true;

    let refTokenParams = {
      'auth-token' : this.ac_tkn,

    }

    alert("refreshToken");

    return  this.http.post(API_END_POINT + 'refresh-token', refTokenParams, {withCredentials: true})
    .map((res: Response) => {
      alert("refreshToken-Call");

    });
  }

As per the above code, when a server returns ERR_TKN_EXP code, interceptor checks this code and accordingly call function to refresh the token. As I tried to trace the issue, "refreshToken" alerted, but can not see the alert box for "refreshToken-Call" that means http post request is not happening.

Can anyone suggest what went wrong here.

Thank you.

1
You have no subscriber to the .refreshToken() method, thus it does not run. Just write return this.authService.refreshToken(); and it should work. - Philipp Meissner
great, thank you Philipp. your answer resolved my issue. - Newbie
You're welcome. I will add it as an official answer so you can accept it. - Philipp Meissner

1 Answers

0
votes

The refreshToken method does in fact return an Observable, but you do not subscribe to it therefore it does not run.

Change your interceptor so that it also passes the return value of refreshToken further. Angular will then internally subscribe to the return value of the interceptor.

return next.handle(request).pipe(catchError(err => {
  const resError = err.error;

  if (err.status === 401 && resError.error.code == 'ERR_TKN_EXP') {
    return this.authService.refreshToken();
  }

  return EMPTY;
}))