Verify Microsoft Graph webhooks
Microsoft Graph doesn't put a signature on a basic change notification. You make up a clientState when you create the subscription, Graph copies it into every item in value, and you compare it with your stored value. Your URL also has to answer a validationToken POST, or Graph won't create the subscription. Rich notifications add validationTokens JWTs, which identify the sender, and a dataSignature over the encrypted data.
The facts
POST: echo the challenge Answer within 10 seconds with 200, text/plain and the URL-decoded validationToken.
Answer the validationToken POST, then compare clientState on every item in value. On rich notifications, also validate each JWT in validationTokens and check dataSignature Microsoft Graph webhook secret
clientState is a secret you make up and send when you create the subscription. Microsoft doesn't issue one, and Graph copies it into each notification so you can compare it with your stored value. Keep it in an environment variable, not in source code.
- Set it in the body of
POST /subscriptions, one value per subscription if you want to tell them apart. There is no dashboard to read it from. - Graph puts it on each item in
value, so readvalue[].clientState, not a header or a top-level field. - Microsoft's subscription reference limits it to 128 characters, while its notification reference says 255. Stay within 128.
- Microsoft's webhook how-to calls it required, and its API reference calls it optional. Always set it: a basic notification gives you nothing else to check.
- Microsoft documents no way to update
clientState, so plan on creating a new subscription to change it. - Rich notifications add two keys you manage: the certificate whose private key decrypts
dataKey, and Microsoft identity platform signing keys for the JWTs, which rotate daily.
Source: Microsoft Graph docs ↗
Code
// Generated with: microsoft-graph-webhooks skill
// https://github.com/hookdeck/webhook-skills
require('dotenv').config();
const express = require('express');
const crypto = require('crypto');
const app = express();
/**
* Verify the clientState echoed on a Microsoft Graph notification.
*
* Graph does NOT sign notifications with an HMAC. Instead, the opaque
* `clientState` you set when creating the subscription is echoed on every
* notification. Compare it (timing-safe, length-checked) to your stored secret.
*
* @param {string} received - clientState from the notification item
* @param {string} expected - your stored MICROSOFT_GRAPH_CLIENT_STATE
* @returns {boolean}
*/
function verifyClientState(received, expected) {
if (!received || !expected) {
return false;
}
const a = Buffer.from(received);
const b = Buffer.from(expected);
if (a.length !== b.length) {
// crypto.timingSafeEqual throws on length mismatch
return false;
}
return crypto.timingSafeEqual(a, b);
}
// Microsoft Graph notifications are application/json. The endpoint validation
// handshake carries no body (the token is in the query string), so express.json()
// leaving req.body empty for it is fine.
app.post('/webhooks/microsoft-graph', express.json(), (req, res) => {
// 1) Endpoint validation handshake.
// On subscription create/renewal Graph sends ?validationToken=... and
// expects the URL-decoded token echoed back as text/plain, 200, within 10s.
// Express already URL-decodes req.query values.
const validationToken = req.query.validationToken;
if (validationToken) {
return res.status(200).type('text/plain').send(String(validationToken));
}
// 2) Ordinary notification batch under `value`.
const notifications = Array.isArray(req.body?.value) ? req.body.value : [];
const expected = process.env.MICROSOFT_GRAPH_CLIENT_STATE;
// Validate clientState on every item before processing any of them.
for (const notification of notifications) {
if (!verifyClientState(notification.clientState, expected)) {
console.error('clientState mismatch — rejecting notification batch');
return res.status(400).send('Invalid clientState');
}
}
for (const notification of notifications) {
if (notification.lifecycleEvent) {
handleLifecycleEvent(notification);
} else {
handleChangeNotification(notification);
}
}
// Acknowledge within 3 seconds. Return 202 and do heavy work asynchronously.
return res.status(202).send();
});
/**
* Handle a change notification (created / updated / deleted).
*/
function handleChangeNotification(notification) {
const { changeType, resource, subscriptionId } = notification;
const resourceId = notification.resourceData?.id;
console.log(`Received ${changeType} for ${resource} (subscription: ${subscriptionId})`);
switch (changeType) {
case 'created':
console.log(`Resource created: ${resourceId}`);
// Your code: Fetch the full resource from Graph, or use rich notifications
break;
case 'updated':
console.log(`Resource updated: ${resourceId}`);
// Your code: Re-fetch and reconcile
break;
case 'deleted':
console.log(`Resource deleted: ${resourceId}`);
// Your code: Remove local copy
break;
default:
console.log(`Unhandled changeType: ${changeType}`);
}
}
/**
* Handle a lifecycle notification (delivered to lifecycleNotificationUrl).
*/
function handleLifecycleEvent(notification) {
const { lifecycleEvent, subscriptionId } = notification;
console.log(`Lifecycle event ${lifecycleEvent} for subscription ${subscriptionId}`);
switch (lifecycleEvent) {
case 'reauthorizationRequired':
console.log('Reauthorize/renew the subscription (POST /reauthorize or PATCH expirationDateTime)');
// Your code: Reauthorize and/or renew the subscription
break;
case 'subscriptionRemoved':
console.log('Subscription removed — recreate it and resync via delta query');
// Your code: Recreate subscription, then delta-sync missed changes
break;
case 'missed':
console.log('Missed notifications — resync via delta query');
// Your code: Delta-sync to recover missed changes
break;
default:
console.log(`Unhandled lifecycleEvent: ${lifecycleEvent}`);
}
}
// Health check endpoint
app.get('/health', (req, res) => {
res.json({ status: 'ok' });
});
// Export for testing
module.exports = { app, verifyClientState };
// Start server only when run directly (not when imported for testing)
if (require.main === module) {
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
console.log(`Webhook endpoint: POST http://localhost:${PORT}/webhooks/microsoft-graph`);
});
} // Generated with: microsoft-graph-webhooks skill
// https://github.com/hookdeck/webhook-skills
import { NextRequest, NextResponse } from 'next/server';
import crypto from 'crypto';
/**
* Verify the clientState echoed on a Microsoft Graph notification.
*
* Graph does NOT sign notifications with an HMAC. The opaque `clientState` you
* set when creating the subscription is echoed on every notification. Compare it
* (timing-safe, length-checked) to your stored secret.
*/
export function verifyClientState(
received: string | undefined | null,
expected: string | undefined
): boolean {
if (!received || !expected) {
return false;
}
const a = Buffer.from(received);
const b = Buffer.from(expected);
if (a.length !== b.length) {
// crypto.timingSafeEqual throws on length mismatch
return false;
}
return crypto.timingSafeEqual(a, b);
}
interface GraphNotification {
subscriptionId?: string;
changeType?: string;
resource?: string;
clientState?: string;
lifecycleEvent?: string;
resourceData?: { id?: string; '@odata.type'?: string };
}
export async function POST(request: NextRequest) {
// 1) Endpoint validation handshake.
// On subscription create/renewal Graph sends ?validationToken=... and
// expects the URL-decoded token echoed back as text/plain, 200, within 10s.
// searchParams values are already URL-decoded.
const validationToken = request.nextUrl.searchParams.get('validationToken');
if (validationToken) {
return new NextResponse(validationToken, {
status: 200,
headers: { 'Content-Type': 'text/plain' },
});
}
let payload: { value?: GraphNotification[] };
try {
payload = await request.json();
} catch {
return NextResponse.json({ error: 'Invalid JSON' }, { status: 400 });
}
const notifications = Array.isArray(payload?.value) ? payload.value : [];
const expected = process.env.MICROSOFT_GRAPH_CLIENT_STATE;
// Validate clientState on every item before processing any of them.
for (const notification of notifications) {
if (!verifyClientState(notification.clientState, expected)) {
console.error('clientState mismatch — rejecting notification batch');
return NextResponse.json({ error: 'Invalid clientState' }, { status: 400 });
}
}
for (const notification of notifications) {
if (notification.lifecycleEvent) {
handleLifecycleEvent(notification);
} else {
handleChangeNotification(notification);
}
}
// Acknowledge within 3 seconds. Return 202 and do heavy work asynchronously.
return new NextResponse(null, { status: 202 });
}
function handleChangeNotification(notification: GraphNotification) {
const { changeType, resource, subscriptionId } = notification;
const resourceId = notification.resourceData?.id;
console.log(`Received ${changeType} for ${resource} (subscription: ${subscriptionId})`);
switch (changeType) {
case 'created':
console.log(`Resource created: ${resourceId}`);
// Your code: Fetch the full resource from Graph, or use rich notifications
break;
case 'updated':
console.log(`Resource updated: ${resourceId}`);
// Your code: Re-fetch and reconcile
break;
case 'deleted':
console.log(`Resource deleted: ${resourceId}`);
// Your code: Remove local copy
break;
default:
console.log(`Unhandled changeType: ${changeType}`);
}
}
function handleLifecycleEvent(notification: GraphNotification) {
const { lifecycleEvent, subscriptionId } = notification;
console.log(`Lifecycle event ${lifecycleEvent} for subscription ${subscriptionId}`);
switch (lifecycleEvent) {
case 'reauthorizationRequired':
console.log('Reauthorize/renew the subscription (POST /reauthorize or PATCH expirationDateTime)');
// Your code: Reauthorize and/or renew the subscription
break;
case 'subscriptionRemoved':
console.log('Subscription removed — recreate it and resync via delta query');
// Your code: Recreate subscription, then delta-sync missed changes
break;
case 'missed':
console.log('Missed notifications — resync via delta query');
// Your code: Delta-sync to recover missed changes
break;
default:
console.log(`Unhandled lifecycleEvent: ${lifecycleEvent}`);
}
} # Generated with: microsoft-graph-webhooks skill
# https://github.com/hookdeck/webhook-skills
import hmac
import os
from dotenv import load_dotenv
from fastapi import FastAPI, Request, Response
from fastapi.responses import JSONResponse, PlainTextResponse
load_dotenv()
app = FastAPI()
def verify_client_state(received: str | None, expected: str | None) -> bool:
"""Verify the clientState echoed on a Microsoft Graph notification.
Graph does NOT sign notifications with an HMAC. The opaque ``clientState`` you
set when creating the subscription is echoed on every notification. Compare it
(timing-safe) to your stored secret.
"""
if not received or not expected:
return False
return hmac.compare_digest(received, expected)
def handle_change_notification(notification: dict) -> None:
"""Handle a change notification (created / updated / deleted)."""
change_type = notification.get("changeType")
resource = notification.get("resource")
subscription_id = notification.get("subscriptionId")
resource_id = (notification.get("resourceData") or {}).get("id")
print(f"Received {change_type} for {resource} (subscription: {subscription_id})")
if change_type == "created":
print(f"Resource created: {resource_id}")
# Your code: Fetch the full resource from Graph, or use rich notifications
elif change_type == "updated":
print(f"Resource updated: {resource_id}")
# Your code: Re-fetch and reconcile
elif change_type == "deleted":
print(f"Resource deleted: {resource_id}")
# Your code: Remove local copy
else:
print(f"Unhandled changeType: {change_type}")
def handle_lifecycle_event(notification: dict) -> None:
"""Handle a lifecycle notification (delivered to lifecycleNotificationUrl)."""
lifecycle_event = notification.get("lifecycleEvent")
subscription_id = notification.get("subscriptionId")
print(f"Lifecycle event {lifecycle_event} for subscription {subscription_id}")
if lifecycle_event == "reauthorizationRequired":
print("Reauthorize/renew the subscription (POST /reauthorize or PATCH expirationDateTime)")
# Your code: Reauthorize and/or renew the subscription
elif lifecycle_event == "subscriptionRemoved":
print("Subscription removed — recreate it and resync via delta query")
# Your code: Recreate subscription, then delta-sync missed changes
elif lifecycle_event == "missed":
print("Missed notifications — resync via delta query")
# Your code: Delta-sync to recover missed changes
else:
print(f"Unhandled lifecycleEvent: {lifecycle_event}")
@app.post("/webhooks/microsoft-graph")
async def microsoft_graph_webhook(request: Request):
# 1) Endpoint validation handshake.
# On subscription create/renewal Graph sends ?validationToken=... and
# expects the URL-decoded token echoed back as text/plain, 200, within 10s.
# Starlette query params are already URL-decoded.
validation_token = request.query_params.get("validationToken")
if validation_token is not None:
return PlainTextResponse(validation_token, status_code=200)
try:
payload = await request.json()
except Exception:
return PlainTextResponse("Invalid JSON", status_code=400)
notifications = payload.get("value") if isinstance(payload, dict) else None
if not isinstance(notifications, list):
notifications = []
expected = os.environ.get("MICROSOFT_GRAPH_CLIENT_STATE")
# Validate clientState on every item before processing any of them.
for notification in notifications:
if not verify_client_state(notification.get("clientState"), expected):
print("clientState mismatch — rejecting notification batch")
return PlainTextResponse("Invalid clientState", status_code=400)
for notification in notifications:
if notification.get("lifecycleEvent"):
handle_lifecycle_event(notification)
else:
handle_change_notification(notification)
# Acknowledge within 3 seconds. Return 202 and do heavy work asynchronously.
return Response(status_code=202)
@app.get("/health")
async def health():
return JSONResponse({"status": "ok"})
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000) Or install the Microsoft Graph webhooks skill:
npx skills add hookdeck/webhook-skills --skill microsoft-graph-webhooks
Common failures
Reading clientState from the wrong place
clientState is on each item in value, not in a header or at the top of the body. Check every item, since a POST can batch several.
Returning an error for the whole batch
A POST can mix subscriptions, and any non-2xx response makes Graph retry it for up to 4 hours. The code below returns a 400 on any mismatch. If you run more than one clientState, look up the expected value by subscriptionId, drop only the bad items and still return a 202. Microsoft asks for that response on rich notifications, even when validation later fails.
Returning an encoded validation token
Graph sends the token URL-encoded and expects it back decoded, as text/plain. Most frameworks decode query parameters for you, so don't encode the value again or wrap it in JSON.
Checking the wrong JWT claim
On rich notifications, the caller identity is in appid on v1.0 tokens and in azp on v2.0 tokens, and should be 0bf30f3b-4a52-48df-9a82-234910c4a086. A null value for validationTokens means Graph couldn't encrypt the data because of your app's configuration.
Queue Microsoft Graph deliveries before they reach your handler.
Event Gateway accepts each Microsoft Graph delivery, queues it and retries failures on your schedule, with a log of every attempt.