使用 Microsoft Graph 管理 Azure AD B2C 用户帐户Manage Azure AD B2C user accounts with Microsoft Graph

Microsoft Graph 允许通过在 Microsoft Graph API 中提供创建、读取、更新和删除方法来管理 Azure AD B2C 目录中的用户帐户。Microsoft Graph allows you to manage user accounts in your Azure AD B2C directory by providing create, read, update, and delete methods in the Microsoft Graph API. 可以调用 Microsoft Graph API 将现有用户存储迁移到 Azure AD B2C 租户并执行其他用户帐户管理操作。You can migrate an existing user store to an Azure AD B2C tenant and perform other user account management operations by calling the Microsoft Graph API.

后面的部分将演示使用 Microsoft Graph API 管理 Azure AD B2C 用户时的重要方面。In the sections that follow, the key aspects of Azure AD B2C user management with the Microsoft Graph API are presented. 本文演示的 Microsoft Graph API 操作、类型和属性是 Microsoft Graph API 参考文档中显示的相应元素的一部分。The Microsoft Graph API operations, types, and properties presented here are a subset of that which appears in the Microsoft Graph API reference documentation.

注册管理应用程序Register a management application

在编写的任何用户管理应用程序或脚本可与 Azure AD B2C 租户中的资源交互之前,需要创建一个应用程序注册,以授权执行此类操作。Before any user management application or script you write can interact with the resources in your Azure AD B2C tenant, you need an application registration that grants the permissions to do so.

遵循本操作指南文章中的步骤创建管理应用程序可以使用的应用程序注册:Follow the steps in this how-to article to create an application registration that your management application can use:

使用 Microsoft Graph 管理 Azure AD B2CManage Azure AD B2C with Microsoft Graph

用户管理 Microsoft Graph 操作User management Microsoft Graph operations

Microsoft Graph API 中可以使用以下用户管理操作:The following user management operations are available in the Microsoft Graph API:

用户属性User properties

显示名称属性Display name property

displayName 是要在用户的 Azure 门户用户管理界面中显示的,以及要在 Azure AD B2C 返回给应用程序的访问令牌中显示的名称。The displayName is the name to display in Azure portal user management for the user, and in the access token Azure AD B2C returns to the application. 此属性是必需项。This property is required.

标识属性Identities property

客户帐户(可以是使用者、合作伙伴或居民)可与以下标识类型相关联:A customer account, which could be a consumer, partner, or citizen, can be associated with these identity types:

  • 本地标识 - 将用户名和密码存储在 Azure AD B2C 目录本地。Local identity - The username and password are stored locally in the Azure AD B2C directory. 我们通常将此类标识称为“本地帐户”。We often refer to these identities as "local accounts."
  • 联合标识 - 也称为社交或企业帐户,该用户标识由 Microsoft、ADFS 或 Salesforce 等联合标识提供者进行管理。 Federated identity - Also known as a social or enterprise accounts, the identity of the user is managed by a federated identity provider like Microsoft, ADFS, or Salesforce.

具有客户帐户的用户可以使用多个标识进行登录。A user with a customer account can sign in with multiple identities. 例如,使用用户名、电子邮件、员工 ID、政府 ID 等。For example, username, email, employee ID, government ID, and others. 一个帐户可以有多个密码相同的本地和社交标识。A single account can have multiple identities, both local and social, with the same password.

在 Microsoft Graph API 中,本地标识和联合标识都存储在 objectIdentity 类型的用户 identities 特性中。In the Microsoft Graph API, both local and federated identities are stored in the user identities attribute, which is of type objectIdentity. identities 集合表示用于登录到用户帐户的一组标识。The identities collection represents a set of identities used to sign in to a user account. 此集合使用户能够使用其关联的任何标识登录到用户帐户。This collection enables the user to sign in to the user account with any of its associated identities.

属性Property 类型Type 说明Description
signInTypesignInType stringstring 指定目录中的用户登录类型。Specifies the user sign-in types in your directory. 对于本地帐户:emailAddressemailAddress1emailAddress2emailAddress3userName,或所需的任何其他类型。For local account: emailAddress, emailAddress1, emailAddress2, emailAddress3, userName, or any other type you like. 社交帐户必须设置为 federatedSocial account must be set to federated.
颁发者issuer stringstring 指定标识的颁发者。Specifies the issuer of the identity. 对于本地帐户(其 signInType 不是 federated),此属性是本地 B2C 租户的默认域名,例如 contoso.partner.onmschina.cnFor local accounts (where signInType is not federated), this property is the local B2C tenant default domain name, for example contoso.partner.onmschina.cn. 对于社交标识(其 signInTypefederated),该值是颁发者的名称。For social identity (where signInType is federated) the value is the name of the issuer
issuerAssignedIdissuerAssignedId stringstring 指定由颁发者分配给用户的唯一标识符。Specifies the unique identifier assigned to the user by the issuer. issuerissuerAssignedId 的组合在租户中必须唯一。The combination of issuer and issuerAssignedId must be unique within your tenant. 对于本地帐户,当 signInType 设置为 emailAddressuserName 时,它表示用户的登录名。For local account, when signInType is set to emailAddress or userName, it represents the sign-in name for the user.
如果 signInType 设置为:When signInType is set to:
  • emailAddress(或以 emailAddress 开头,例如 emailAddress1),则 issuerAssignedId 必须是有效的电子邮件地址emailAddress (or starts with emailAddress like emailAddress1) issuerAssignedId must be a valid email address
  • userName(或任何其他值),则 issuerAssignedId 必须是有效的电子邮件地址本地部分userName (or any other value), issuerAssignedId must be a valid local part of an email address
  • federated,则 issuerAssignedId 表示联合帐户唯一标识符federated, issuerAssignedId represents the federated account unique identifier

以下 Identities 属性包含一个本地帐户标识、一个电子邮件地址和一个社交标识,它们均可用作登录名。The following Identities property, with a local account identity with a sign-in name, an email address as sign-in, and with a social identity.

"identities": [
    {
      "signInType": "userName",
      "issuer": "contoso.partner.onmschina.cn",
      "issuerAssignedId": "johnsmith"
    },
    {
      "signInType": "emailAddress",
      "issuer": "contoso.partner.onmschina.cn",
      "issuerAssignedId": "jsmith@yahoo.com"
    }
  ]

对于联合标识,根据标识提供者,issuerAssignedId 是每个应用程序的给定用户或开发帐户的唯一值。For federated identities, depending on the identity provider, the issuerAssignedId is a unique value for a given user per application or development account. 使用社交网络提供商以前分配的相同应用程序 ID 或者同一开发帐户中的另一应用程序配置 Azure AD B2C 策略。Configure the Azure AD B2C policy with the same application ID that was previously assigned by the social provider or another application within the same development account.

密码配置文件属性Password profile property

对于本地标识,passwordProfile 属性是必需的,其中包含用户的密码。For a local identity, the passwordProfile property is required, and contains the user's password. forceChangePasswordNextSignIn 属性必须设置为 falseThe forceChangePasswordNextSignIn property must set to false.

对于联合(社交)标识,passwordProfile 属性不是必需的。For a federated (social) identity, the passwordProfile property is not required.

"passwordProfile" : {
    "password": "password-value",
    "forceChangePasswordNextSignIn": false
  }

密码策略属性Password policy property

Azure AD B2C 密码策略(对于本地帐户)基于 Azure Active Directory 强密码强度策略。The Azure AD B2C password policy (for local accounts) is based on the Azure Active Directory strong password strength policy. Azure AD B2C 的注册或登录和密码重置策略要求实施此强密码强度,并且不能让密码过期。The Azure AD B2C sign-up or sign-in and password reset policies require this strong password strength, and don't expire passwords.

在用户迁移方案中,如果与 Azure AD B2C 强制实施的强密码强度相比,要迁移的帐户的密码强度更弱,则你可以禁用强密码要求。In user migration scenarios, if the accounts you want to migrate have weaker password strength than the strong password strength enforced by Azure AD B2C, you can disable the strong password requirement. 若要更改默认密码策略,请将 passwordPolicies 属性设置为 DisableStrongPasswordTo change the default password policy, set the passwordPolicies property to DisableStrongPassword. 例如,可按如下所示修改创建用户请求:For example, you can modify the create user request as follows:

"passwordPolicies": "DisablePasswordExpiration, DisableStrongPassword"

扩展属性Extension properties

每个面向客户的应用程序对要收集的信息都有独特的要求。Every customer-facing application has unique requirements for the information to be collected. Azure AD B2C 租户附带了一组存储在属性中的内置信息:名字、姓氏、城市和邮政编码。Your Azure AD B2C tenant comes with a built-in set of information stored in properties, such as Given Name, Surname, City, and Postal Code. 使用 Azure AD B2C 可以扩展存储在每个客户帐户中的属性集。With Azure AD B2C, you can extend the set of properties stored in each customer account. 若要详细了解如何定义自定义属性,请参阅自定义属性(用户流)和“自定义属性(自定义策略)”。For more information on defining custom attributes, see custom attributes (user flows) and custom attributes (custom policies).

Microsoft Graph API 支持使用扩展特性创建和更新用户。Microsoft Graph API supports creating and updating a user with extension attributes. 图形 API 中的扩展属性使用约定 extension_ApplicationObjectID_attributename 来命名。Extension attributes in the Graph API are named by using the convention extension_ApplicationObjectID_attributename. 例如:For example:

"extension_831374b3bd5041bfaa54263ec9e050fc_loyaltyNumber": "212342"

代码示例Code sample

此代码示例是一个 .NET Core 控制台应用程序,它使用 Microsoft Graph SDK 来与 Microsoft Graph API 交互。This code sample is a .NET Core console application that uses the Microsoft Graph SDK to interact with Microsoft Graph API. 其中的代码演示了如何调用 API 来以编程方式管理 Azure AD B2C 租户中的用户。Its code demonstrates how to call the API to programmatically manage users in an Azure AD B2C tenant. 可以下载示例存档 (*.zip),在 GitHub 中浏览存储库,或克隆存储库: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. Visual StudioVisual Studio Code 中打开项目。Open the project in Visual Studio or Visual Studio Code.

  2. 打开 src/appsettings.jsonOpen src/appsettings.json.

  3. appSettings 节中,将 your-b2c-tenant 替换为租户的名称,将 Application (client) IDClient secret 替换为管理应用程序注册的值(请参阅本文中的注册管理应用程序部分)。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 (see the Register a management application section of this article).

  4. 在存储库的本地克隆中打开控制台窗口,切换到 src 目录,然后生成项目: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. 使用 dotnet 命令运行应用程序:Run the application with the dotnet command:

    dotnet bin/Debug/netcoreapp3.0/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.

代码探讨Code discussion

示例代码使用 Microsoft Graph SDK,旨在简化可访问 Microsoft Graph 的优质、高效且可复原的应用程序的生成。The sample code uses the Microsoft Graph SDK, which is designed to simplify building high-quality, efficient, and resilient applications that access Microsoft Graph.

对 Microsoft Graph API 发出的任何请求都需要使用访问令牌进行身份验证。Any request to the Microsoft Graph API requires an access token for authentication. 该解决方案利用 Microsoft.Graph.Auth NuGet 包,该包提供 Microsoft 身份验证库 (MSAL) 的基于身份验证方案的包装器,以便与 Microsoft Graph SDK 配合使用。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.

Program.cs 文件中的 RunAsync 方法:The RunAsync method in the Program.cs file:

  1. appsettings.json 文件读取应用程序设置Reads application settings from the appsettings.json file

  2. 使用 OAuth 2.0 客户端凭据授予流初始化身份验证提供程序。Initializes the auth provider using OAuth 2.0 client credentials grant flow. 应用可以使用客户端凭据授予流获取用于调用 Microsoft Graph API 的访问令牌。With the client credentials grant flow, the app is able to get an access token to call the Microsoft Graph API.

  3. 使用身份验证提供程序设置 Microsoft Graph 服务客户端: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);
    

然后,在 UserService.cs 中使用初始化的 GraphServiceClient 来执行用户管理操作。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));
    }
}

使用 Microsoft Graph SDK 发出 API 调用中介绍了如何在 Microsoft Graph 中读取和写入信息,使用 $select 控制返回的属性,提供自定义查询参数,以及使用 $filter$orderBy 查询参数。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.

后续步骤Next steps

有关 Azure AD B2C 资源支持的 Microsoft Graph API 操作的完整索引,请参阅可用于 Azure AD B2C 的 Microsoft Graph 操作For a full index of the Microsoft Graph API operations supported for Azure AD B2C resources, see Microsoft Graph operations available for Azure AD B2C.