2

I am new to refresh tokens and I cannot get my application to work. Once the JWT_TOKEN expires, I cannot connect to my refresh api route to refresh the token. I get the error:

Failed to load resource: the server responded with a status of 401 (Unauthorized)

I cannot figure out what is wrong.

Here is some of my code:

  refreshToken() {
    return this.http.post<any>(environment.apiBaseUrl + '/refresh', {
      'refreshToken': this.getRefreshToken()
    }).pipe(tap((tokens: Tokens) => {
      console.log('token', tokens);
      this.storeJwtToken(tokens.jwt);
    }));
  }
module.exports.refresh = (req, res, next) => {
  const refreshToken = req.body.refreshToken;

  if (refreshToken in refreshTokens) {
    /* Possible error in assignment */
    const user = {
      'email': refreshTokens[refreshToken].email,
      'fullName': refreshTokens[refreshToken].fullName
    }
    const token = jwt.sign(user, 'anything', {expiresIn: 2000});
    res.json({jwt: token})
  }
  else {
    res.sendStatus(401);
  }
}
  private handle401Error(request: HttpRequest<any>, next: HttpHandler) {
    if (!this.isRefreshing) {
      this.isRefreshing = true;
      this.refreshTokenSubject.next(null);
      console.log('good');
      return this.authService.refreshToken().pipe(
        switchMap((token: any) => {
          console.log('token', token);
          this.isRefreshing = false;
          this.refreshTokenSubject.next(token.jwt);
          return next.handle(this.addToken(request, token.jwt));
        }));

    } else {
      return this.refreshTokenSubject.pipe(
        filter(token => token != null),
        take(1),
        switchMap(jwt => {
          return next.handle(this.addToken(request, jwt));
        }));
    }
  }
  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    if (this.authService.getJwtToken()) {
      request = this.addToken(request, this.authService.getJwtToken());
      console.log("Request:", this.addToken(request, this.authService.getJwtToken()));
      console.log("Request:", request, this.authService.getJwtToken());
    }

    return next.handle(request).pipe(catchError(error => {
      if (error instanceof HttpErrorResponse && error.status === 401) {
        console.log('TM Error 401', error);
        return this.handle401Error(request, next);
      } else {
        console.log('TM Error else', error);
        return throwError(error);
      }
    }));
  }
exports.verifyJwtToken = (req, res, next) => {
  if ('authorization' in req.headers) {
    const token = req.headers['authorization'].split(' ')[1];
    console.log('token', token);
    jwt.verify(token, '*****',
      (err, decoded) => {
        if (err) {
          console.log(err);
          res.status(401).send({ auth: false, message: 'Token authentication failed.' });
        }
        else {
          console.log(decoded);
          req.user = decoded;
          console.log("req.user", req.user);
          next();
        }
      })
  } else {
    res.status(403).send({ auth: false, message: 'No token provided.' });
  }
}
Jonathan
  • 441
  • 1
  • 9
  • 28

1 Answers1

1

The refresh Token Service Must Be Open, Because you check the expired token and Unauthorized Error Raisaed.

Refresh Token service Just get old token and return new valid Token. and it should skip the check for expire token.

check this for more info

Masoud Bimmar
  • 6,941
  • 4
  • 30
  • 33
  • I’m confused on what you mean by open. Also, if I do this I will be able to get data from the API? – Jonathan Jan 09 '20 at 06:55
  • 1
    if you refresh token before the current expire for example every call renew token, everything goes write, but if you refresh after expiring token it means you cant use current token for calling authorized service, then you have to call a Unprotected service to refresh your token – Masoud Bimmar Jan 09 '20 at 07:04