Introduction
In the world of modern identity and access management, Azure Active Directory B2C (Azure AD B2C) stands out as a powerful solution for implementing secure and user-friendly authentication and authorization experiences in applications. Whether you're building a web or mobile application, Azure AD B2C provides a scalable and customizable identity platform that enables you to integrate identity services seamlessly.
To harness the full potential of Azure AD B2C and streamline the development process, Microsoft Graph SDK into play. The Microsoft Graph SDK simplifies the interaction with Azure AD B2C by providing a consistent and intuitive programming model. This allows developers to focus on building robust identity experiences without getting bogged down by intricate API interactions.
In this article, we will explore the integration of Azure AD B2C with the Microsoft Graph SDK with C#. We’ll discuss the capabilities offered by the Microsoft Graph SDK for Azure AD B2C with practical examples of getting the Azure AD B2C user list using Microsoft Graph to guide you through the process of incorporating these technologies into your applications.
Azure AD B2C Application Registration
Let’s start with registering a new application in Azure AD B2C
Step 1. Log in to Azure AD B2C tenant using an admin account.
Step 2. Go to Azure AD B2C services - > App registration.
Step 3. Create a new application; in my case, I named it as B2CUserMigration.
Step 4. After creating an application, go to API Permissions, and add Microsoft Graph application permissions for Directory read and write.
Step 5. Create a Secret. Click on Certification & secrets, and add a new client secret. Copy the value, we will be using it later.
Create .NET 8 console Application with Microsoft Graph package
I have created a .NET 8 console application using Visual Studio 2022. Prefer your IDE and create a .NET 8 Console application.
Install all the latest stable following packages using NuGet package manager.
- Azure.Identity
- Microsoft.Extensions.Configuration
- Microsoft.Extensions.Configuration.Binder
- Microsoft.Extensions.Configuration.FileExtensions
- Microsoft.Extensions.Configuration.Json
- Microsoft.Graph
Create an appsettings.json file to configure the Azure AD B2C details.
{
"appSettings": {
"TenantId": "[yourtenantname].onmicrosoft.com",
"AppId": "[you new registered app ID]",
"ClientSecret": "[your new app client secret]",
"B2cExtensionAppClientId": "[app id of the B2CExtensioAppClientId app]",
}
}
- TenantId: Replace with your tenant’s name.
- AppId: Provide the new registered application ID.
- CleintSecret: Provide the copied application secret.
- B2cExtensionAppClientId: By default, this app is registered with B2C to store the Extension attribute details.
Create a new model file AppSettingsFile.cs, and add the following code.
public class AppSettingsFile
{
public AppSettings AppSettings { get; set; }
public static AppSettings ReadFromJsonFile()
{
IConfigurationRoot Configuration;
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json");
Configuration = builder.Build();
return Configuration.Get<AppSettingsFile>().AppSettings;
}
}
public class AppSettings
{
[JsonPropertyName("TenantId")]
public string TenantId { get; set; }
[JsonPropertyName("AppId")]
public string AppId { get; set; }
[JsonPropertyName("ClientSecret")]
public string ClientSecret { get; set; }
[JsonPropertyName("B2cExtensionAppClientId")]
public string B2cExtensionAppClientId { get; set; }
[JsonPropertyName("UsersFileName")]
public string UsersFileName { get; set; }
}
The above ReadFromJsonFile function will be used to read a B2C configuration from the appsettings.json file.
Open Program.cs file and add the following code.
AppSettings config = AppSettingsFile.ReadFromJsonFile();
var scopes = new[] { "https://graph.microsoft.com/.default" };
var clientSecretCredential = new ClientSecretCredential(config.TenantId, config.AppId, config.ClientSecret);
var graphClient = new GraphServiceClient(clientSecretCredential, scopes);
The above code is used to initialize the Microsoft Graph client.
Create a new class to add the service methods. In my case, I named it as UserService.cs.
public static async Task ListUsers(GraphServiceClient graphClient)
{
Console.WriteLine("Getting list of users...");
try
{
var users = await graphClient.Users.GetAsync();
var pageIterator = PageIterator<User, UserCollectionResponse>
.CreatePageIterator(
graphClient,
users,
(user) =>
{
Console.WriteLine(JsonSerializer.Serialize(user));
return true;
},
(req) =>
{
Console.WriteLine($"Reading next page of users...");
return req;
}
);
await pageIterator.IterateAsync();
}
catch (Exception ex)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(ex.Message);
Console.ResetColor();
}
}
The above List Users function will be used to get all user details from Azure AD B2C using graph client. The PageIterator class efficiently manages the enumeration of the present page and automatically triggers requests for subsequent pages.
The PostAsync method will be used to create a new account with the graph client. We will see more about creating, updating and deleting the use accounts with graph client in my next article.
Summary
In this article, we explore the process of acquiring user account details in Azure AD B2C using the Microsoft Graph SDK. It started with the crucial step of Azure AD B2C application registration, ensuring a seamless integration for subsequent operations. Next, it covered the creation of a .NET 8 console application, establishing the foundation for leveraging the power of the Microsoft Graph SDK. Finally, we created a sample function using the Microsoft graph client with C# to retrieve comprehensive user details.
Download the source code from GitHub.