I'm trying to build RESTful API using NodeJS but having trouble understanding right way to authenticate user using tokens during api calls. After reading some blogs and articles I came up with these approaches:
Approach 1:
Access Token(AT) is JWT token containing unique userId as JWT payload. Expires in 1 day.
Refresh Token(RT) is random uuid using uuid npm package. Stored in database alongside user document.
Process:
- When user signin/signup server issues new AT+RT.
- If AT expires user sends request to /refresh-token route with AT+RT. Server check for correctness of RT by matching RT stored in db with RT given by user and decodes userId present in AT if AT is a valid JWT token. If every thing goes well RT is correct and AT is a valid JWT token, server issues a new AT and send it to user.
In above approach refresh token does not expires so if RT comes in hand of an malicious client then he can issue n number of access token and make calls to apis using them until a user signin again and server generates new pair of AT+RT. so RT in hands of attacker is of no use.
Approach 2:
Based on Request token rotation read on AuthO docs on refresh token
Access Token(AT) is JWT token containing unique userId as JWT payload. Expires in 1 day.
Referesh Token(RT) is JWT token. Expires in 4-5 month. Stored in DB as array of refresh tokens alonside user document.
Process:
- When user signin/signup server issues new pair of AT+RT and pushes RT in array of refresh tokens stored in db.
- When AT expires user requests to /request-token route with old pair of AT+RT and server generates new pair of AT+RT also stores
For above approach if tokens comes in hand of malicious client then server can detect it using following approach describe in below image.
Implementation for above approach of Reuse Detections of token in nodejs can be: if malicious client generates new AT+RT pair and legitimate user makes requests to /request-token route (unaware of malicious client has generated new AT+RT which make user pair invalidated). Server along with checking if AT+RT are valid can check if that AT+RT are both signed using by using its secret and if RT given by user is present in arrays of refresh token if found that means refresh token is reused and can be possible that tokens are leaked or stolen which deletes all that refresh tokens issued and asks user to login again.
my questions are:
Which approach should i use? and are that right way of implementing authentication?
OR Should i use another approach? (In this case plz suggest)