simple-authentication-jwt v1.0.3
JWTAuth - Simple JWT Authentication Utility for Express
simple-authentication-jwt is a lightweight and easy-to-use utility for handling JWT authentication in Express applications. It provides methods to manage token verification, token extraction, and refresh token generation with minimal setup.
Features:
- Check Authorization Header: Verifies if the
Authorization
header exists and extracts the Bearer token. - Verify Token: Validates JWT tokens to ensure they are correctly signed and unexpired.
- Extract Data from Token: Easily extract specific fields from the decoded JWT payload.
- Generate Refresh Token: Issues a refresh token to extend session validity.
Installation
You can install this utility in your Express project via npm:
npm i simple-authentication-jwt
Usage
1. Check Authorization Header
This middleware checks for the presence of the Authorization
header and extracts the Bearer token.
import { Request, Response, NextFunction } from 'express';
import authenticationUtils from 'simple-authentication-jwt';
app.use(authenticationUtils.checkAuthHeader);
2. Verify Token
To protect your routes, use the verifyAuthHeader
middleware. It verifies if the JWT token is valid and decodes the token to attach data to the request.
app.use(authenticationUtils.verifyAuthHeader);
3. Extract Data from Token
You can extract specific fields from the decoded JWT by calling the extractFieldsFromToken
method, passing the token and the fields you need.
const fields = ['userId', 'role'];
const extractedData = authenticationUtils.extractFieldsFromToken(token, fields);
4. Generate Refresh Token
Generate a refresh token when needed, such as when the current token is about to expire. This will allow the user to stay authenticated without needing to log in again.
app.post('/generate-refresh-token', authenticationUtils.generateRefreshToken);
Configuration
Ensure that your environment variables are properly set to configure JWT secrets:
JWT_SECRET
: Secret key used to sign and verify JWT tokens.JWT_REFRESH_SECRET
: Secret key for generating refresh tokens.JWT_REFRESH_EXPIRY
: Refresh token expiry time (default is7d
).
JWT_SECRET=your-jwt-secret
JWT_REFRESH_SECRET=your-refresh-token-secret
JWT_REFRESH_EXPIRY=7d
Example
Here’s an example of how to use the utility in an Express application.
import express from 'express';
import authenticationUtils from 'simple-authentication-jwt';
import dotenv from 'dotenv';
dotenv.config();
const app = express();
const port = 3000;
app.use(authenticationUtils.checkAuthHeader);
app.use(authenticationUtils.verifyAuthHeader);
app.get('/protected', (req, res) => {
res.send('Protected Route Accessed');
});
app.post('/generate-refresh-token', authenticationUtils.generateRefreshToken);
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
Contributing
If you'd like to contribute to this project, feel free to submit a pull request or open an issue for any bugs or features you'd like to see.
License
This project is licensed under the MIT License. See the LICENSE file for more details.
Note: This utility is intended to simplify JWT authentication in your Express app. It abstracts common operations like token validation and extraction, enabling you to focus on building your app's features instead of spending time on authentication details.