How to Secure Node js Rest API with JWT

javascript-logo

What is a JSON Web Token or JWT?

JSON Web Token or JWT is a JSON based access token for securely transmitting information between two or more parties. The information in the JSON Web Token can be verified and trusted because it is digitally signed. Every JSON Web Token can be signed with public or private key. Generally, a server will generate and sign a token and provide that to a client, for example, the client could use that token to prove that is it logged in, and both client and the server can verify the legitimacy of the token. Every JWT has three parts: header, payload, and signature. Most of the time the JSON Web Token is used for authentication but it can be used for secure information exchange too.

JWT structure example:

Header:
{
  "alg": "HS256",
  "typ": "JWT"
}
Payload:
{
  "name": "John Doe",
  "admin": true
}
Signature:
HMACSHA256(
  base64UrlEncode(header) + "." +
  base64UrlEncode(payload),
  secret)

The header contains the information about the algorithm used for the encryption of the JWT, the payload is the data included in the JWT and the signature encrypted string, and it is not readable because it is encrypted with the secret key.

Signin of the JSON Web Token

To use JWT or JSON Web Token in your Node js app, you need to install an NPM package with the command npm i jsonwebtoken in your node js project, and after the installation you will need to import the package and generate the JSON Web Token.

Let's see an example of signin the jwt:

var jwt = require('jsonwebtoken');  //Importing the jwt npm package

//Asynchronously singing (creating) a Json Web Token
jwt.sign({ data: 'foobar', exp: Math.floor(Date.now() / 1000) + (60 * 60),}, privateKey, { algorithm: 'RS256' }, (err, token) => {
  console.log(token);
});

In the previous example we are calling sing() on the JWT object, and we are passing the data as the first parameter, the second parameter is the token expiration time, in our case it is one hour, after that we are passing the private key, which can be something we will keep away from others, and the last one is the algorithm. After that we will recive the token from the callback and we can send the token to the client (front-end app).

Verifying the JSON Web Token

When we receive the request from the client (front-end app) we need to verify the JWT that was signed by our back-end.

Let's see an example of verifying the jwt:

//Asynchronously verifying a Json Web Token
jwt.verify(token, privateKey, (err, decoded) => {
  console.log(decoded.foo) // bar
});

In our example, we are calling verify() on the jwt object, and we are passing the received token from the client (front-end) as our first parameter, the second parameter is the private key that we have entered in our sign-in on the token. There is also a synchronous way to sign and verify JSON Web Token and much more in the documentation of the NPM package. It is also possible of throwing errors durning the token verification process.

Error object can look like these:

err = {
  name: 'TokenExpiredError',
  message: 'jwt expired',
  expiredAt: 1408620000
}

Using JWT for securing and authenticating Rest API is the most recommended way, it is beneficial because the token can be consumed (used) by almost every front-end app including web browsers and mobile apps, and it is much more secure than the older way of using sessions. You can practice with generating and verifying the concept of JSON Web Tokens on the jwt.io.




#nodejs #expressjs #javascript #jsonwebtoken #jwt

Author: Aleksandar Vasilevski |

Loading...