How to decode a JWT token in node js with and without using external libraries?

OAuth is a very popular authentication mechanism used on web apps.

Using Json Web Tokens for authentication is one of OAuth concepts.

You can secure your API using JSON Web tokens.

The party who calls your API need to send a valid JWT to access your API.

This JWT has three parts: header, payload and signature all encoded.

Here is a sample JWT:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c

In your API you need to decode this JWT to extract the payload.

(You can verify this on jwt.io website as well):

Let’s see how to decode a JWT in node js first using a library and then using node js itself.

Using jsonwebtoken library:

For this to work install “jsonwebtoken” dependency using npm install jsonwebtoken command.

Then import the library in your code:

const jwt = require("jsonwebtoken");

Then use the decode method :


const token =
  "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c";
 const decoded = jwt.decode(token);

Here is the entire code of a sample implementation:

const express = require("express");
const cors = require("cors");

const app = express();

const jwt = require("jsonwebtoken");

const token =
  "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c";

app.use(cors());

app.get("/test", (req, res) => {
  const decoded = jwt.decode(token);
  console.log(decoded);

  res.send(decoded);
});

app.listen(3000, () => {
  console.log("Server listening on port 3000");
});

Start the node app using node index.js command and hit /test api.

You will get the below output:

Without using library:

You can achieve the same without using jsonwebtoken by using JSON class of node js.

Here is the code:


const decoded = JSON.parse(
    Buffer.from(token.split(".")[1], "base64").toString()
  );

Here is the full code:

const express = require("express");
const cors = require("cors");

const app = express();

const token =
  "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c";

app.use(cors());

app.get("/test", (req, res) => {
  const decoded = JSON.parse(
    Buffer.from(token.split(".")[1], "base64").toString()
  );
  console.log(decoded);

  res.send(decoded);
});

app.listen(3000, () => {
  console.log("Server listening on port 3000");
});

And it produces the same output:

That’s it!


Posted

in

by

Comments

Leave a Reply

Discover more from The Full Stack Developer

Subscribe now to keep reading and get access to the full archive.

Continue reading