The Authentication and Authorization flows are difficult to get right without concrete examples. NestJs doc has a good example for JWT tokens, however I find it difficult to establish the correct flow.
Here is the closest I have been able to get to solve the authorization flow:
- after authentication, store refresh token in DB (which I don't like much but couldn't find an easier way to handle it), send access token to Angular and keep it in local storage or a cookie
- On every request send the access token and check if it's still valid and not close to expiry; if it's expired or about to expire, then go to the DB, get the refresh token and use it to acquire a new access token. I would very much liked to have refresh token stored in a cookie too, but the problem with that is that I don't know how to get more than Authorization header when implementing the JwtStrategy, and what's the best (if any) way to attach the refresh token
- If access token is updated, somehow send it back to the Angular side to be replaced. send the expired time as well so Angular side doesn't replace a newer access token with an older one if there are concurrent requests. But concurrent requests still have a chance of running into a race condition and each, separately, requesting an access token.
There are a bunch of details that are missing in the summary above, but that should give the overall flow that I am trying to implement. The two challenges I have right now is:
- The possibility of multiple concurrent requests, all finding out that access token is about to expire and trying to refresh it at once.
- How to add the new access token and expiry timestamp to response header (or body if it should be there), in JwtStrategy itself so the whole auth cycle can be handled with one single annotation/guard.
I appreciate if somebody can help with the above two questions.
Also, I am not sure if it complies with SO policies, but since there is no solid material for the NestJs/Angular/Cognito combination, and since auth is the most important part of a secure webpage. I will be happy to grant some bounties for someone who can put a full working example in github that demonstrates fully how both authentication and authorization (both access and refresh tokens) flows are implemented using best practices.
Finally, here are the best (only?) resources I have found and used so far for NestJs/Cognito combo; none really get to answer the above questions.