saget-auth-middleware
v2.1.2
Published
A comprehensive authentication middleware for Node.js applications with SSO integration, JWT validation, and role-based access control
Maintainers
Readme
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:
// 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
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:
# 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 ./authWhat gets generated:
middleware.ts/js- Main middleware filetypes.ts(TypeScript only) - Type definitionsauth-utils.ts/js- Client-side utilities.env.example- Environment configuration templateREADME.md- Usage documentation
Default behavior: Files are generated directly in your current directory (no subdirectory created).
🔧 Environment Variables
Required Variables
# 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.comOptional Variables
# 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)
// middleware.js
import { middleware, config } from 'saget-auth-middleware';
export { middleware as default, config };📁 See examples/simple-usage.js for complete basic setup
Advanced Configuration
// 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 for all configuration options
Using with Express.js
// 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 for complete Express.js setup
🔐 Authentication Flow
The middleware follows the exact same flow as your original SSO middleware:
- Public Path Check: Allows access to configured public paths
- Token Validation: Verifies JWT access token using jose library
- Token Refresh: Automatically refreshes expired tokens using refresh token
- Authorization Check: Validates user roles against path requirements
- 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)
// 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)
// 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.
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
# Run integration tests
npm test
# Run with coverage
npm run test:coverage
# Run in watch mode
npm run test:watch🐛 Troubleshooting
Common Issues
"SSO_JWT_SECRET environment variable is not set"
- Ensure
SSO_JWT_SECRETis set in your environment variables
- Ensure
"Failed to refresh tokens"
- Check your
SSO_API_URLis correct and accessible - Verify your refresh token endpoint is working
- Check your
"User not authorized for path"
- Check your
ACCESS_CONTROLconfiguration - Verify user roles in the application token
- Check your
Token refresh loops
- Ensure your SSO API returns valid tokens
- Check network connectivity to SSO API
Debug Mode
Enable detailed logging by setting:
NODE_ENV=development🤝 Contributing
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
📄 License
This project is licensed under the MIT License - see the 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
