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 JWT.io (source)

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

One Reply to “Generate JSON Webtoken with NodeJs”

  1. Hello there I am so delighted I found your website, I really found you by accident, while I was looking on Askjeeve for something else, Nonetheless I am here now and would just like to say thanks for a fantastic post and a all round exciting blog (I also love the theme/design), I don’t have time to go through it all at the moment but I have saved it and also added in your RSS feeds, so when I have time I will be back to read a lot more, Please do keep up the superb jo.|

Leave a Reply

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