@mokuteki/jwt
TypeScript icon, indicating that this package has built-in type declarations

1.0.2 • Public • Published

@mokuteki/jwt

Zero dependency typescript friendly Node.js library designed to hash/decode JSON Web Tokens using symmetric/asymmetric algorithms

Installation

npm i @mokuteki/jwt

Quick start

  • Pick one hashing strategy out of existing ones
  • Pass the strategy to JSONWebToken constructor
  • Use created instance to generate/verify JWTs

HS256 Strategy

const { JSONWebToken, HS256Strategy } = require('@mokuteki/jwt');

const strategy = new HS256Strategy({
  ttl: 10000,
  secret: 'YOUR_SECRET',
});

const jwt = new JSONWebToken(strategy);
const payload = { id: 1 };

const token = jwt.generate(payload);
const decoded = jwt.verify(token);

console.log(decoded); // { id: 1 }

RS256 Strategy

const { JSONWebToken, RS256Strategy } = require('@mokuteki/jwt');

const strategy = new RS256Strategy({
  ttl: 10000,
  publicKey: 'YOUR_PUBLIC_KEY',
  privateKey: 'YOUR_PRIVATE_KEY',
});

const jwt = new JSONWebToken(strategy);
const payload = { id: 1 };

const token = jwt.generate(payload);
const decoded = jwt.verify(token);

console.log(decoded); // { id: 1 }

Override predefined options

const { JSONWebToken, HS256Strategy } = require('@mokuteki/jwt');

const strategy = new HS256Strategy({
  ttl: 10000,
  secret: 'YOUR_SECRET',
});

const jwt = new JSONWebToken(strategy);
const payload = { id: 1 };

/**
 * Override JWT ttl option
 */
const token = jwt.generate(payload, { ttl: 1000 });

setTimeout(() => {
  try {
    const decoded = jwt.verify(token);
  } catch (err) {
    // err instanceof JwtExpiredError
  }
}, 2000);
const { JSONWebToken, HS256Strategy } = require('@mokuteki/jwt');

const strategy = new HS256Strategy({
  ttl: 10000,
  secret: 'YOUR_SECRET',
});

const jwt = new JSONWebToken(strategy);
const payload = { id: 1 };

const token = jwt.generate(payload, { ttl: 20000, secret: 'NEW_SECRET' });

try {
  const decoded = jwt.verify(token);
} catch (err) {
  // err instanceof InvalidSignatureError
}

License

Licensed under MIT

Package Sidebar

Install

npm i @mokuteki/jwt

Weekly Downloads

1

Version

1.0.2

License

MIT

Unpacked Size

22.9 kB

Total Files

21

Last publish

Collaborators

  • mokuteki