@jnode/auth
Simple authorization package for Node.js.
Installation
npm i @jnode/auth
Quick start
Import
const { AuthService } = require('@jnode/auth');
const crypto = require('crypto');
Basic usage
const { publicKey, privateKey } = crypto.generateKeyPairSync('rsa', {
modulusLength: 2048,
});
const auth = new AuthService(publicKey, privateKey);
const token = auth.signToken({ alg: 'RSA-SHA256' }, { userId: 123, role: 'admin' });
try {
const decoded = auth.verifyToken(token);
console.log('Decoded:', decoded);
} catch (err) {
console.error('Verification failed:', err.message);
}
How it works?
@jnode/auth provides a lightweight and binary-safe alternative to JWT, focusing on a straightforward token format encoded in base64url.
The token structure is as follows:
- Header Length: 2 bytes (UInt16BE)
- Header JSON: n bytes
- Payload Length: 2 bytes (UInt16BE)
- Payload JSON: n bytes
- Signature: RSA-SHA256 signature of the preceding segments (bytes 1 through 4).
This format ensures that the token is self-contained and tamper-proof while being extremely efficient to parse without complex regex or split operations.
Reference
Class: auth.AuthService
The main class to handle signing and verification of tokens.
new auth.AuthService(publicKey, privateKey)
Signs the provided header and payload using the RSA-SHA256 algorithm.
Static method: AuthService.verifyToken(token, publicKey)
Parses and verifies the token. Throws an Error if the signature is invalid or TypeError if keys are missing.
Instance method that uses the privateKey provided in the constructor to sign a token.
service.verifyToken(token)
Instance method that uses the publicKey provided in the constructor to verify a token.