在 Azure AD B2C 自定义策略中集成 REST API 声明交换Integrate REST API claims exchanges in your Azure AD B2C custom policy


在 Azure Active Directory B2C 中,custom policies 主要用于解决复杂方案。In Azure Active Directory B2C, custom policies are designed primarily to address complex scenarios. 大多数情况下,建议使用内置的用户流For most scenarios, we recommend that you use built-in user flows.

构成 Azure Active Directory B2C (Azure AD B2C) 的基础的 Identity Experience Framework 可在用户旅程中与 RESTful API 相集成。The Identity Experience Framework, which underlies Azure Active Directory B2C (Azure AD B2C), can integrate with RESTful APIs within a user journey. 本文介绍如何使用 RESTful 技术配置文件创建与 RESTful 服务交互的用户旅程。This article shows how to create a user journey that interacts with a RESTful service using a RESTful technical profile.

使用 Azure AD B2C 可以通过调用 RESTful 服务,将自己的业务逻辑添加到用户旅程中。Using Azure AD B2C, you can add your own business logic to a user journey by calling your own RESTful service. Identity Experience Framework 可以在 RESTful 服务中发送和接收数据,以交换声明。The Identity Experience Framework can send and receive data from your RESTful service to exchange claims. 例如,可以:For example, you can:

  • 验证用户输入数据。Validate user input data. 例如,可以验证用户提供的电子邮件地址是否在客户数据库中存在,如果不存在,则显示错误消息。For example, you can verify that the email address provided by the user exists in your customer's database, and if not, present an error.
  • 处理声明。Process claims. 如果用户使用全小写或全大写字母输入了其名字,REST API 可以设置该名字的格式,只将第一个字母,然后将此名字返回到 Azure AD B2C。If a user enters their first name in all lowercase or all uppercase letters, your REST API can format the name with only the first letter capitalized and return it to Azure AD B2C.
  • 通过进一步与企业业务线应用程序集成来丰富用户数据。Enrich user data by further integrating with corporate line-of-business applications. RESTful 服务可以接收用户的电子邮件地址、查询客户的数据库,并向 Azure AD B2C 返回用户的会员号。Your RESTful service can receive the user's email address, query the customer's database, and return the user's loyalty number to Azure AD B2C. 返回声明可以存储在用户 Azure AD 帐户中、在后续的业务流程步骤中进行评估,或包含在访问令牌中。Then return claims can be stored in the user's Azure AD account, evaluated in the next orchestration steps, or included in the access token.
  • 运行自定义业务逻辑。Run custom business logic. 可以发送推送通知、更新企业数据库、运行用户迁移过程、管理权限、审核数据库,以及执行任何其他工作流。You can send push notifications, update corporate databases, run a user migration process, manage permissions, audit databases, and perform any other workflows.

RESTful 服务声明交换示意图


如果 RESTful 服务对 Azure AD B2C 的响应速度缓慢或没有响应,则超时为 30 秒,重试计数为 2 次(这意味着总共有 3 次尝试)。If there is slow or no response from the RESTful service to Azure AD B2C, the timeout is 30 seconds and the retry count is 2 times (meaning there are 3 tries in total). 超时和重试计数设置当前不可配置。The timeout and retry count settings are not currently configurable.

调用 RESTful 服务Calling a RESTful service

交互包括 REST API 声明与 Azure AD B2C 之间的声明信息交换。The interaction includes a claims exchange of information between the REST API claims and Azure AD B2C. 可通过以下方式来设计与 RESTful 服务的集成:You can design the integration with the RESTful services in the following ways:

  • 验证技术配置文件。Validation technical profile. 对 RESTful 服务的调用在指定的自我断言技术配置文件验证技术配置文件中发生,或者在显示控制验证显示控制中发生。The call to the RESTful service happens within a validation technical profile of the specified self-asserted technical profile, or a verification display control of a display control. 在用户旅程推进之前,验证技术配置文件会验证用户提供的数据。The validation technical profile validates the user-provided data before the user journey moves forward. 使用验证技术配置文件,可以:With the validation technical profile, you can:

    • 将声明发送到 REST API。Send claims to your REST API.
    • 验证声明,并引发向用户显示的自定义错误消息。Validate claims, and throw custom error messages that are displayed to the user.
    • 将 REST API 中的声明发回到后续的业务流程步骤。Send back claims from the REST API to subsequent orchestration steps.
  • 声明交换。Claims exchange. 可以通过从用户旅程的业务流程步骤直接调用 REST API 技术配置文件,来配置直接声明交换。A direct claims exchange can be configured by calling a REST API technical profile directly from an orchestration step of a user journey. 此定义仅限于:This definition is limited to:

    • 将声明发送到 REST API。Send claims to your REST API.
    • 验证声明,并引发返回给应用程序的自定义错误消息。Validate claims, and throw custom error messages that are returned to the application.
    • 将 REST API 中的声明发回到后续的业务流程步骤。Send back claims from the REST API to subsequent orchestration steps.

可在自定义策略定义的用户旅程中的任意步骤中添加 REST API 调用。You can add a REST API call at any step in the user journey defined by a custom policy. 例如,可在以下时机调用 REST API:For example, you can call a REST API:

  • 登录期间在 Azure AD B2C 验证凭据之前的那一刻。During sign-in, just before Azure AD B2C validates the credentials.
  • 登录后立即调用。Immediately after sign-in.
  • Azure AD B2C 在目录中创建新帐户之前。Before Azure AD B2C creates a new account in the directory.
  • Azure AD B2C 在目录中创建新帐户之后。After Azure AD B2C creates a new account in the directory.
  • Azure AD B2C 颁发访问令牌之前。Before Azure AD B2C issues an access token.


发送数据Sending data

RESTful 技术配置文件中,InputClaims 元素包含要发送到 RESTful 服务的声明列表。In the RESTful technical profile, the InputClaims element contains a list of claims to send to your RESTful service. 可将声明的名称映射到 RESTful 服务中定义的名称,设置默认值,然后使用声明解析程序You can map the name of your claim to the name defined in the RESTful service, set a default value, and use claims resolvers.

可以使用 SendClaimsIn 特性来配置如何将输入声明发送到 RESTful 声明提供程序。You can configure how the input claims are sent to the RESTful claims provider by using the SendClaimsIn attribute. 可能的值包括:The possible values are:

  • Body,以 JSON 格式在 HTTP POST 请求正文中发送。Body, sent in the HTTP POST request body in JSON format.
  • Form,以“&”符号分隔的键值格式在 HTTP POST 请求正文中发送。Form, sent in the HTTP POST request body in an ampersand '&' separated key value format.
  • Header,在 HTTP GET 请求标头中发送。Header, sent in the HTTP GET request header.
  • QueryString,在 HTTP GET 请求查询字符串中发送。QueryString, sent in the HTTP GET request query string.

配置 Body 选项时,REST API 技术配置文件允许将复杂的 JSON 有效负载发送到终结点。When the Body option is configured, the REST API technical profile allows you to send a complex JSON payload to an endpoint. 有关详细信息,请参阅发送 JSON 有效负载For more information, see Send a JSON payload.

接收数据Receiving data

RESTful 技术配置文件OutputClaims 元素包含 REST API 返回的声明列表。The OutputClaims element of the RESTful technical profile contains a list of claims returned by the REST API. 可能需要将策略中定义的声明名称映射到 REST API 中定义的名称。You may need to map the name of the claim defined in your policy to the name defined in the REST API. 只要设置了 DefaultValue 特性,就还可以包含 REST API 标识提供者不会返回的声明。You can also include claims that aren't returned by the REST API identity provider, as long as you set the DefaultValue attribute.

RESTful 声明提供程序分析的输出声明始终预期分析平面 JSON 正文响应,例如:The output claims parsed by the RESTful claims provider always expect to parse a flat JSON Body response, such as:

  "name": "Emily Smith",
  "email": "emily@outlook.com",
  "loyaltyNumber":  1234

输出声明应如下所示:The output claims should look like the following:

  <OutputClaim ClaimTypeReferenceId="displayName" PartnerClaimType="name" />
  <OutputClaim ClaimTypeReferenceId="email" />
  <OutputClaim ClaimTypeReferenceId="loyaltyNumber" />

若要分析嵌套的 JSON 正文响应,请将 ResolveJsonPathsInJsonTokens 的元数据设置为 true。To parse a nested JSON Body response, set the ResolveJsonPathsInJsonTokens metadata to true. 在输出声明中,将 PartnerClaimType 设置为要输出的 JSON 路径元素。In the output claim, set the PartnerClaimType to the JSON path element you want to output.

"contacts": [
    "id": "MAINCONTACT_1",
    "person": {
      "name": "Emily Smith",
      "loyaltyNumber":  1234,
      "emails": [
          "id": "EMAIL_1",
          "type": "WORK",
          "email": "email@domain.com"

输出声明应如下所示:The output claims should look like following:

  <OutputClaim ClaimTypeReferenceId="displayName" PartnerClaimType="contacts[0].person.name" />
  <OutputClaim ClaimTypeReferenceId="email" PartnerClaimType="contacts[0].person.emails[0].email" />
  <OutputClaim ClaimTypeReferenceId="loyaltyNumber" PartnerClaimType="contacts[0].person.loyaltyNumber" />

安全注意事项Security considerations

必须保护 REST API 终结点,以便只有经过身份验证的客户端才能与其通信。You must protect your REST API endpoint so that only authenticated clients can communicate with it. REST API 必须使用 HTTPS 终结点。The REST API must use an HTTPS endpoint. 将 AuthenticationType 元数据设置为以下身份验证方法之一:Set the AuthenticationType metadata to one of the following authentication methods:

  • “客户端证书”使用客户端证书身份验证来限制访问。Client certificate restricts access by using client certificate authentication. 只有具有适当证书的服务才能访问你的 API。Only services that have the appropriate certificates can access your API. 将客户端证书存储在 Azure AD B2C 策略密钥中。You store the client certificate in an Azure AD B2C Policy Key.
  • “持有者”使用客户端 OAuth2 访问令牌来限制访问。Bearer restricts access using a client OAuth2 access token. 访问令牌存储在 Azure AD B2C 策略密钥中。The access token is stored in an Azure AD B2C policy key.

REST API 平台REST API platform

REST API 可以基于任何平台,并可以使用任何编程语言编写,前提是该 API 安全,并可以根据 RESTful 技术配置文件中的指定发送和接收声明。Your REST API can be based on any platform and written in any programing language, as long as it's secure and can send and receive claims as specified in RESTful technical profile.

本地化 REST APILocalize the REST API

在 RESTful 技术配置文件中,你可能想要发送当前会话的语言/区域设置,并在必要时引发本地化的错误消息。In a RESTful technical profile, you may want to send the current session's language/locale, and if necessary, raise a localized error message. 使用声明解析程序可以发送上下文声明,例如用户语言。Using the claims resolver, you can send a contextual claim, such as the user language. 以下示例中的 RESTful 技术配置文件演示了此方案。The following example shows a RESTful technical profile demonstrating this scenario.

<TechnicalProfile Id="REST-ValidateUserData">
  <DisplayName>Validate user input data</DisplayName>
  <Protocol Name="Proprietary" Handler="Web.TPEngine.Providers.RestfulProvider, Web.TPEngine, Version=, Culture=neutral, PublicKeyToken=null" />
    <Item Key="ServiceUrl">https://your-app.chinacloudsites.cn/api/identity</Item>
    <Item Key="AuthenticationType">None</Item>
    <Item Key="SendClaimsIn">Body</Item>
    <Item Key="IncludeClaimResolvingInClaimsHandling">true</Item>
    <InputClaim ClaimTypeReferenceId="userLanguage" DefaultValue="{Culture:LCID}" AlwaysUseDefaultValue="true" />
    <InputClaim ClaimTypeReferenceId="email" PartnerClaimType="emailAddress" />
  <UseTechnicalProfileForSessionManagement ReferenceId="SM-Noop" />

处理错误消息Handling error messages

REST API 可能需要返回错误消息,例如“在 CRM 系统中未找到该用户”。Your REST API may need to return an error message, such as "The user was not found in the CRM system." 如果发生错误,REST API 应返回 HTTP 409 错误消息(冲突响应状态代码)。If an error occurs, the REST API should return an HTTP 409 error message (Conflict response status code). 有关详细信息,请参阅 RESTful 技术配置文件For more information, see the RESTful technical profile.

只能通过从验证技术配置文件调用 REST API 技术配置文件来实现此目的。This can only be achieved by calling a REST API technical profile from a validation technical profile. 这样,用户就可以更正页面上的数据,并在提交页面后再次运行验证。This allows the user to correct the data on the page and run the validation again upon page submission.

需要使用 HTTP 409 响应来阻止处理此业务流程步骤中的任何后续验证技术配置文件。An HTTP 409 response is required to prevent the processing of any subsequent validation technical profiles within this orchestration step.

如果直接从用户旅程引用 REST API 技术配置文件,用户将通过相关的错误消息重定向回到信赖方应用程序。If you reference a REST API technical profile directly from a user journey, the user is redirected back to the relying party application with the relevant error message.

发布 REST APIPublishing your REST API

对 REST API 服务的请求来自 Azure AD B2C 服务器。The request to your REST API service comes from Azure AD B2C servers. 必须将 REST API 服务发布到可公开访问的 HTTPS 终结点。The REST API service must be published to a publicly accessible HTTPS endpoint. REST API 调用将从 Azure 数据中心 IP 地址抵达。The REST API calls will arrive from an Azure data center IP address.

请对 REST API 服务及其底层组件(例如数据库和文件系统)采用高可用性设计。Design your REST API service and its underlying components (such as the database and file system) to be highly available.

后续步骤Next steps

有关使用 RESTful 技术配置文件的示例,请参阅以下文章:See the following articles for examples of using a RESTful technical profile: