Error 401 on Angular-NestJs page when refreshing token with Auth0

41 views Asked by At

I have created an application with Angular as Frontend and NestJs as Backend using Auth0 as authentication system.

In Angular I have put the authentication button and it works correctly. When the user authenticates, the request to /token is made correctly and this value is used to add it to the headers that will make the requests to the NestJS API. It works correctly, however, when a new request is made to /token (for example when refreshing the page), when sending the token through the headers, I receive a 401 error from NestJS.

I have to say that NestJS uses Passport JWT as authentication strategy.

I have not been able to determine why it does not work on subsequent requests (but it does on the first one). Am I missing something?

2

There are 2 answers

1
Marc Fernandez On BEST ANSWER

I fixed the issue by adding the issuer parameter in the Angular interceptor configuration that adds the token in the API request headers. That way the API can now correctly validate the refreshed tokens.

3
Andrey Etumyan On

I'm not sure why you get "401 Unauthorized" in case "Authorization" header forming and sending to the API server correctly.

But generally I believe you shouldn't request a new token such often (like every page reload) but only once the current token get expired or a little earlier.

So once you've got 401 error on any endpoint (probably except GET /token and so on in your setup) it's the right time to request a new token. In some scenarios it might be better to made it a bit sooner, based on something like iat (issued at) property encoded to the token. You can check what is inside yours here https://jwt.io.

Also in case of Angular most likely you'll implement token refresh logic inside an interceptor like so.