Authentication Middleware — Building Reusable Auth Middleware Components
DodaTech
Updated 2026-06-28
1 min read
In this tutorial, you'll learn about Authentication Middleware. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.
Authentication middleware encapsulates authentication logic into reusable components that can be composed and tested independently.
// Composable auth middleware
function authenticate(options = {}) {
const { required = true, scopes = [], mfaRequired = false } = options;
return async (req, res, next) => {
try {
const token = extractToken(req);
if (!token && !required) return next();
if (!token) return res.status(401).json({ error: 'Authentication required' });
const decoded = await validateToken(token);
req.user = decoded;
// Scope validation
if (scopes.length > 0) {
const userScopes = decoded.scope?.split(' ') || [];
const hasAll = scopes.every(s => userScopes.includes(s));
if (!hasAll) {
return res.status(403).json({ error: 'Insufficient scope', required: scopes });
}
}
// MFA check
if (mfaRequired && !decoded.amr?.includes('mfa')) {
return res.status(403).json({ error: 'MFA required', mfa_required: true });
}
next();
} catch (err) {
return res.status(401).json({ error: 'Authentication failed', detail: err.message });
}
};
}
// Usage
app.get('/api/scans', authenticate({ scopes: ['scan:read'] }), scanHandler);
app.post('/api/scans/deep', authenticate({ scopes: ['scan:write'], mfaRequired: true }), deepScanHandler);
app.get('/api/public', authenticate({ required: false }), publicHandler);
// Testing auth middleware
describe('authenticate middleware', () => {
it('should reject requests without token', async () => {
const req = mockRequest({ headers: {} });
const res = mockResponse();
await authenticate()(req, res, () => {});
expect(res.status).toHaveBeenCalledWith(401);
});
});
Composable auth middleware reduces duplication and ensures consistent authentication across all routes.
← Previous
Biometric Authentication — Fingerprint and Face Authentication Integration
Next →
Token Revocation — Strategies for Revoking Auth Tokens
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro