Refresh Token implementation with JWT authentication and Node.JS

Posted By : Lokesh Singh | 29-Apr-2021

 

1. Introduction

  • Authentication - Authentication is divided based on how they verify the user
    • Based on Known (User Password)
    • Based on something possessed (ID, USB, token)
    • Based on physical characteristics(voice, fingerprints, eyes)
  • Token Authentication - Token is used in modern web applications for authentication and authorization. It uses the OAuth protocol. 

When we describe authentication with tokens, we can divide it into two types:

  1. Status-full authentication-based authentication - When a user log-in, the server returns a token that is typically stored in a cookie. The server saves the session information, either in memory or in a database (Redis, MongoDB), then each time user makes a request with that token, the server searches this information that the user is trying to access, and if it is valid, it executes the requested method.
  2. Statusless authentication - When the user is authenticated with his credentials or any other method, the user receives an access token in response. From there on all requests made to the API will carry this token in an HTTP header so the server can identify which user makes the request without having to search the database or any other request to the storage system.
  • JWT(JSON Web Token) - This is an open standard based on JSON to create an access token that allows the use of application or API resources. This token will take the information of the user who needs the server to identify it, as well as information that is useful.

A JWT token consists of 3 parts.

  1. Header: with the type(JWT) and type of coding
{
“Alg”: “HS256”,
“Typ”: “JWT” 
}
  1. Payload: It is the User's Information that allows the server to check access
{
name: “User Name”,
email: “[email protected]”,
exp:  344565858
}
  1. Signature: The signature function will be applied to the other two token fields to get the check field 

2. Types Of Token

In authentication with JSON web token, the most commonly used are access token and refresh token.

A. Access Token - It Contains Information to know if the user/ device can access the resources you are requesting or not. They are valid for some time only.

B. Refresh Token - This token is used to get the new access token. It has an expiration date once it gets expires user has to authenticate again to get the access token. This token requires greater security when it is stored so no third parties can access it.

3. Refresh Token and JWT. Implementation in Node.js

The first thing we add is a method to authenticate the user. This method can be any method, although the most used is username and password. In response to this request, we will return both the JWT token and the refresh token with which you can request new access tokens. As we will make the access token valid for 300 seconds(5 min).

With the JSON web token module, we will generate and encrypt the signature, it will automatically generate the JWT token by simply passing it the object to encrypt and the key that we use for both encrypt and decrypt afterward.

Refresh Token, we will generate UID and store it in an object in the database with the associated username and creation and expiration date (We make it valid for a limited period of time).

var bodyParser = require(‘body-parser’);
var jwt = require(‘jsonwebtoken’);
var randToken = require(‘rand-token’);
Var refreshToken = {};
Var SECRET = ‘SECRET_PAR_STRING’;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.post(‘/login’, function (req, res, next) {
Var username = req.bosy.username;
Var password = req.body.password;
Var user = {
Username: username,
Role: admin
}
Var token = jwt.sign(user, SECRET, {expiresIn: 300})
Var refreshToken = refreshtoken.uid(256);
refreshTokens[refreshToken] = username res.json({ token: ‘JWT’ + token, refreshToken: refreshToken})
});

To request a new access token we have created the /token endpoint. In it, we receive a refresh token and as an additional control the username of the user who owns the refresh token. Here what we do is check that in our list of refresh tokens the associated user’s information is correct and then we generate a new token with the user’s information and return it.

app.post(‘/token’, function (req, res, next) {
Var username = req.body.username;
Var refreshToken = req.body.refreshToken;
If ((refreshToken in refreshToken) && (refreshTokens[refreshToken] === username)) {
Var user = {
Username: username,
Role: admin
}
Var token = jwt.sign(user, SECRET , {expiresIn: 300})
res.json({token: ‘JWT’ + token})
} else {
res.send(400);
}
})

4. Conclusion

Using JSON Web Token allows us to increase the effectiveness of our application by avoiding multiple database calls and reduce latency. And we use these refresh tokens to improve the security and scalability of the application.


 

 

About Author

Author Image
Lokesh Singh

He is Hard Working and Punctual and keen to learn new technologies. He works as both Full Stack Developer and MEAN Stack Developer on both frontend and backend technologies.

Request for Proposal

Name is required

Comment is required

Sending message..