Microsoft Graph – How to implement IAuthenticationProvider
Beginning
In the article about integration Azure AD with Angular I got a question how to implement Microsoft Graph on API side. I’ll show you here how to implement IAuthenticationProvider in the simplest way.
Overview
The Microsoft Graph is powerful tool to interact with most important Office 365 and Azure Active Directory. List of most common services what you can access data:
- Azure Active Directory
- Office 365
- OneDrive
- Outlook / Exchange
- OneNote
- Planner
- Microsoft Teams
- SharePoint
- Windows 10 services
Register & configure application on azure
After login on https://portal.azure.com go to Azure Active Directory > App Registrations and click New Registration and follow simple instructions, if you will stuck do this by analogy from this article.
If you have already registered application, you need generate your secret for application, you can do this in Certificates & secrets section while editing registered application.
Important! Copy immediately your secret, generated secret is only once available to see.
In next step you should give application appropriate permissions in API permissions section. After that we can go to the implementation in C#
Implementation
Now you need to install these Nuget packages:
- Microsoft.Graph
- Microsoft.Graph.Core
- Microsoft.Identity.Client
Now it’s time to implement IAuthenticationProvider, I’ll show you the simplest way to implement it in my opinion. However, there are many different ways to do it.
AuthenticationProvider.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
public class AuthenticationProvider : IAuthenticationProvider { private readonly string clientId; private readonly string clientSecret; private readonly string[] appScopes; private readonly string tenantId; public AuthenticationProvider(string clientId, string clientSecret, string[] appScopes, string tenantId) { this.clientId = clientId; this.clientSecret = clientSecret; this.appScopes = appScopes; this.tenantId = tenantId; } public async Task AuthenticateRequestAsync(HttpRequestMessage request) { var clientApplication = ConfidentialClientApplicationBuilder.Create(this.clientId) .WithClientSecret(this.clientSecret) .WithClientId(this.clientId) .WithTenantId(this.tenantId) .Build(); var result = await clientApplication.AcquireTokenForClient(this.appScopes).ExecuteAsync(); request.Headers.Add("Authorization", result.CreateAuthorizationHeader()); } } |
Summary
That’s all! After that simple implementation, you need to create only GraphServiceClient and inject in constructor your implementation of IAuthenticationProvider and make request 🙂
If my articles helped you, that would be nice if you like my Facebook fanpage 🙂