JWT refreshing with refresh token - node.js

I am building SPA app with its rest API and I cannot find information when I should refresh JWT using refresh token. Should I do this when I will receive 401 HTTP status from server (JWT expired) or for example every 15 minutes if possible (before JWT will expire)?

I'm not a security expert, but as far we know, we
1- login and save the received token
2- we put one interceptor that check every response (in angular it's easy, in react we usually use axios ...etc)
3- we check every response in the interceptor, if the response was 401 and the expiration date from the token has passed, we send a refresh token request and save the new token
to check expiration date you can use a library that decode the token like: jwt-decode on npm, (don't forget to wrap the process in try...catch in case somebody screw with the token) and you even can paste the token in https://jwt.io/ and see for your self the decoded token and check the expiration date.
4- repeat the last request with the new token should succeed.
5- if for example even the refresh token request failed, simply redirect the user to the login page

If the server is sending a proper error code in case of access_token expired then you can intercept the error code on the client-side and use the refresh_token you got earlier during authentication to get a new access token. You can repeat this process again and again until your refresh token gets expired. On that occasion, you should redirect the user to perform the authentication to get both the tokens.

Related

Should i logout a user if access token is malformed?

I am creating a Node js / Express js based, login registration system using JWT (i am using JSONWEBTOKEN npm library).
Whenever a user login, that user gets a pair of access and refresh token. Now for accessing resources user need to send access token to backend.
Now when i verify the access token send by user to backend and if it will not get verified then it produces three types of error (as mentioned is JSONWEBTOKEN library in npm):
Token Expired Error: If i get this error, then in that case i will send response to frontend to send the request to refresh token route to get a new pair of access and refresh token.
JsonWebTokenError: If i get this error then it means that access token is malformed. Then in this case what should i do? Should i logout a user or should i will send a response to frontend to send request to refresh token route to get a new pair of access and refresh token. <-- This is the main question should i logout a user?
NotBeforeError: Since i am not using nbf claim and then in that case i dont need to worry about it.
Please provide your useful suggestion. while building backend security plays an important role.
This is useful to read: JWT refresh token flow.
Talking short, you should logout user if refresh token malformed or expired.
According to JWT idea, access token is short-life token. When it doesn't pass validation due to malformed or expired you have to send refresh token to server to get new pair. User continues to work using new access token without interruption.
If JWT is malformed then just block that call by responding with 403. that's fine. The application then takes the decision on it to refresh the token or not.
When a user logs out please revoke the issued token even if it is a JWT.
JWT also needs to be revoked as best practice. Yes, JWTs are self tokens and expirations already part of themselves. But if user logs out and still their JWTs are not expired means someone can use that token to call different APIs. So it is a security breach.
To avoid such things we should maintain JTI claim of that JWT in our backend with the same TTL with the value of JWT "exp". When the user logs out we have to clear those JTIs and notifcy the API callers about this just putting into some event service from their API Gateways should get to be notified and clear their side cached tokens if anything and cross check with identity system (Introspection).
This is we have to design the system to avoid further security related issues.
First thing is that user will be logged out from front end side.
front end will send request to your node server and token will be verified. Server will only send the response that token is expired or malformed and based on that front end will perform the action.
If token is expired then request for new token.
Is token is malformed then based on your requirements you can show results to your end user. You can either logout user or you can show unauthorized page too.
Suppose, you have role based website and some unauthorized user is trying to access root level routes then you can show unauthorized page.

How can I create JWT refresh token on node js?

I am using a simple JWT auth firebase. backend checks if its a valid user and gives back an access token using JWT. Now I want to implement a refresh token. How can I do it? What should be the content of the refresh token? When I sign a new access token and go to protected a page but when fresh it, it go to login page again.
what should I do to also sign a refresh token? please help me anyone.
when you are generating JWT auth token generate refresh token with 1d or with no expiry time according to you requirement. After this send JWT and JWT-REFRESH token in the response of login API, after this make an API in your backend which accepts the refresh token from header or from body and in response generate a JWT token, in case of bad refresh token return 401 status code.
At client side if you are using axios, you can use axios-interceptors as a middle to detect if 401 is coming from any API, then in that case hit the refresh JWT token API to generate new auth token.
If refresh token API gives again 401 response then handle it as REFRESH token is also expire and redirect the user into login page.

How to regenerate Refresh Token and Access Token on Resource Request?

I am trying implementing JWT Tokens(Access tokens and Refresh tokens), but I come to an issue on requesting a protected resource with an expired access token, while the refresh token is still valid.
I know that I should not use refresh tokens to request resources, refresh tokens should be used against authorization validators to revalidate/regenerate access tokens.
In my app, the User can log in by POST request with a valid credential to get Access token(exp. in 1min) and Refresh token(exp. in 10min.). Say now User making a request 30 sec later of login and sends both tokens, then tokens get checked and resource comes back. If now user makes a request after 2min and sends tokens, his access token is Invalid, in this scenario how can I proceed with the request and revalidate tokens.
I can think of middleware to validate and provide tokens and send that with the response, but is this the right approach?
Then I need to handle and restore tokens on the client-side for every response. Don't I?
Also, I do not want to prompt users to re-login. I am using Node and Express for Server and React on Client.
Here are your steps:
Try to login
Receive 401 from server when token is invalid
Request a new access token by making a new refresh request.
Set the new access token and refresh token
Retry original request
This has to be done on the client side because it is the audience that gets validated for authorization.
Usually we don't set the access token to expire every minute because the described process would add too much latency to the process.
Edit from #MComment:
5 min for access tokens and 30 min up to a few hours is what is generally recommended for respectively access and refresh tokens. Usually Authorization Servers offer "rolling refresh" - refresh token's expiration is renewed whenever you use it. This way a user stays logged in as long as they are actively using the website
You can update expired date of access token in every request, no need to regenerate token.
I think session time you set is not normal and recommended.
If you dont want user must re-login, make a forever refresh token, create a function in reactjs for re-generate access token by refresh token if it expired.
Revoke refresh token only when u want to logout from this client.

JWT refresh token in React+NodeJS

working on a small project and got some authentication going on with jwt tokens, the whole procedure looks like this:
Generate jwt token on auth/register along with a refreshToken
Make requests with the token
If the token is expired, I query the requesting user and his refreshToken, comparing his current request refreshToken and database token
If tokens match, I generate a new token and a new refresh token.
The whole problem is 5th step, lets say i make a request to "/me/friends" and along the way my token expires, I then make a new one out of my refreshToken, but I do not understand how should I return the token back to front-end on "me/friends" api call as it returns an array of specific fields and token has nothing to do with it. I just cant get my head around on how this is supposed to work, can anyone assist me please?
How are you storing your token on the client side? The easiest method is to just store it in a cookie. In that case, Step 5 just becomes setting an updated cookie with the request.
Another option is to return a 401-Unauthorized from your endpoint, then on the client side you can handle a 401 status code by trying to refresh the token manually and then retrying the request.
But I think option 1 is preferable if you're not using some sort of authentication middleware that doesn't hit the endpoint at all if auth is expired.

On which side the access_token needs to be updated

Since an access_token has a short life period, for the users' convenience a refresh_token is used.
Let's imagine we have client side mobile iOs/android app. After the first login when the user provides his username and credentials then the subsequent request is sent to the server side which respond with access and refresh token.
But what if 1 minute left before access token expires or it has already expired. Should verification process be on the server side?
Server get a request (gateway proxy as example), read auth token from header, verify expiration time, under the hood update token if refresh token is present (in header as example), modify initial request and proceed with newly created access_token?
Or this kind of iterations should perform client app? On each request validate expires_in date and if so ask for a new access_token using refresh_token grant type and only after this make a remote call?
According to OAuth, when your initial token expires, depending the situation, you should refresh it by sending the refresh_token value to the respective server endpoint. Server does the refreshing operation generating a new token so you get a new token with a new expires_in date. You get many options on how you should send the refresh the token by the client, for example:
Having a timer and send the refresh action before token expiration.
If you have a 401 status error.
I would suggest you coding a HTTP interceptor and when a response get a 401 code, you should send the refresh action.

Resources