1

I have an application that gets a JWT from his backend. This JWT is valid for 15 minutes. When I send the JWT from the frontend to the backend, a HTTP interceptor appends the JWT to the Authorization header.

What I try to do is:

In the Http interceptor check if the token is still valid, if not send a request to the backends endpoint to get a new JWT.

My problem is: if I intercept every call to append the header, I will walk into a loop if I do a http request in the interceptor itself.

This is my interceptor:

intercept(req: HttpRequest<any>, next: HttpHandler) {
  let authReq = req;
  const token = this.userService.getUserInfo()?.token;
  const jwtHelper: JwtHelperService = new JwtHelperService();
  if (token != null) {
    if (!jwtHelper.isTokenExpired(token)) {
      authReq = req.clone({headers: req.headers.set(TOKEN_HEADER_KEY, 'Bearer ' + token)});
    } else {
      this.authenticationService.getToken();
    return;
    }
  }
  return next.handle(authReq);
}

What is the right way to do this?

1 Answer 1

3

The server should handle the validity of the token, it's not the client's logic.

Send the request with the token, if the response will have a 401/403/whatever status send a request for a new token.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.