Skip to content

Instantly share code, notes, and snippets.

@hyunbinseo
Last active October 2, 2021 08:06
Show Gist options
  • Save hyunbinseo/9899f8cc00589e56a8d4dc6cac0fe4a8 to your computer and use it in GitHub Desktop.
Save hyunbinseo/9899f8cc00589e56a8d4dc6cac0fe4a8 to your computer and use it in GitHub Desktop.
Sign JWT in Node.js using crypto-js library
import { generateJWT } from './jwt';
import type { JwtPayload } from 'jsonwebtoken';
// Sample PayLoad and Secret from https://jwt.io/
const jwtPayLoad: JwtPayload = {
sub: '1234567890',
name: 'John Doe',
iat: 1516239022
};
const jwtSecret = 'your-256-bit-secret';
const jwt = generateJWT(jwtPayLoad, jwtSecret);
// eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
import HmacSHA256 from 'crypto-js/hmac-sha256.js';
import Base64 from 'crypto-js/enc-base64.js';
import type { JwtHeader, JwtPayload } from 'jsonwebtoken';
/**
* JWS requires base64url encoding without padding
* https://datatracker.ietf.org/doc/html/rfc7515#appendix-C
*/
const base64UrlConvert = (base64: string): string => (
base64
.replace(/[=]/g, '')
.replace(/\+/g, '-')
.replace(/\//g, '_')
);
const base64UrlEncode = (string: string): string => (
base64UrlConvert(Buffer.from(string).toString('base64'))
);
export const generateJWT = (
jwtPayLoad: JwtPayload,
jwtSecret: string,
jwtHeader?: JwtHeader
): string => {
const jwtHeaderDefault: JwtHeader = {
alg: 'HS256', // Using HmacSHA256 to hash
typ: 'JWT'
};
/**
* Convert JSON to string
* Encode string to base64Url
*/
const header = base64UrlEncode(JSON.stringify({
...(jwtHeader || {}), // jwtHeader is optional parameter
...jwtHeaderDefault // Overwrite provided JWT Header
}));
const payLoad = base64UrlEncode(JSON.stringify(jwtPayLoad));
/**
* Hash string using HMAC-SHA256
* Stringify hash to base64Url
*/
const verifySignature = base64UrlConvert(Base64.stringify(HmacSHA256(
`${header}.${payLoad}`,
jwtSecret
)));
return `${header}.${payLoad}.${verifySignature}`;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment