UNPKG

@mahdi.golzar/jwtauthenticator

Version:

JWTAuthenticator is a simple utility for managing authentication using JSON Web Tokens (JWT). It provides methods for generating, verifying, and decoding JWTs in a Node.js environment without relying on external libraries.

68 lines (54 loc) 1.78 kB
const crypto = require('crypto'); class JWTAuthenticator { constructor(secretKey) { if (!secretKey) { throw new Error('A secret key is required'); } this.secretKey = secretKey; this.algorithm = 'HS256'; } base64UrlEncode(data) { return Buffer.from(JSON.stringify(data)) .toString('base64') .replace(/=/g, '') .replace(/\+/g, '-') .replace(/\//g, '_'); } base64UrlDecode(base64UrlString) { return JSON.parse( Buffer.from(base64UrlString, 'base64').toString('utf8') ); } sign(data) { return crypto .createHmac('sha256', this.secretKey) .update(data) .digest('base64') .replace(/=/g, '') .replace(/\+/g, '-') .replace(/\//g, '_'); } generateToken(payload, expiresInSeconds) { const header = this.base64UrlEncode({ alg: this.algorithm, typ: 'JWT' }); const exp = Math.floor(Date.now() / 1000) + expiresInSeconds; const body = this.base64UrlEncode({ ...payload, exp }); const signature = this.sign(`${header}.${body}`); return `${header}.${body}.${signature}`; } verifyToken(token) { const [header, body, signature] = token.split('.'); const validSignature = this.sign(`${header}.${body}`); if (validSignature !== signature) { return false; } const payload = this.base64UrlDecode(body); if (payload.exp < Math.floor(Date.now() / 1000)) { return false; } return payload; } decodeToken(token) { const [, body] = token.split('.'); return this.base64UrlDecode(body); } }