UNPKG

@ahhaohho/auth-middleware

Version:

Shared authentication middleware with Passport.js for ahhaohho microservices

251 lines (185 loc) 5.24 kB
# @ahhaohho/auth-middleware Shared authentication middleware with Passport.js for ahhaohho microservices. ## Features - ✅ Passport.js JWT authentication strategy - ✅ Multi-key JWT verification with fallback support - ✅ Redis-based token blacklist - ✅ AWS Secrets Manager integration - ✅ Express middleware ready ## Installation ### Using npm (recommended) ```bash npm install @ahhaohho/auth-middleware ``` Or add to `package.json`: ```json { "dependencies": { "@ahhaohho/auth-middleware": "^1.0.2" } } ``` ### Using Git ```bash npm install git+ssh://git@github.com:Future-Lab-META/auth-middleware.git#v1.0.2 ``` Or add to `package.json`: ```json { "dependencies": { "@ahhaohho/auth-middleware": "git+ssh://git@github.com:Future-Lab-META/auth-middleware.git#v1.0.2" } } ``` ## Usage ### Basic Setup ```javascript const express = require('express'); const { authenticateJWT, authenticateRefresh } = require('@ahhaohho/auth-middleware'); const app = express(); // Environment variables required // AWS_REGION=ap-northeast-2 // REDIS_HOST=your-redis-host // REDIS_PORT=6379 // JWT_SECRET_NAME=your-secret-name // Protected routes app.get('/api/verify', authenticateJWT, (req, res) => { res.json({ userId: req.user.userId, userRole: req.user.userRole }); }); app.get('/api/refresh', authenticateRefresh, (req, res) => { // Generate new access token res.json({ newAccessToken: '...' }); }); app.listen(3000); ``` ### Environment Variables ```bash # Required AWS_REGION=ap-northeast-2 REDIS_HOST=your-redis-host REDIS_PORT=6379 JWT_SECRET_NAME=your-secret-name # Optional ELASTICACHE_ENDPOINT=your-elasticache-endpoint # If using ElastiCache (auto-enables TLS) REDIS_TLS=true # Force enable TLS for Redis connection ``` #### Redis Configuration Notes - **REDIS_HOST**: If set, takes priority over ELASTICACHE_ENDPOINT - **ELASTICACHE_ENDPOINT**: Used only when REDIS_HOST is not set - **TLS Auto-detection**: - TLS is automatically disabled for `localhost` and `127.0.0.1` - TLS is automatically enabled when using ELASTICACHE_ENDPOINT (without REDIS_HOST) - Use `REDIS_TLS=true` to force enable TLS for any host ## Architecture ### JWT Verification Flow ``` Request with JWT ↓ authenticateJWT middleware ↓ Extract token from Authorization header ↓ Verify with current JWT key ↓ (if fails) Fallback to previous JWT key ↓ Check Redis blacklist ↓ Inject user data to req.user ↓ Next middleware ``` ### Multi-Key Support Supports seamless JWT key rotation: - Verifies with current key first - Falls back to previous key if current fails - Allows zero-downtime key rotation ### Token Blacklist Uses Redis to maintain revoked tokens: - Stores blacklisted tokens per user - Automatically expires with token TTL - Checked on every authentication ## API Reference ### `authenticateJWT(req, res, next)` Passport.js middleware for JWT authentication. **Headers:** - `Authorization: Bearer <access_token>` **Sets:** - `req.user`: `{ userId, userRole, phoneNumber }` **Errors:** - 401: Unauthorized (invalid or expired token) - 500: Authentication error ### `authenticateRefresh(req, res, next)` Passport.js middleware for refresh token authentication. **Headers:** - `Refresh-Token: Bearer <refresh_token>` **Sets:** - `req.user`: `{ userId, userRole, phoneNumber }` **Errors:** - 401: Invalid refresh token - 500: Token refresh error ## Development ### Project Structure ``` auth-middleware/ ├── src/ │ ├── index.js # Main export │ ├── strategies/ │ │ ├── jwt.strategy.js # Passport JWT strategy │ │ └── refresh.strategy.js # Refresh token strategy │ ├── middleware/ │ │ └── auth.js # Express middleware │ ├── utils/ │ │ ├── jwtValidator.js # Multi-key verification │ │ ├── blacklist.js # Redis blacklist │ │ └── secretManager.js # AWS Secrets Manager │ └── config/ │ └── redis.js # Redis client singleton ├── package.json └── README.md ``` ### Testing Locally ```bash # Clone the repository git clone git@github.com:Future-Lab-META/auth-middleware.git cd auth-middleware # Install dependencies npm install # Link locally for testing npm link # In your service directory npm link @ahhaohho/auth-middleware ``` ## Versioning This package follows [Semantic Versioning](https://semver.org/). ### Creating a New Version ```bash # Update version in package.json npm version patch # 1.0.0 -> 1.0.1 npm version minor # 1.0.0 -> 1.1.0 npm version major # 1.0.0 -> 2.0.0 # Push with tags git push origin main --tags ``` ### Using Specific Versions ```bash # npm npm install @ahhaohho/auth-middleware@1.0.2 # Git npm install git+ssh://git@github.com:Future-Lab-META/auth-middleware.git#v1.0.2 ``` Or in `package.json`: ```json { "dependencies": { "@ahhaohho/auth-middleware": "1.0.2" } } ``` ## Migration Guide See [MIGRATION.md](./MIGRATION.md) for detailed migration guide from HTTP-based authentication to Passport.js. ## License MIT