Episode #117 – Using MSAL.NET to access Microsoft Graph – Part 1

Here you can find the transcript of Episode #117 of PiaSys TechBites.

Welcome back to PiaSys Tech Bite. Today I want to talk with you about MSAL, the Microsoft authentication library, which is a library that helps developers to retrieve tokens to consume APIs secure with the Microsoft identity platform. I’m talking about the APIs like the Microsoft Graph, for example, which is for sure the primary API you should consume through MSAL, as well as other Microsoft APIs, like the SharePoint Online APIs or the Power BI REST APIs and so on and so forth. As well as, third-party APIs or APIs developed by yourself and secured in Azure Active Directory. MSAL is available in multiple development platforms and languages. Like for example, Microsoft.NET, JavaScript and TypeScript, Android, macOS and IOS, Python and Java. And why should you use a helper library to consume external APIs and to get an access token to consume external APIs?

Well, first of all, because using a helper library, you can offload the maintenance and support of the authentication logic. Moreover, using such kind of helper library you don’t need to dig into the details of the open authorization protocol, and you can easily get access tokens as delegated access token or app-only access token in order to consume external APIs. Moreover, the MSAL library provides a native cache for the retrieved tokens so that you can speed up the running and the performance of your custom developed application in order to use MSAL first of all, you need to include the package in your solution. And once you have done that, you can use a model based on the idea of having a Builder and through a Builder, you can build a PublicClientApplication or a ConfidentialClientApplication object. The PublicClientApplication targets those scenarios where you want to create a desktop or a mobile application which will be executed on an end user device.

And in there you will retrieve delegated access tokens to behave in the name of the user while costuming the targeted API. The ConfidentialClientApplication on the other side has been defined to be used in websites, web applications, web APIs, demos, function, and stuff like that so that you will need to have typically an application-only Access Token, and it is called ConfidentialClientApplication because you can assume that you can store confidential information like, a shared secret or a certificate that you will use to get that the application-only Access Token. Whether you use the PublicClientApplication or the ConfidentialClientApplication, you will have to register an application in Azure Active Directory, and you will have to configure proper permissions wether delegated or application only permissions to consume the target APIs that you want use.

So let’s move to the new environment and let’s start playing with the PublicClientApplication in a .NET solution. So in order to use a MSAL, first of all we need to register an application in Azure Active Directory. And that’s why I’m going here right now under app registration, I can register an application. I can call it MSALPublicClientDemo, for example, and it will be an application targeting a single tenant, my current tenant. It can be also a multi tenant application, if you like.

Once I have created the application, I can store in a safe place, the client ID, as well as the tenant ID, which will be useful later on in order to consume the Microsoft Identity Platform. Once I’ve done that, I need to go under API permissions and under this section, I need to add the permission scopes that I want to have. So let’s assume that I want to consume Microsoft Graph and specifically with delegated permission because we are using the PublicClientApplication. We are going to use that one. I want to consume the SharePoint Online sites in my tenant. Specifically, I want to be able to read them all of the sites accordingly to the permissions of my currently connected user.

So I will add this permission. And as a tenant admin, I will grant this permission to my tenant and now to my app in my tenant, sorry. So now my app is configured from a permission point of view. I need to go under authentication here. I have to configure what the URL is for my application in order to make it possible for the OpenID Connect and open authorization flow to properly run. So I will add the platform, this will be a mobile or a desktop application because I’m going to create a console application. And as the URL of my application, I will just provide http://locahost just for the sake of making a test in a console application.

Once I’ve done that, I can switch to visual studio where I already created the empty, fresh new console application. And there, I will have to add the reference to the NuGet package of MSAL. So I can search for MSAL and the package is Microsoft.Identity.Client. I will install the latest version at the time of this registration and once I’ve done that, I can go back to my program Main. First of all, MSAL is built up with asynchronous in mind. So I will define my main method as asynchronous, and I will return a task as the result. So once I’ve done that I can create in my application few variables. First of all, we need to create a variable for the PublicClientApplication, so that the PublicClientApplication for my solution for my consumer application. Then I will have to save the client ID and the tenant ID in order to being able to use them to access the target endpoint at the target Azure Active Directory and then the target API and these information are those that I stored before while creating the application in Azure Active Directory.

Once I’ve done that, I also need to configure a variable called authority, which will be a URI, which will uniquely represent target tenant, or the fact that I’m targeting multiple tenants with my application. Right now I’m targeting a specific tenant, the one with the ID that I just copied. So once I’ve done that, I can configure the PublicClient variable, and I will do that using the PublicClientApplicationBuilder. First of all, I will say that I want to create a new builder for my client ID. Then I will say that I want to use as the authority the one that I just configured and moreover, I want to use as the redirect Uri for my application, the one that I configured earlier, so http://localhost. Once I’ve done that, I can build my client application and I will get back an instance of the IPublicClientApplication interface.

Then when I want to get a token, I need to specify the permission scopes that I want to have in the token. So let me declare a variable called scopes. Which will be an array of strings, and which will contain the permission scopes that I want to have. Those permissions scopes are available under Azure Active Directory. If I go back to the API permissions section, and for example, I select this permission. Here I can see what the permission scope is. Let me copy this value, and this will be the content or the unique item in the array of scopes that I want to use. Okay, now I need to make a request for the token. So I will need to get a variable of type AuthenticationResult, which I can call result, and which will be the result of in asynchronous call to public client.

And I will use the AcquireTokenInteractive, which will prompt the user with a UI to get the authentication in place for the permission scope that I want to get. And I will execute the synchronous with these method. Once I’ve done that, I will get back up an access token which I can write on the console window, just for the sake of showing you the output. But I want to do more, with the access token that I just got, I want to consumer SharePoint Online effectively. So let me create an HTTP client variable, which will be a new instance of HttpClient type in System.Net and once I have this object, I also create an HTTP Request, which will represent a request to the Microsoft Graph API. So it will be a new HttpRequestMessage. This request message will be for the HTTP method GET, and I want to target the URL of my SharePoint Online API through my Microsoft Graph.

So for example, it will be https://graph.microsoft.com/v1.0/sites API and specifically I want in my current tenant to get the route site collection of my SharePoint Online tenant. So once I’ve done that, I also need to configure in the HTTP request that I want to use a request HTTP header of type authorization, which will include the access token as the bearer authorization token. So let me do that request.headers.authorization and it will be the authentication header value an instance of the AuthenticationHeadrValue with an header of type Bearer and with a value, which will be the content of my result.AccessToken so that I will place the open authorization access token as the bearer authorization token in the request.

So now I can make the request and get a response. So I will say httpClient.SendAsync and I will send the httpRequest. Of course, the SendAsync is in a Asynchronous method. So I need an, await in the method invocation and once I’ve done that, I can evaluate that the response. First of all, I can see if the response is successful or not, and if it is successful, I can then say, okay so let’s try it on the console the Response.Content.ReadAsStringAsync().

And again, I need that wait, because this is in asynchronous method on the contrary, in case of any failure, I will simply provide the content of the response, but I will first say, okay, console foreground color, let’s say the color will be red. So, and again, Console.WriteLine and I will write still the content of the response. So let me build and run this application. It builds at five. Here is the console application, and there is the web browser. I have the interactive login. I will log in with my account, now I’m logged in and I can go back to the application. And here you can see, in the console application, I get the access token as well as the JSON response for the content of my route site collection. So really simple, really straightforward.

Like always thank you for watching this video. I hope you found it interesting and I’m really looking forward to seeing you next week, still talking about MSAL for .NET and using the ConfidentialClientApplication and remember subscribe to this channel. Thank you.