Manage Azure AD B2C with Microsoft Graph

Microsoft Graph allows you to manage resources in your Azure AD B2C directory. The following Microsoft Graph API operations are supported for the management of Azure AD B2C resources, including users, identity providers, user flows, custom policies, and policy keys. Each link in the following sections targets the corresponding page within the Microsoft Graph API reference for that operation.

Note

You can also programmatically create an Azure AD B2C directory itself, along with the corresponding Azure resource linked to an Azure subscription. This functionality isn't exposed through the Microsoft Graph API, but through the Azure REST API. For more information, see B2C Tenants - Create.

Watch this video to learn about Azure AD B2C user migration using Microsoft Graph API.

Prerequisites

To use MS Graph API, and interact with resources in your Azure AD B2C tenant, you need an application registration that grants the permissions to do so. Follow the steps in the Manage Azure AD B2C with Microsoft Graph article to create an application registration that your management application can use.

User management

User phone number management (beta)

A phone number that can be used by a user to sign-in using SMS or voice calls, or multi-factor authentication. For more information, see Azure AD authentication methods API.

Note, the list operation returns only enabled phone numbers. The following phone number should be enabled to use with the list operations.

Enable phone sign-in

Note

In the current beta version, this API works only if the phone number is stored with a space between the country code and the phone number. The Azure AD B2C service doesn't currently add this space by default.

Self-service password reset email address (beta)

An email address that can be used by a username sign-in account to reset the password. For more information, see Azure AD authentication methods API.

Identity providers

Manage the identity providers available to your user flows in your Azure AD B2C tenant.

User flow

Configure pre-built policies for sign-up, sign-in, combined sign-up and sign-in, password reset, and profile update.

User flow authentication methods (beta)

Choose a mechanism for letting users register via local accounts. Local accounts are the accounts where Azure AD does the identity assertion. For more information, see b2cAuthenticationMethodsPolicy resource type.

Custom policies

The following operations allow you to manage your Azure AD B2C Trust Framework policies, known as custom policies.

Policy keys

The Identity Experience Framework stores the secrets referenced in a custom policy to establish trust between components. These secrets can be symmetric or asymmetric keys/values. In the Azure portal, these entities are shown as Policy keys.

The top-level resource for policy keys in the Microsoft Graph API is the Trusted Framework Keyset. Each Keyset contains at least one Key. To create a key, first create an empty keyset, and then generate a key in the keyset. You can create a manual secret, upload a certificate, or a PKCS12 key. The key can be a generated secret, a string (such as the Facebook application secret), or a certificate you upload. If a keyset has multiple keys, only one of the keys is active.

Trust Framework policy keyset

Trust Framework policy key

Applications

Application extension properties

Azure AD B2C provides a directory that can hold 100 custom attributes per user. For user flows, these extension properties are managed by using the Azure portal. For custom policies, Azure AD B2C creates the property for you, the first time the policy writes a value to the extension property.

Audit logs

For more information about accessing Azure AD B2C audit logs, see Accessing Azure AD B2C audit logs.

Conditional Access

How to programmatically manage Microsoft Graph

When you want to manage Microsoft Graph, you can either do it as the application using the application permissions, or you can use delegated permissions. For delegated permissions, either the user or an administrator consents to the permissions that the app requests. The app is delegated with the permission to act as a signed-in user when it makes calls to the target resource. Application permissions are used by apps that do not require a signed in user present and thus require application permissions. Because of this, only administrators can consent to application permissions.

Note

Delegated permissions for users signing in through user flows or custom policies cannot be used against delegated permissions for Microsoft Graph.

Code sample: How to programmatically manage user accounts

This code sample is a .NET Core console application that uses the Microsoft Graph SDK to interact with Microsoft Graph API. Its code demonstrates how to call the API to programmatically manage users in an Azure AD B2C tenant. You can download the sample archive (*.zip), browse the repository on GitHub, or clone the repository:

git clone https://github.com/Azure-Samples/ms-identity-dotnetcore-b2c-account-management.git

After you've obtained the code sample, configure it for your environment and then build the project:

  1. Open the project in Visual Studio or Visual Studio Code.

  2. Open src/appsettings.json.

  3. In the appSettings section, replace your-b2c-tenant with the name of your tenant, and Application (client) ID and Client secret with the values for your management application registration. For more information, see Register a Microsoft Graph Application.

  4. Open a console window within your local clone of the repo, switch into the src directory, then build the project:

    cd src
    dotnet build
    
  5. Run the application with the dotnet command:

    dotnet bin/Debug/netcoreapp3.1/b2c-ms-graph.dll
    

The application displays a list of commands you can execute. For example, get all users, get a single user, delete a user, update a user's password, and bulk import.

Note

For the application to update user account passwords, you'll need to grant the user administrator role to the application.

Code discussion

The sample code uses the Microsoft Graph SDK, which is designed to simplify building high-quality, efficient, and resilient applications that access Microsoft Graph.

Any request to the Microsoft Graph API requires an access token for authentication. The solution makes use of the Microsoft.Graph.Auth NuGet package that provides an authentication scenario-based wrapper of the Microsoft Authentication Library (MSAL) for use with the Microsoft Graph SDK.

The RunAsync method in the Program.cs file:

  1. Reads application settings from the appsettings.json file

  2. Initializes the auth provider using OAuth 2.0 client credentials grant flow. With the client credentials grant flow, the app is able to get an access token to call the Microsoft Graph API.

  3. Sets up the Microsoft Graph service client with the auth provider:

    // Read application settings from appsettings.json (tenant ID, app ID, client secret, etc.)
    AppSettings config = AppSettingsFile.ReadFromJsonFile();
    
    // Initialize the client credential auth provider
    IConfidentialClientApplication confidentialClientApplication = ConfidentialClientApplicationBuilder
        .Create(config.AppId)
        .WithTenantId(config.TenantId)
        .WithClientSecret(config.ClientSecret)
        .Build();
    ClientCredentialProvider authProvider = new ClientCredentialProvider(confidentialClientApplication);
    
    // Set up the Microsoft Graph service client with client credentials
    GraphServiceClient graphClient = new GraphServiceClient(authProvider);
    

The initialized GraphServiceClient is then used in UserService.cs to perform the user management operations. For example, getting a list of the user accounts in the tenant:

public static async Task ListUsers(GraphServiceClient graphClient)
{
    Console.WriteLine("Getting list of users...");

    // Get all users (one page)
    var result = await graphClient.Users
        .Request()
        .Select(e => new
        {
            e.DisplayName,
            e.Id,
            e.Identities
        })
        .GetAsync();

    foreach (var user in result.CurrentPage)
    {
        Console.WriteLine(JsonConvert.SerializeObject(user));
    }
}

Make API calls using the Microsoft Graph SDKs includes information on how to read and write information from Microsoft Graph, use $select to control the properties returned, provide custom query parameters, and use the $filter and $orderBy query parameters.