Hey there, JavaScript wizards! Ready to dive into the world of Azure AD webhooks? Let's get you set up with a slick user-facing integration in no time. Buckle up!
Webhooks in Azure AD are like your app's personal news feed for user events. They're perfect for keeping your app in sync with user changes, without constantly pestering Azure AD for updates. Think of them as Azure's way of saying, "Hey, something changed! You might want to check this out."
Before we jump in, make sure you've got:
We'll be using a couple of npm packages, so have these ready:
npm install @azure/msal-node axios express
First things first, let's get your app registered with Azure AD:
Now, let's give your app the permissions it needs:
User.Read.All
permissionLastly, grab your client credentials:
Time to write some code! First, let's authenticate with Azure AD:
const msal = require('@azure/msal-node'); const config = { auth: { clientId: "YOUR_CLIENT_ID", clientSecret: "YOUR_CLIENT_SECRET", authority: "https://login.microsoftonline.com/YOUR_TENANT_ID" } }; const cca = new msal.ConfidentialClientApplication(config); async function getToken() { const result = await cca.acquireTokenByClientCredential({ scopes: ["https://graph.microsoft.com/.default"] }); return result.accessToken; }
Now, let's create a webhook subscription:
const axios = require('axios'); async function createSubscription() { const token = await getToken(); const response = await axios.post('https://graph.microsoft.com/v1.0/subscriptions', { changeType: "created,updated,deleted", notificationUrl: "https://your-webhook-endpoint.com/notifications", resource: "users", expirationDateTime: new Date(Date.now() + 60 * 60 * 24 * 1000).toISOString(), clientState: "secretClientState" }, { headers: { 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json' } }); console.log('Subscription created:', response.data); } createSubscription();
This sets up a subscription for user changes, sending notifications to your specified endpoint.
Now, let's set up an Express server to receive those juicy notifications:
const express = require('express'); const app = express(); app.use(express.json()); app.post('/notifications', (req, res) => { if (req.query.validationToken) { res.send(req.query.validationToken); return; } // Process the notification console.log('Received notification:', req.body); // Always respond to Microsoft Graph with a 202 status code res.sendStatus(202); }); app.listen(3000, () => console.log('Webhook server running on port 3000'));
This server handles both the initial validation and incoming notifications. Remember to replace the placeholder URL in the subscription creation with your actual endpoint.
Subscriptions don't last forever, so you'll need to renew them periodically. Here's a quick function to do that:
async function renewSubscription(subscriptionId) { const token = await getToken(); const response = await axios.patch(`https://graph.microsoft.com/v1.0/subscriptions/${subscriptionId}`, { expirationDateTime: new Date(Date.now() + 60 * 60 * 24 * 1000).toISOString() }, { headers: { 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json' } }); console.log('Subscription renewed:', response.data); }
If you're having trouble creating subscriptions, double-check your permissions and make sure your app has admin consent.
Not receiving notifications? Verify your endpoint is publicly accessible and correctly handling the validation step.
And there you have it! You're now ready to keep your app in perfect sync with Azure AD user changes. Remember, the key to webhook mastery is in the details - proper error handling, security, and maintenance will take you far.
For more in-depth info, check out the Microsoft Graph webhooks documentation. Happy coding, and may your notifications always arrive on time!