Hello All!,
I started working on .NET Core just recently. My first ever task for client was to write some web APIs to communicate with the
Azure AD and fetch all the users and groups from it. I was naive to .NET Core and had just heard about the active directory thing, but never worked on it, so I planned to go by the traditional process!
Following the said process, I started studying
Microsoft Graph APIs (obviously from the documents provided by Microsoft) and side by side, read some blogs and posts on how to implement them in our application. I also referred some boiler plates and sample codes to get my job started.
What I found was, many of them had some UI part associated with them for authentication process. i.e. A login screen pops in where you need to type your Microsoft account id and password and submit the form. This certainly was not required at my end, reason being, I was working on web APIs and this authentication process was supposed to be handled somehow at the back end itself.
Thus, I had to collect all the bits and pieces and try to integrate them down in a single project. So, I thought that I should document all my tasks and share with others believing that it might save your time and reduce your efforts had you been working on similar thing. Also, being a newbie in writing, I am trying to put down my understandings in a fashion, as simple as it can be, so as to help you understand better. Feel free to correct me wherever needed and pardon me if I am not very clear on some concepts or in case I miss something out.
Whoosh! Finally done with the description and now we can get start working on the actual thing why we are here.
Prerequisites
- You need to have a registered application on Azure Active Directory. Note down the Tenant Id, Application Id and Secret Key for the registered application. (You can refer this for guide and walkthrough )
- Visual Studio Professional 2017. You can also opt for other versions of VS / Visual Studio Code as per your convenience.
Actual Work
Note
If you are familiar with creating projects in Visual Studio, you can directly jump to step number 2.
Step 1
Create a new project in Visual Studio.
Go to File -> New -> Project.
From the templates, under Visual C# section, select .NET Core.
Select ASP.NET Core Web Application project.
Give the desired project name and location and click OK.
From the new window, select ASP.NET Core version 2.1 and API template. Click OK.
Now, your new project will load in the solution explorer with a default ValuesController under controller folder. (You can delete this controller as and when required, for now, let us add a new controller and get started).
Go to appsettings.json and add a new key named AzureAD which will have all the values that we need. These values would be those that we noted while registering our application on Azure AD (mentioned in prerequisites (1)).
After adding this code, your appsetting.json would look as follows,
- {
- "Logging":
- {"LogLevel":
- {"Default": "Warning"}},
- "AllowedHosts": "*",
- "AzureAD": {
- "ClientId": "Your Application Id goes here",
- "ClientSecret": "Your Secret Key goes here",
- "TenantId": "Your Tenant Id goes here",
- "Instance": "https://login.microsoftonline.com/",
- "GraphResource": "https://graph.microsoft.com/",
- "GraphResourceEndPoint": "v1.0"
- }
- }
Step 2 - Creating Models.
Right click on the project name in solution explorer,
Select Add -> New Folder. Name it as Models.
Right click the Models folder, select Add -> Class.
We would be adding 3 class files, namely AzureAD.cs, Group.cs and User.cs
The classes are as follows,
AzureAD.cs
- public class AzureAD
- {
- public string ClientId { get; set; }
- public string ClientSecret { get; set; }
- public string TenantId { get; set; }
- public string Instance { get; set; }
- public string GraphResource { get; set; }
- public string GraphResourceEndPoint { get; set; }
- }
Group.cs
- public class Group
- {
- public string id { get; set; }
- public string displayName { get; set; }
- }
-
- public class Groups
- {
- public int itemsPerPage { get; set; }
- public int startIndex { get; set; }
- public int totalResults { get; set; }
- public List resources { get; set; }
- }
User.cs
- public class User
- {
- public string id { get; set; }
- public string givenName { get; set; }
- public string surname { get; set; }
- public string userPrincipalName { get; set; }
- public string email { get; set; }
- }
-
- public class Users
- {
- public int itemsPerPage { get; set; }
- public int startIndex { get; set; }
- public int totalResults { get; set; }
- public List resources { get; set; }
- }
The AzureAD models class would be used while getting values from out config file (from appsettings.json) and the other 2 classes , as their names suggest, would be used while actually retrieving data from the AD. Our models are ready. Lets head to the next step.
Step 3 - Adding a Controller
Right click the Controllers folder,
select Add -> Controller. Give name as MyDirectory (MyDirectoryController is the desired name) and click Add.
Add the following code to MyDirectoryController.cs
Now, we have implemented 4 methods. These methods would serve the purpose exactly how their names suggest i.e. get user by id, get all users from the AD, get group by id and get all groups from the AD respectively.
The 2 things that are missing now are MicrosoftGraphClient and CopyHandler. Head over to next steps for the same.
Step 4 - Adding MicrosoftGraphClient
Add a new folder in our project as we did earlier and name it as Services. Add a new class to this folder which would be MicrosoftGraphClient.cs
The following code goes there,
- using WebApiWithGraph.Models;
- using Microsoft.Extensions.Configuration;
- using Microsoft.Graph;
- using Microsoft.IdentityModel.Clients.ActiveDirectory;
- using System;
- using System.Linq;
- using System.Net.Http.Headers;
- using System.Threading.Tasks;
- namespace WebApiWithGraph.Services{
-
- public static class MicrosoftGraphClient
- {
- private static GraphServiceClient graphClient;
- private static IConfiguration configuration;
- private static string clientId;
- private static string clientSecret;
- private static string tenantId;
- private static string aadInstance;
- private static string graphResource;
- private static string graphAPIEndpoint;
- private static string authority;
-
- static MicrosoftGraphClient()
- {
- configuration = new ConfigurationBuilder().SetBasePath(System.IO.Directory.GetCurrentDirectory())
- .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
- .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", optional: true)
- .AddEnvironmentVariables()
- .Build();
- SetAzureADOptions();
- }
-
- private static void SetAzureADOptions()
- {
- var azureOptions = new AzureAD();
- configuration.Bind("AzureAD", azureOptions);
- clientId = azureOptions.ClientId;
- clientSecret = azureOptions.ClientSecret;
- tenantId = azureOptions.TenantId;
- aadInstance = azureOptions.Instance;
- graphResource = azureOptions.GraphResource;
- graphAPIEndpoint = $"{azureOptions.GraphResource}{azureOptions.GraphResourceEndPoint}";
- authority = $"{aadInstance}{tenantId}";
- }
-
- public static async Task GetGraphServiceClient()
- {
-
- var delegateAuthProvider = await GetAuthProvider();
-
- graphClient = new GraphServiceClient(graphAPIEndpoint, delegateAuthProvider);
- return graphClient;
- }
-
- private static async Task GetAuthProvider()
- {
- AuthenticationContext authenticationContext = new AuthenticationContext(authority);
- ClientCredential clientCred = new ClientCredential(clientId, clientSecret);
-
- AuthenticationResult authenticationResult = await authenticationContext.AcquireTokenAsync(graphResource, clientCred);
- var token = authenticationResult.AccessToken;
- var delegateAuthProvider = new DelegateAuthenticationProvider((requestMessage) =>{
- requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", token.ToString());
- return Task.FromResult(0);
- });
- return delegateAuthProvider;
- }
- }
- }
Here, we have 3 methods : SetAzureADOptions, GetGraphServiceClient and GetAuthProvider. You can see that in the constructor of the MicrosoftGraphClient, we have built the configuration.
The SetAzureADOptions method will read the config for us and get the required details that we have stored in appsettings.json in Step (1).
The GetGraphServiceClient method will call GetAuthProvider method internally and return that value along with graphAPIEndpoint (which is constructed in SetAzureADOptions method ).
The GetAuthProvider method would take our client id and secret and authenticate these credentials with the graph resource (i.e. https://graph.microsoft.com/) and get a token for us. This token is the bearer token that is required to pass in the header of all the requests made to the Microsoft Graph API.
Thus, in a nutshell, the MicrosoftGraphClient authenticates our credentials with the graph resource and returns a client to the controller. Now, in the controller, we can request and retrieve the desired data from this client.Now, we are almost at the end of our work.
You can head to the last step now i.e. Step 5.
Step 5 - Adding CopyHandler
This step can be said to be optional. This handler is used just for type conversion (i.e. to convert the Microsoft.Graph.User to our defined class Models .User, and, to convert the Microsoft.Graph.Group to our defined class Models.Group). So, you can either use this handler, or you can also handle the type casting then and there in the controller as per your convenience. Add a new class to the Services folder and name it CopyHandler. The following code goes in CopyHandler.cs
- using WebApiWithGraph.Models;
- namespace WebApiWithGraph.Services
- {
- public class CopyHandler
- {
- public static User UserProperty(Microsoft.Graph.User graphUser)
- {
- User user = new User();
- user.id = graphUser.Id;
- user.givenName = graphUser.GivenName;
- user.surname = graphUser.Surname;
- user.userPrincipalName = graphUser.UserPrincipalName;
- user.email = graphUser.Mail;
- return user;
- }
-
- public static Group GroupProperty(Microsoft.Graph.Group graphGroup)
- {
- Group group = new Group();
- group.id = graphGroup.Id;
- group.displayName = graphGroup.DisplayName;
- return group;
- }
- }
- }
Running the application
Now, our coding part is done and we can go ahead and check it's working. This can be done with tools like swagger, advanced rest client, postman, etc, just as we test the APIs for the data. We can also see the output in the browser (I used Chrome) by just changing the URLs.Run the application through Visual Studio using IIS Express in Chrome. This will open a new window of Google Chrome with the URL somewhat like,
https://localhost:44385/api/values
Change the URL to,
https://localhost:44385/directory/users
and hit enter.
You should see the list of users from your Azure AD in JSON format. Grab and copy anyone user id from the above mentioned data and now change the URL to,
https://localhost:44385/directory/users/123abc-12ab-12ab-12ab-12ab12ab
and hit enter.
You should see the JSON data for that single user!
Repeat the same for getting groups and group by id. The URLs would be,
https://localhost:44385/directory/groups
and
https://localhost:44385/directory/groups/123abc-12ab-12ab-12ab-12ab12ab
respectively.
Conclusion
So, here I think I should conclude this topic.
Hope this post will help you in case you face the same situation that I did. If I have missed anything, let me know in the comments and I'll add it in! You can get the
sample application here.
Cheers!