0.0.3 • Published 6 months ago
jwt-validator-js v0.0.3
JWT Validator Middleware
This middleware provides a simple and secure way to authenticate requests using JSON Web Tokens (JWT). It extracts the token from the Authorization header, verifies it using the provided secret, and attaches the decoded user information to the request object. If the token is invalid or has expired, an appropriate error response is returned.
Installation
npm install jwt-validator-js
Usage
const express = require('express');
const jwtValidator = require(jwt-validator-js');
const app = express();
const JWT_SECRET = 'MY_SECRET_KEY';
app.use(jwtTokenValidator({
JWT_SECRET,
handleErrors: {
// your custom error code here
},
}));
or
app.use(jwtTokenValidator({
JWT_SECRET
}));
app.get('/', (req, res) => {
console.log('Authenticated user:', req.userInformation);
res.send('Hello, authenticated user!');
});
app.listen(3000, () => console.log('Server listening on port 3000'));
Configuration
The middleware accepts a configuration object with the following properties:
JWT_SECRET: The secret key used for JWT verification.
handleErrors: An object with custom error messages for different scenarios.
The handleErrors object can contain the following properties if not specified:
- unauthorized: The error message to return when a token is missing or invalid.
- invalidToken: The error message to return when a token is expired or doesn't match the signing key.