Subscribe for Microsoft Graph webhooks to be notified when your user's data changes so you don't have to poll for changes.
This Azure WebJobs sample shows how to start getting notifications from Microsoft Graph. Microsoft Graph provides a unified API endpoint to access data from the Microsoft cloud.
This sample uses the Azure AD endpoint to obtain an access token for work or school accounts. The sample uses a application-only permission, however delegated-permissions should also work.
The following are common tasks that an application performs with webhooks subscriptions:
- Get consent to subscribe to users' resources and then get an access token.
- Use the access token to create a subscription to a resource.
- Send back a validation token to confirm the notification URL.
- Listen for notifications from Microsoft Graph and respond with a 202 status code.
- Request more information about changed resources using data in the notification.
After the app creates a subscription using app-only auth token , Microsoft Graph sends a notification to the registered notification endpoint when events happen in the user's data. The app then reacts to the event.
This sample subscribes to the Users
resource for updated
and deleted
changes. The sample assumes that the notification URL is an Azure Function, which listens for webhook over http and immediately adds those notifications to an Azure storage queue. The sample uses Azure WebJobs SDK to bind to the Azure storage queue, and receive new notifications as they are queued by the Azure function.
To use the Microsoft Graph Webhooks sample using WebJobs SDK, you need the following:
-
Visual Studio 2017 installed on your development computer.
-
The application ID and key from the application that you register on the Azure Portal.
-
A public HTTPS endpoint to receive and send HTTP requests. You can host this on Microsoft Azure or another service. This sample was tested using Azure Function
-
An Azure storage account that will be used by Azure WebJobs SDK
- Sign in to the Azure portal using either a work or school account.
- If your account is present in more than one Azure AD tenant:
- Select your profile from the menu on the top right corner of the page, and then Switch directory.
- Change your session to the Azure AD tenant where you want to create your application.
-
Navigate to the Azure portal > App registrations to register your app.
-
When the Register an application page appears, enter your app's registration information:
- In the Name section, enter a meaningful name that will be displayed to users of the app. For example:
MyWebApp
- In the Supported account types section, select Accounts in any organizational directory and personal Microsoft accounts (e.g. Skype, Xbox, Outlook.com).
- In the Name section, enter a meaningful name that will be displayed to users of the app. For example:
-
On the app's Overview page, find the Application (client) ID value and record it for later. You'll need this value to configure the Visual Studio configuration file for this project.
-
In the list of pages for the app, select Authentication.
-
Select Save.
-
From the Certificates & secrets page, in the Client secrets section, choose New client secret.
- Enter a key description (of instance
app secret
). - Select a key duration of either In 1 year, In 2 years, or Never Expires.
- When you click the Add button, the key value will be displayed. Copy the key value and save it in a safe location. You'll need this key later to configure the project in Visual Studio. This key value will not be displayed again, nor retrievable by any other means, so record it as soon as it is visible from the Azure portal.
- Enter a key description (of instance
-
In the list of pages for the app, select API permissions.
- Click the Add a permission button and then make sure that the Microsoft APIs tab is selected.
- In the Commonly used Microsoft APIs section, select Microsoft Graph.
- In the Application permissions section, make sure that the Directory.Read.All permission is checked. Use the search box if necessary.
- Select the Add permissions button.
-
From the Manage page, select API permissions > Add a permission.
-
Choose Microsoft API > Microsoft Graph.
-
Choose Application permissions. In the search box, type directory.read.all and select the first option from the list. Select Add permissions.
You must expose a public HTTPS endpoint to create a subscription and receive notifications from Microsoft Graph. You can use Azure Functions for the same.
-
Sign in to the Azure Portal using your work or school account.
-
Choose Function Apps in the left-hand navigation pane.
-
Follow instructions to create a new Function App
-
Create a new WebHook/API function with following sample code
using System.Net;
public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, ICollector<string> queue, TraceWriter log)
{
log.Info("C# HTTP trigger function processed a request.");
// parse query parameter
string validationToken = req.GetQueryNameValuePairs()
.FirstOrDefault(q => string.Compare(q.Key, "validationToken", true) == 0)
.Value;
log.Info("validationToken: " + validationToken);
// Get request body
string data = await req.Content.ReadAsStringAsync();
log.Info("Body of request: " + data);
queue.Add(data);
log.Info("Added message to queue");
return string.IsNullOrWhiteSpace(validationToken)
? req.CreateResponse(HttpStatusCode.Accepted, "Notification received")
: req.CreateResponse(HttpStatusCode.OK, validationToken);
}
-
Choose Integrate > New Output > Azure Queue Storage
-
Enter
queue
as Message Parameter name -
Enter
webhooksnotificationqueue
as Queue name -
Use an existing or create a new Storage account connection
-
Choose the function created and Run from the portal to make sure that it succeeds.
-
Choose on Get function URL to copy the notification url to be used in the sample.
-
In Solution Explorer, select the App.config project.
a. For the clientId key, replace ENTER_YOUR_APP_ID with the application ID of your registered Azure application.
b. For the clientSecret key, replace ENTER_YOUR_SECRET with the key of your registered Azure application.
c. For the tenantId key, replace ENTER_YOUR_ORGANIZATION_ID with id of your organization.
d. For the webjobs key, replace ENTER_YOUR_AZURE_STORAGE_CONNECTION_STRING with connection string of azure storage integrated in Azure function.
e. For the notificationurl key, replace ENTER_YOUR_NOTIFICATION_URL with URL of Azure function.
-
Press F5 to start your sample.
-
Wait for sample to print the message Created new subscription with id:
-
Update any property of any user in the organization. Example: Update their phone number
-
In a few minutes, sample should receive notification for the updated user along with their identification.
-
Every 30 seconds, sample will renew subscription. One can change the time period of updated operation to be once every 24 hours.
Controllers
Function.cs
Manages subscriptions and Receives notifications.Program.cs
Bootstraps Azure WebJob host.
Issue | Resolution |
---|---|
You get a 403 Forbidden response when you attempt to create a subscription. | Make sure that your app registration includes the Read directory data application permission for Microsoft Graph (as described in the Register the app section). |
You do not receive notifications. | Check the logs for Azure function in portal. If Microsoft Graph is not sending notifications, please open a Stack Overflow issue tagged [MicrosoftGraph]. Include the subscription ID and the time it was created. |
You get a Subscription validation request timed out response. | This indicates that Microsoft Graph did not receive a validation response within the expected timeframe (about 10 seconds). If you created Azure function on consumption plan then the function can go to sleep due to inactivity. The sample will try again and should succeed in next attempts. Alternately, try creating Azure function using App service plan. |
You get errors while installing packages. | Make sure the local path where you placed the solution is not too long/deep. Moving the solution closer to the root drive resolves this issue. |
If you'd like to contribute to this sample, see CONTRIBUTING.MD.
This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact opencode@microsoft.com with any additional questions or comments.
We'd love to get your feedback about the Microsoft Graph Webhooks sample using WebJobs SDK. You can send your questions and suggestions to us in the Issues section of this repository.
Questions about Microsoft Graph in general should be posted to Stack Overflow. Make sure that your questions or comments are tagged with [MicrosoftGraph].
If you have a feature suggestion, please post your idea on our User Voice page, and vote for your suggestions there.
- Microsoft Graph Node.js Webhooks sample
- Working with Webhooks in Microsoft Graph
- Subscription resource
- Microsoft Graph developer site
- Call Microsoft Graph in an ASP.NET MVC app
Copyright (c) 2019 Microsoft Corporation. All rights reserved.