saget-auth-middleware
Version:
A comprehensive authentication middleware for Node.js applications with SSO integration, JWT validation, and role-based access control
317 lines (229 loc) โข 8.67 kB
Markdown
# SAGET Auth Middleware
A comprehensive, production-ready authentication middleware for Node.js applications that integrates with SAGET SSO system. This package provides a **drop-in replacement** for your existing SSO middleware with enhanced features and better error handling.
## ๐ Quick Start (Drop-in Replacement)
Replace your existing `middleware.js` file with this simple setup:
```javascript
// middleware.js
import { middleware, configureMiddleware, config } from 'saget-auth-middleware';
// Optional: Configure for your specific needs
configureMiddleware({
PUBLIC_PATHS: ['/', '/login', '/register', '/docs'],
ACCESS_CONTROL: {
'/dashboard': ['SUPER ADMIN'],
'/account': ['SUPER ADMIN', 'GUEST', 'USER', 'ADMIN', 'APPLICANT']
}
});
export { middleware as default, config };
```
That's it! Your middleware now has all the features of your original SSO middleware plus:
โ
**JWT token verification** using jose library
โ
**Automatic token refresh** with proper error handling
โ
**Role-based access control (RBAC)**
โ
**Configurable public paths**
โ
**SSO login redirect** with proper parameters
โ
**Cookie management** with security best practices
โ
**Comprehensive error handling** and logging
โ
**Environment variable support** with fallbacks
โ
**Docker network compatibility**
## ๐ฆ Installation
```bash
npm install saget-auth-middleware
# or
yarn add saget-auth-middleware
```
## ๐ ๏ธ CLI Generator (Simplified)
Generate middleware files directly in your project root with a single command:
```bash
# Generate TypeScript files for Next.js (most common)
npx saget-auth-middleware init
# Or specify options
npx saget-auth-middleware init --type ts --framework next
# Generate JavaScript files for Express
npx saget-auth-middleware init --type js --framework express
# Generate in a specific directory
npx saget-auth-middleware init --output ./auth
```
**What gets generated:**
- `middleware.ts/js` - Main middleware file
- `types.ts` (TypeScript only) - Type definitions
- `auth-utils.ts/js` - Client-side utilities
- `.env.example` - Environment configuration template
- `README.md` - Usage documentation
**Default behavior:** Files are generated directly in your current directory (no subdirectory created).
## ๐ง Environment Variables
### Required Variables
```env
# JWT Secret for token verification
SSO_JWT_SECRET=your-jwt-secret-key
# SSO App Configuration
SSO_APP_KEY=your-sso-app-key
# or
NEXT_PUBLIC_APP_KEY=your-sso-app-key
# Redirect URL after SSO login
NEXT_PUBLIC_REDIRECT_URL=https://yourapp.com/login/callback
# or
NEXT_REDIRECT_URL=https://yourapp.com/login/callback
# SSO API URL
SSO_API_URL=https://your-sso-api.com
# or
NEXT_PUBLIC_API_URL=https://your-sso-api.com
```
### Optional Variables
```env
# Custom SSO login URL
SSO_LOGIN_URL=https://your-sso-server.com/login
# Server-side API URL (for Docker networks)
NEXT_PUBLIC_API_URL_SERVER_SIDE=http://sso-api:3000
# Custom cookie names
NEXT_PUBLIC_COOKIE_ACCESS_TOKEN_NAME=accessToken-yourapp.com
NEXT_PUBLIC_COOKIE_REFRESH_TOKEN_NAME=refreshToken-yourapp.com
NEXT_PUBLIC_COOKIE_APPLICATION_TOKEN_NAME=applicationToken-yourapp.com
```
## ๐ฏ Usage Examples
### Basic Usage (Minimal Setup)
```javascript
// middleware.js
import { middleware, config } from 'saget-auth-middleware';
export { middleware as default, config };
```
๐ **See [examples/simple-usage.js](examples/simple-usage.js) for complete basic setup**
### Advanced Configuration
```javascript
// middleware.js
import { middleware, configureMiddleware, config } from 'saget-auth-middleware';
configureMiddleware({
// Public paths that bypass authentication
PUBLIC_PATHS: [
'/',
'/login',
'/register',
'/docs',
'/about',
'/contact',
'/login/verify-otp'
],
// Role-based access control
ACCESS_CONTROL: {
'/dashboard': ['SUPER ADMIN'],
'/admin': ['SUPER ADMIN', 'ADMIN'],
'/account': ['SUPER ADMIN', 'GUEST', 'USER', 'ADMIN', 'APPLICANT'],
'/reports': ['SUPER ADMIN', 'ADMIN'],
'/settings': ['SUPER ADMIN']
},
// Custom cookie names
COOKIE_NAMES: {
ACCESS_TOKEN: 'accessToken-myapp.com',
REFRESH_TOKEN: 'refreshToken-myapp.com',
APPLICATION_TOKEN: 'applicationToken-myapp.com'
},
// Custom SSO login URL
SSO_LOGIN_URL: 'https://sso.mycompany.com/login'
});
export { middleware as default, config };
```
๐ **See [examples/advanced-config.js](examples/advanced-config.js) for all configuration options**
### Using with Express.js
```javascript
// app.js
import express from 'express';
import { middleware } from 'saget-auth-middleware';
const app = express();
// Apply SSO middleware to all routes
app.use(middleware);
app.get('/dashboard', (req, res) => {
res.json({ message: 'Protected dashboard' });
});
app.listen(3000);
```
๐ **See [examples/express/app.js](examples/express/app.js) for complete Express.js setup**
## ๐ Authentication Flow
The middleware follows the exact same flow as your original SSO middleware:
1. **Public Path Check**: Allows access to configured public paths
2. **Token Validation**: Verifies JWT access token using jose library
3. **Token Refresh**: Automatically refreshes expired tokens using refresh token
4. **Authorization Check**: Validates user roles against path requirements
5. **SSO Redirect**: Redirects to SSO login if authentication fails
## ๐ก๏ธ Security Features
- **JWT Verification**: Uses industry-standard jose library for token verification
- **Automatic Token Refresh**: Seamlessly refreshes expired tokens
- **Secure Cookies**: HttpOnly, Secure, SameSite protection
- **Role-Based Access Control**: Fine-grained permission system
- **Error Handling**: Comprehensive error logging and recovery
- **Environment Validation**: Validates required configuration
## ๐ Migration from Original Middleware
### Before (Original Middleware)
```javascript
// middleware.js - 300+ lines of code
import { NextResponse } from "next/server";
import { JsonWebTokenError } from "jsonwebtoken";
import { jwtVerify } from "jose";
const PUBLIC_PATHS = ['/', '/login', '/register'];
const ACCESS_CONTROL = { /* ... */ };
const decodeJwtToken = async (token) => { /* ... */ };
const checkOtorisasi = async (req) => { /* ... */ };
const setCookieFromReauth = async (refreshToken) => { /* ... */ };
// ... 200+ more lines
export async function middleware(req) {
// ... complex logic
}
```
### After (SAGET Auth Middleware)
```javascript
// middleware.js - 3 lines of code!
import { middleware, config } from 'saget-auth-middleware';
export { middleware as default, config };
```
## ๐ API Reference
### `configureMiddleware(config)`
Configure the middleware with custom settings.
```javascript
configureMiddleware({
PUBLIC_PATHS: string[], // Paths that bypass authentication
ACCESS_CONTROL: object, // Role-based access control rules
COOKIE_NAMES: object, // Custom cookie names
SSO_LOGIN_URL: string // Custom SSO login URL
});
```
### `middleware(request)`
The main middleware function that handles authentication.
- **Parameters**: `request` - Next.js request object
- **Returns**: `NextResponse` - Response with authentication handling
## ๐งช Testing
```bash
# Run integration tests
npm test
# Run with coverage
npm run test:coverage
# Run in watch mode
npm run test:watch
```
## ๐ Troubleshooting
### Common Issues
1. **"SSO_JWT_SECRET environment variable is not set"**
- Ensure `SSO_JWT_SECRET` is set in your environment variables
2. **"Failed to refresh tokens"**
- Check your `SSO_API_URL` is correct and accessible
- Verify your refresh token endpoint is working
3. **"User not authorized for path"**
- Check your `ACCESS_CONTROL` configuration
- Verify user roles in the application token
4. **Token refresh loops**
- Ensure your SSO API returns valid tokens
- Check network connectivity to SSO API
### Debug Mode
Enable detailed logging by setting:
```env
NODE_ENV=development
```
## ๐ค Contributing
1. Fork the repository
2. Create your feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add some amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request
## ๐ License
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
## ๐ข About PIJAR TEKNOLOGI
This middleware is developed and maintained by PIJAR TEKNOLOGI. For enterprise support and custom implementations, please contact us.
---
**Made with โค๏ธ by PIJAR TEKNOLOGI**