A reusable authentication and authorization middleware for Express microservices, designed to be used as a GitHub submodule.
- JWT-based authentication
- Role-based authorization
- Rate limiting
- Token refresh mechanism
- CSRF protection
- Secure cookie handling
- Redis-based token management
- Integrated logging with local logging middleware
# Add as submodule in your microservice
git submodule add git@github.com:codephilip/authentication-middleware.git shared/auth-middleware
# Initialize and update submodule
git submodule update --init --recursive
# Install dependencies
cd shared/auth-middleware
npm install# Clone the repository
git clone git@github.com:codephilip/authentication-middleware.git
cd authentication-middleware
# Install dependencies
npm install- Install dependencies:
npm install- Initialize the middleware in your Express app:
const { initializeAuth } = require('./shared/auth-middleware/src/index');
const auth = initializeAuth({
jwtSecret: process.env.JWT_SECRET,
jwtRefreshSecret: process.env.JWT_REFRESH_SECRET,
redisUrl: process.env.REDIS_URL,
jwtAudience: 'your-service-name',
jwtIssuer: 'auth-service'
});
// Apply essential middleware
app.use(...auth.essential);
// Protected route example
app.get('/protected',
auth.authenticate,
auth.authorize(['READ']),
(req, res) => {
res.json({ message: 'Protected resource' });
}
);The initializeAuth function accepts the following configuration:
/**
* @typedef {Object} AuthConfig
* @property {string} jwtSecret - JWT secret key
* @property {string} jwtRefreshSecret - JWT refresh secret key
* @property {string} [jwtAudience] - JWT audience
* @property {string} [jwtIssuer] - JWT issuer
* @property {string} redisUrl - Redis connection URL
* @property {string} [cookieDomain] - Cookie domain
* @property {boolean} [secureCookies] - Whether to use secure cookies
*/auth.essential: Array of essential middleware (authenticate, rateLimiter, securityHeaders, csrfProtection)auth.authenticate: Authentication middlewareauth.authorize(permissions): Authorization middlewareauth.logout: Logout handlerauth.errorHandler: Error handling middleware
TokenManager.generateTokenPair(payload): Generate access and refresh tokensTokenManager.revokeUserTokens(userId): Revoke all tokens for a userTokenManager.isTokenBlacklisted(token): Check if a token is blacklisted
- Install dependencies:
npm install
cd example-service
npm install- Start Redis (required for token management):
docker run --name redis -p 6379:6379 -d redis:alpine- Run the example service:
npm run dev- Visit http://localhost:3000/api-docs to view the API documentation and test the endpoints.
To run tests:
npm test
npm run test:coverageThis middleware uses a local logging implementation for structured logging. All authentication and authorization events are logged with appropriate context and severity levels.
Example log output:
{
"level": "info",
"service": "auth-middleware",
"component": "AUTH",
"message": "Authentication successful",
"metadata": {
"userId": "123",
"roles": ["USER"]
},
"timestamp": "2024-01-20T12:00:00.000Z"
}docker-compose up --builddocker-compose exec auth-service npm testdocker-compose logs -f auth-service- Add to your microservice:
git submodule add git@github.com:codephilip/authentication-middleware.git shared/auth-middleware- Update your service's package.json:
{
"dependencies": {
"auth-middleware": "file:./shared/auth-middleware"
}
}- Initialize in your Express app:
const { initializeAuth } = require('./shared/auth-middleware/src/index');Update the submodule to latest version:
git submodule update --remote shared/auth-middlewareUpdate to specific version:
cd shared/auth-middleware
git checkout v1.0.0
cd ../..
git add shared/auth-middleware
git commit -m "Update auth-middleware to v1.0.0"Clone a project with submodules:
git clone --recursive <your-repo-url>This middleware follows semantic versioning. To update to a specific version:
cd shared/auth-middleware
git fetch --tags
git checkout v1.0.0 # Replace with desired version
cd ../..
git add shared/auth-middleware
git commit -m "Update auth-middleware to v1.0.0"This middleware is implemented in pure JavaScript (ES6+) and can be used directly without any TypeScript compilation step. All type definitions have been converted to JSDoc comments for better IDE support and documentation.