Loading source
Pulling the file list, source metadata, and syntax-aware rendering for this listing.
Source from repo
Prepare Azure environments for new workloads—subscriptions, networking, identity, and landing zones
Files
Skill
Size
Entrypoint
Format
Open file
Syntax-highlighted preview of this file as included in the skill package.
references/services/app-service/templates/recipes/auth/source/nodejs.md
1# Auth Recipe — Node.js (Express) — REFERENCE ONLY23## JWT Validation with jsonwebtoken + jwks-rsa45### npm Packages67```bash8npm install jsonwebtoken jwks-rsa9```1011### Auth Middleware1213Add `middleware/auth.js`:1415```javascript16const jwt = require("jsonwebtoken");17const jwksClient = require("jwks-rsa");1819const client = jwksClient({20jwksUri: `https://login.microsoftonline.com/${process.env.AZURE_TENANT_ID}/discovery/v2.0/keys`,21cache: true,22rateLimit: true,23});2425// Use APP_ID_URI if set (e.g., "api://<client-id>"); fall back to CLIENT_ID26const AUDIENCE = process.env.AZURE_APP_ID_URI || process.env.AZURE_CLIENT_ID;2728function authMiddleware(req, res, next) {29const token = req.headers.authorization?.split(" ")[1];30if (!token) return res.status(401).json({ error: "No token" });3132const decoded = jwt.decode(token, { complete: true });33if (!decoded || !decoded.header || !decoded.header.kid) {34return res.status(401).json({ error: "Invalid token" });35}3637client.getSigningKey(decoded.header.kid, (err, key) => {38if (err || !key) {39return res.status(401).json({ error: "Invalid token" });40}4142jwt.verify(43token,44key.getPublicKey(),45{46algorithms: ["RS256"],47audience: AUDIENCE,48issuer: `https://login.microsoftonline.com/${process.env.AZURE_TENANT_ID}/v2.0`,49},50(err, payload) => {51if (err) return res.status(401).json({ error: "Invalid token" });52req.user = payload;53next();54}55);56});57}5859module.exports = { authMiddleware };60```6162> ⚠️ The `aud` claim in Entra ID tokens is often the Application ID URI (`api://<client-id>`), not the raw client ID. Set `AZURE_APP_ID_URI` in app settings to match your app registration's exposed API URI.6364### Protected Endpoint6566Add to `src/index.js`:6768```javascript69const { authMiddleware } = require("./middleware/auth");7071app.get("/api/me", authMiddleware, (req, res) => {72res.json({ name: req.user?.name, oid: req.user?.oid });73});74```7576## App Settings Required7778| Setting | Value |79|---------|-------|80| `AZURE_TENANT_ID` | Entra tenant ID |81| `AZURE_CLIENT_ID` | App registration client ID |82| `AZURE_APP_ID_URI` | Application ID URI (e.g., `api://<client-id>`) — optional, defaults to CLIENT_ID |8384## Files to Modify8586| File | Action |87|------|--------|88| `middleware/auth.js` | Create — JWT validation middleware |89| `src/index.js` | Modify — add protected routes |90| `package.json` | Modify — add jsonwebtoken, jwks-rsa |91