@unidev-hub/azure-auth
v1.0.1
Published
Azure AD authentication and authorization module for Node.js applications
Readme
@unidev-hub/azure-auth
Azure AD Authentication Module
A reusable npm module for authentication and authorization using Azure AD in Node.js applications.
Features
- Azure AD authentication using MSAL
- Token validation and decoding
- Role-based and group-based authorization
- Express middleware for protecting routes
- Token caching and refresh capabilities
- Client credentials flow for server-to-server auth
Installation
npm install azure-authPrerequisites
This module has peer dependencies on:
expressloggercache
Ensure these are installed in your project.
Usage
Basic Setup
import { createAzureAuth, AzureAdOptions } from 'azure-auth';
import { logger } from 'logger';
import { cache } from 'cache';
const azureOptions: AzureAdOptions = {
tenantId: 'your-tenant-id',
clientId: 'your-client-id',
clientSecret: 'your-client-secret',
redirectUri: 'http://localhost:3000/auth/callback',
allowedGroups: ['admin-group-id']
};
const { service, middleware } = createAzureAuth(azureOptions, logger, cache);
// Use in Express application
import express from 'express';
const app = express();
// Protected route with authentication
app.get('/protected',
middleware.authenticate,
(req, res) => {
res.json({ message: 'Authenticated', user: req.user });
}
);
// Route protected with role-based authorization
app.get('/admin',
middleware.authenticate,
middleware.requireRole('Admin'),
(req, res) => {
res.json({ message: 'Admin route' });
}
);
// Route protected with group-based authorization
app.get('/group-members',
middleware.authenticate,
middleware.requireGroup('group-id'),
(req, res) => {
res.json({ message: 'Group members only' });
}
);Login Process
// Generate login URL
app.get('/login', (req, res) => {
const state = req.query.returnUrl || '/';
service.getLoginUrl(state)
.then(url => {
res.redirect(url);
})
.catch(err => {
res.status(500).json({ error: err.message });
});
});
// Handle callback
app.post('/auth/callback', async (req, res) => {
try {
const { code, state } = req.body;
const { user, tokenResponse } = await service.authenticateWithCode(code);
// Store tokens in session or send to client
req.session.accessToken = tokenResponse.accessToken;
req.session.refreshToken = tokenResponse.refreshToken;
// Redirect to original URL
res.redirect(state || '/');
} catch (error) {
res.status(401).json({ error: 'Authentication failed' });
}
});Client Credentials Flow
// Service-to-service authentication
async function callProtectedAPI() {
const tokenResponse = await service.getClientCredentialsToken();
// Use token to call another API
const apiResponse = await fetch('https://api.example.com/data', {
headers: {
Authorization: `Bearer ${tokenResponse.accessToken}`
}
});
return apiResponse.json();
}API Documentation
[Link to detailed API documentation]
License
MIT
