Generate JSON Webtoken with NodeJs

In this post, we will use NodeJS and npm packages to connect to an API secured with JWT bearer tokens. Firstly we will explore how we can generate a valid JWT web token, followed by attaching the token to the API request.

There are many libraries and frameworks that have native support for generating a valid JWT, for example, JWT-Dotnet (source), but we will be using Jsonwebtoken npm package. Include the below code into a .js script file. Next, we will install the needed packages using npm.

The script uses npm libraries to generate JWT web tokens.
const jwt = require('jsonwebtoken')
const fs = require('fs');
var tkn = jwt.sign({ sub: 'tkn_data' }, 'secret_or_private_key');
fs.writeFile("returnedJson.json", tkn, (err) => {
    if (err) { return console.log(err); }
npm install jsonwebtoken --save-dev
npm install fs --save-dev
node generate_jsonwebtoken.js

Use the node to run the generate_jsonwebtoken.js script to generate returnedJson.json containing the JWT.

returnedJson.json file generated after running generate_jsonwebtoken.js in node

Using a Restful HTTP client such as REST Client (source), attach the generated JWT to the Authorization header of the request. To check that the JWT token generated is valid, you can use a JWT validator such as the one found on (source)

REST Client tool used to make HTTP RESTful requests using Authorization header JWT web token

Leave a Reply

Your email address will not be published. Required fields are marked *