@bliv/authentication
v0.0.8
Published
Authentication middleware for Express applications
Downloads
97
Maintainers
Readme
@bliv/authentication
A TypeScript-based authentication middleware library for Express applications, providing JWT verification and authentication functionality.
Features
- Full TypeScript support with built-in type definitions
- JWT verification with JWKS (JSON Web Key Set) support
- Express middleware for authentication
- Configurable path exclusions
- Rate limiting for JWKS requests
- Customizable audience and issuer validation
- Error handling middleware
Installation
npm install @bliv/authenticationUsage with TypeScript
Basic Setup
import express from 'express';
import { middleware, JwtVerifyConfig, AuthRequest } from '@bliv/authentication';
const app = express();
// Configure the authentication middleware
const config: JwtVerifyConfig = {
JWKSURL: 'https://your-jwks-url.com/.well-known/jwks.json',
AUDIENCE: 'your-audience',
ISSUER: 'your-issuer',
IGNORE_PATHS: ['/public', '/health'],
CREDENTIALS_REQUIRED: true
};
// Use the middleware
app.use(middleware(config));
// Type-safe request handling
app.get('/protected', (req: AuthRequest, res) => {
// TypeScript knows about req.auth
const userId = req.auth?.userId;
if (!userId) {
return res.status(401).json({ error: 'User not authenticated' });
}
res.json({ userId, message: 'Protected resource accessed successfully' });
});Configuration Options
interface JwtVerifyConfig {
// Required: URL to fetch JWKS (JSON Web Key Set)
JWKSURL: string;
// Optional: Expected audience for the JWT (default: "platform")
AUDIENCE?: string;
// Optional: Expected issuer for the JWT
ISSUER?: string;
// Optional: Whether to require authentication (default: true)
CREDENTIALS_REQUIRED?: boolean;
// Optional: Array of paths to exclude from authentication
IGNORE_PATHS?: string[];
}Type Definitions
The package includes TypeScript definitions for enhanced type safety:
// Request with authentication data
interface AuthRequest extends Request {
auth?: AuthPayload;
headers: {
"x-coreplatform-correlationid"?: string;
[key: string]: string | string[] | undefined;
};
}
// Authentication payload
interface AuthPayload {
userId?: string;
[key: string]: any;
}Error Handling
import { ErrorRequestHandler } from 'express';
import { AuthRequest } from '@bliv/authentication';
const errorHandler: ErrorRequestHandler = (err, req: AuthRequest, res, next) => {
if (err.name === 'UnauthorizedError') {
return res.status(401).json({
error: 'Authentication failed',
details: err.message
});
}
next(err);
};
app.use(errorHandler);Advanced Usage
Custom Claims Validation
import { middleware, JwtVerifyConfig } from '@bliv/authentication';
const config: JwtVerifyConfig = {
JWKSURL: 'https://your-jwks-url.com/.well-known/jwks.json',
AUDIENCE: ['web', 'mobile'], // Support multiple audiences
ISSUER: 'https://your-issuer.com',
IGNORE_PATHS: [
'/public',
'/health',
/^\/api\/v1\/public\/.*/ // Support regex patterns
]
};
app.use(middleware(config));Role-Based Access Control
import { AuthRequest } from '@bliv/authentication';
const checkRole = (role: string) => {
return (req: AuthRequest, res, next) => {
const userRoles = req.auth?.roles || [];
if (!userRoles.includes(role)) {
return res.status(403).json({
error: 'Access denied',
message: `Required role: ${role}`
});
}
next();
};
};
app.get('/admin', checkRole('admin'), (req, res) => {
res.json({ message: 'Admin access granted' });
});Development
Prerequisites
- Node.js v16 or higher
- npm v7 or higher
Setup
# Clone the repository
git clone https://github.com/bliv-club/bliv-authentication.git
# Install dependencies
npm install
# Build the library
npm run build
# Run tests
npm testAvailable Scripts
npm run build: Compiles TypeScript code to JavaScriptnpm test: Runs the test suitenpm run lint: Runs ESLint for code qualitynpm run format: Formats code using Prettier
Version History
0.0.6: Current version
- Full TypeScript support with built-in type definitions
- Improved error handling
- Rate limiting for JWKS requests
- Express middleware integration
- Type-safe request handling
- Customizable audience and issuer validation
- Configurable path exclusions
- Documentation updates
0.0.5:
- Added TypeScript support
- Improved error handling
- Updated dependencies
0.0.4:
- Initial TypeScript conversion
- Added JWKS support
- Basic middleware functionality
0.0.3:
- Initial release
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
Apache-2.0
Support
For support:
- Check the documentation
- Open an issue in the GitHub repository
- Contact [email protected]
Acknowledgments
- express-jwt - JWT middleware for Express
- jwks-rsa - Retrieve RSA signing keys from a JWKS endpoint
