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?