Creating Signed JWTs (JWS) with Node.JS

When you're working with JSON Web Tokens (JWTs), you'll almost certainly be validating that the contents of the token is sent by the correct service by verifying the token's signature.

However, it's also helpful to be able to create these signed JWTs for yourself, which we can do using the [jsonwebtoken library][jsonwebtoken] (v8.5.1) Node.JS library (tested using v8.5.1):

const fs = require('fs');
const jwt = require('jsonwebtoken');

const args = process.argv.slice(2);

const payload = fs
  .readFileSync(args[0])
  .toString();

const secretOrPrivateKey = fs
  .readFileSync(args[1])
  .toString()
  // required to handle newlines at the end of file, otherwise jsonwebtoken
  // doesn't like it!
  .replace(/\n$/, '');

const algorithm = args[2] || 'HS256';

console.log(jwt.sign(payload, secretOrPrivateKey, {algorithm: algorithm}));

Which we can run like so, and will output the JWS to the console:

$ node sign.js payload.json file-with-secret 'HS256'
$ node sign.js payload.json rsa.key 'RS256'

Written by Jamie Tanna's profile image Jamie Tanna on , and last updated on .

Content for this article is shared under the terms of the Creative Commons Attribution Non Commercial Share Alike 4.0 International, and code is shared under the Apache License 2.0.

Tags

This post was filed under articles.

Related Posts

Other posts you may be interested in:

Interactions with this post

Interactions with this post

Below you can find the interactions that this page has had using WebMention.

Have you written a response to this post? Let me know the URL:

Do you not have a website set up with WebMention capabilities? You can use Comment Parade.