Tuesday, 16 November 2021

Interactively authenticate Microsoft Graph .NET SDK with Azure Identity library

In this post, we will have a look at the new recommended way of using the Azure Identity library to authenticate to the Microsoft Graph .NET SDK. Since v4 of the Microsoft Graph SDK, using the Azure.Identity library is the preferred way to auth with the Graph over the previous Microsoft.Graph.Auth method. You can read more about it here: https://github.com/microsoftgraph/msgraph-sdk-dotnet/blob/dev/docs/upgrade-to-v4.md#azure-identity

Specifically, we will have a look at Interactive browser based authentication where the user would enter their credentials and the Azure Identity library will fetch the access token based on them.

Before going through the code, let us check out the Azure AD App registration which would be used to authenticate to the Graph API

Since we are going to authenticate from a .NET Desktop console application, we will select Desktop as a platform and add the default redirect URIs. In addition, we will also add http://localhost to the list.

The supported account types can be as per your requirements. I have selected the app to be multi tenant.

Select the Allow public client flows to "Yes":  


Select the needed scopes:


Once all of this in place, we can use the following code to open a browser window and authenticate to the Microsoft Graph once the user enters their credentials:

If this is the first time logging into this tenant, you will need to grant permissions to the app:


Once the authentication happens, you will see a similar message in the browser:



and our console window logs the current access token along with the expiry time and also uses the Graph SDK to get the display name of the current user:


Hope that helps!

No comments: