1.2.0 โข Published 6 months ago
authentication-facilitator v1.2.0
๐ Authentication Facilitator
A simple and secure JWT authentication helper for Node/Express.js.
๐ Features
โ
Token Generation โ Create JWT access tokens
โ
Token Authentication โ Verify and decode JWT tokens
โ
Middleware โ Enforce JWT authentication in Express
๐ฆ Installation
npm install authentication-facilitator
๐ Usage
1๏ธโฃ Import the Module
const { buildToken, authenticateToken, resolveToken, enforceJWT } = require("authentication-facilitator");
2๏ธโฃ Generate a Token
const userPayload = { userId: 123 };
const secretKey = "your_secret_key";
const expiresIn = '1h'
const token = buildToken(userPayload, secretKey, expiresIn);
console.log(token);
3๏ธโฃ Verify & Decode a Token
const decoded = await authenticateToken(token, secretKey);
console.log(decoded); // { userId: 123, iat: ... , exp: ... }
4๏ธโฃ Extract Token from Request Headers
const sampleToken = 'token1234'
const tokenFromHeader = resolveToken(token);
console.log(tokenFromHeader);
5๏ธโฃ Use JWT Middleware in Express
const express = require("express");
const app = express();
app.use(enforceJWT("your_secret_key"));
app.get("/protected", (req, res) => {
res.json({ message: "You have access!", user: req.user });
});
app.listen(3000, () => console.log("Server running on port 3000"));
๐ API Reference
๐น buildToken(payload, secret, expiresIn = "1h")
- payload (Object) โ Data to include in the token
- secret (String) โ Secret key to sign the token
- expiresIn (String) โ Expiration time (default:
"1h"
) - Returns: A JWT string
๐น authenticateToken(token, secret)
- token (String) โ The JWT token to verify
- secret (String) โ Secret key used for verification
- Returns: Decoded payload or
null
if invalid
๐น resolveToken(token)
- token (String) โ Express request string
- Returns: Extracted token from
Authorization
header
๐น enforceJWT(secret)
- secret (String) โ Secret key for verification
- Returns: Express middleware to enforce authentication
๐งช Running Tests
npm test
๐ License
MIT License
๐ Author: Ryan Charles Alcaraz (github)