0

I'm implementing a JWT system in my Angular app, and in this case, in an Http Interceptor.

My "issue" is that the code below :

request = request.clone({
        setHeaders: {
          Authorization: `Bearer ${token}`
        }
      });

is trigerred before :

this.authService.refreshToken(token_refresh).subscribe(
            response => {
              localStorage.setItem('token', response.token);
              token = response.token;
            }
          );

Which is a normal behavior due to the asynchronous nature of the subscribe function, but in my case, I need the token in the setHeaders to be up to date, because is takes the older token which is invalid at this point.

I tried to make refreshtoken() return a promise with async await, but it didn't change anything.

Here's the whole code block :

 let token = localStorage.getItem('token');
 // if token is not valid or not set
  if ((this.jwtHelper.isTokenExpired(token) || token === null)) {
    if (token_refresh !== null) {
      // if token_refresh exists and is valid
      this.authService.refreshToken(token_refresh).subscribe(
        response => {
          localStorage.setItem('token', response.token);
          token = response.token;
        }
      );
    } else {
      // if no token_refresh exists or is expired
      this.router.navigate(['/register']);
    }
  }

  // always executed
  request = request.clone({
    setHeaders: {
      Authorization: `Bearer ${token}`
    }
  });
naspy971
  • 1,137
  • 2
  • 13
  • 31

1 Answers1

0
 let token = localStorage.getItem('token');
 // if token is not valid or not set
  if ((this.jwtHelper.isTokenExpired(token) || token === null)) {
    if (token_refresh !== null) {
      // if token_refresh exists and is valid
      this.authService.refreshToken(token_refresh).subscribe(
        response => {
          localStorage.setItem('token', response.token);
          token = response.token;
          request = request.clone({
             setHeaders: {
                Authorization: `Bearer ${token}`
             }
          });
        }
      );
    } else {
      // if no token_refresh exists or is expired
      this.router.navigate(['/register']);
    }
  } else {
     request = request.clone({
       setHeaders: {
         Authorization: `Bearer ${token}`
     }
  });
  }

You can an else block to execute if you don't need to refresh the token, and add that code block again after you get a fresh token.

  • I also tried this trick with "if else" conditions but the problem is the same, whilst subscribe is loading its stuff, the flow continues and it will look for what's after this if else block statement, and in this case there's the return next.handle(request); and now it doesn't event have a token in its header – naspy971 Jan 28 '21 at 18:48