How to use Microsoft Graph API in UWP
Microsoft Graph APIs has very powerful feature sets. My favorite is findMeetingTimes API.
There are a lot of APIs outside of this.
In this article, I explain how to use Microsoft Graph APIs in your UWP app.
Following list is steps to use Graph APIs in your app.
- Register app to Azure AD
- Add permission to the app
- Add authentication logic in your app
- Call the APIs
Register app to Azure AD
Sign in to https://portal.azure.com. Then click “New application registration (Preview)” button at “Azure Active Directory > App registrations”. Fill the form below values:
- Name: Your app name
- Support account types: Accounts in any organizational directory
After created the app, you can see “Application ID” on Azure portal. Please store the value because to use after. And then, check “urn:ietf:wg:oauth:2.0:oob” on “Authentication”.
Add permission to the app
Next step is adding permission to the app. Select “API permissions”. Then select permissions to call API you want. The permission is defined on the document. In this sample app, I want to call “Get a user” api.
“User.Read” permission is already added.
Add authentication logic in your app
In Azure AD v2, we can use MSAL.NET library.
Add “Microsoft.Identity.Client” to UWP project using NuGet package manager. Next, add “Const.cs” to the project, and then add “ClientId” property and “Scopes” property to the file.
Edit MainPage.xaml like below:
Then add SignInButton_Click method to MainPage.xaml.cs.
OK, launch the app ,then click sign in button ,and then Sign In dialog is appeared.
After sign in, access token is shown on “Output Window”.
Call the APIs
You can call APIs using the access token. In UWP, you can use “Microsoft.Graph” package.
Add the package, then edit the files like below:
After launch the app and sign in, user profile is displayed.
Conclusion
Microsoft Graph APIs is powerful API set. You can use the APIs in your apps.
Have a fun programming.