Overview
The API uses JWT (JSON Web Tokens) issued by Azure Active Directory to authenticate requests. Each token contains claims about the user’s identity and permissions.Authorization Header Format
All authenticated requests must include a Bearer token in the Authorization header:The token must be sent with every request to protected endpoints.
Token Structure
A JWT consists of three parts separated by dots:Header
Contains metadata about the token:Payload (Claims)
Contains user identity and token metadata:Signature
Cryptographic signature that validates the token hasn’t been tampered with.Important Token Claims
The API uses the following claims from Azure AD tokens:oid
Object ID - Unique identifier for the user in Azure AD. Used as the primary user identifier.
upn
User Principal Name - The user’s email address. Primary source for user email.
preferred_username
Preferred Username - Alternative email claim, used as fallback if
upn is not present.name
Display Name - The user’s full name as configured in Azure AD.
aud
Audience - The intended recipient of the token (must match
AZURE_AUDIENCE).iss
Issuer - The authority that issued the token (Azure AD).
exp
Expiration - Timestamp when the token expires (Unix timestamp).
iat
Issued At - Timestamp when the token was issued (Unix timestamp).
Token Verification with express-oauth2-jwt-bearer
The API uses theexpress-oauth2-jwt-bearer library (v1.7.1) to verify tokens.
Installation
Configuration
Fromsrc/middleware/authMiddleware.js:13-19:
src/middleware/authMiddleware.js
The
auth() function creates a middleware that automatically:- Downloads Azure AD’s public keys (JWKS)
- Verifies the token signature
- Validates issuer and audience
- Checks token expiration
The authenticateAndExtract Middleware
This middleware combines JWT verification with user identity extraction.Full Implementation
Fromsrc/middleware/authMiddleware.js:22-56:
src/middleware/authMiddleware.js
What It Does
Handle Errors
If verification fails:
- Returns
401for invalid/expired/missing tokens - Returns
500for other errors
Extract User Identity
On successful verification:
- Extracts email from
upnorpreferred_usernameclaim - Extracts Azure Object ID from
oidclaim - Attaches identity to
req.userIdentity
Request Object After Authentication
After successful authentication, the request object contains:Usage in Routes
Apply the middleware to protect routes:Example: Employee Routes
Fromsrc/routes/empleadoRoutes.js:10-13:
src/routes/empleadoRoutes.js
All routes in this router automatically require a valid JWT token.
Error Responses
401 - Unauthorized
Returned when token validation fails:- Token is expired
- Token signature is invalid
- Missing Authorization header
- Invalid token format
- Token audience doesn’t match API configuration
500 - Internal Server Error
Returned for unexpected errors during token verification:Testing Authentication
Using cURL
Using Postman
Using JavaScript (Fetch)
Token Expiration
Azure AD tokens typically expire after 1 hour. Client applications must:- Detect expiration: Handle 401 responses
- Refresh token: Use refresh tokens to obtain new access tokens
- Retry request: Retry the original request with the new token
Best Practices
Always Use HTTPS
Tokens must only be transmitted over encrypted connections to prevent interception.
Validate on Every Request
Never skip token validation, even for seemingly “internal” requests.
Handle Expiration Gracefully
Implement automatic token refresh in client applications.
Log Authentication Failures
Monitor failed authentication attempts for security analysis.
Next Steps
Azure AD Setup
Configure Azure Active Directory for your API
Roles & Permissions
Implement role-based access control