Features
- Sign JWT in Node.js without using built-in Crypto Module
Dependencies
- crypto-js // stand-alone library (as of version 4.1.1)
Type Dependencies
Features
Dependencies
Type Dependencies
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}`; | |
}; |