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.

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 Register a Microsoft Graph application article to create an application registration that your management application can use.

User management

Note

Azure AD B2C currently does not support advanced query capabilities on directory objects. This means that there is no support for $count, $search query parameters and Not (not), Not equals (ne), and Ends with (endsWith) operators in $filter query parameter. For more information, see query parameters in Microsoft Graph and advanced query capabilities in Microsoft Graph.

User migration

Watch this video to learn how user migration to Azure AD B2C can be managed using Microsoft Graph API.

User phone number management

A phone number that can be used by a user to sign-in using SMS or voice calls, or multifactor authentication. For more information, see Microsoft Entra 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.

Note

A correctly represented 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.

Screenshot of the Authentication methods page for a sample user from the Azure portal. The text box for phone number is highlighted.

Self-service password reset email address

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

Software OATH token authentication method

A software OATH token is a software-based number generator that uses the OATH time-based one-time password (TOTP) standard for multifactor authentication via an authenticator app. Use the Microsoft Graph API to manage a software OATH token registered to a user:

Identity providers

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

User flow (beta)

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. A Local account is one where Azure AD B2C completes the identity assertion. For more information, see b2cAuthenticationMethodsPolicy resource type.

Custom policies (beta)

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

Policy keys (beta)

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 (directory extension) properties

Application extension properties are also known as directory or Microsoft Entra extensions. To manage them in Azure AD B2C, use the identityUserFlowAttribute resource type and its associated methods.

You can store up to 100 directory extension values per user. To manage the directory extension properties for a user, use the following User APIs in Microsoft Graph.

  • Update user: To write or remove the value of the directory extension property from the user object.
  • Get a user: To retrieve the value of the directory extension for the user. The property will be returned by default through the beta endpoint, but only on $select through the v1.0 endpoint.

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.

Note

In Microsoft Entra ID, directory extensions are managed through the extensionProperty resource type and its associated methods. However, because they are used in B2C through the b2c-extensions-app app which should not be updated, they are managed in Azure AD B2C using the identityUserFlowAttribute resource type and its associated methods.

Tenant usage

Use the Get organization details API to get your directory size quota. You need to add the $select query parameter as shown in the following HTTP request:

GET https://graph.microsoft.com/v1.0/organization/organization-id?$select=directorySizeQuota

Replace organization-id with your organization or tenant ID.

The response to the above request looks similar to the following JSON snippet:

{
    "directorySizeQuota": {
        "used": 156,
        "total": 1250000
    }
}

Audit logs

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

Conditional Access

Retrieve or restore deleted users and applications

Deleted users and apps can only be restored if they were deleted within the last 30 days.

How to programmatically manage Microsoft Graph

You can manage Microsoft Graph in two ways:

  • 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. 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 API.

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
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 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...");

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

        // Iterate over all the users in the directory
        var pageIterator = PageIterator<User>
            .CreatePageIterator(
                graphClient,
                users,
                // Callback executed for each user in the collection
                (user) =>
                {
                    Console.WriteLine(JsonSerializer.Serialize(user));
                    return true;
                },
                // Used to configure subsequent page requests
                (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();
    }
}

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.

See also