使用 Application Insights 在 Azure AD B2C 中跟踪用户行为Track user behavior in Azure AD B2C by using Application Insights

开始之前,请使用上面的选择器选择要配置的策略类型。Before you begin, use the selector above to choose the type of policy you’re configuring. Azure AD B2C 提供了两种定义用户如何与应用程序交互的方法:通过预定义的用户流,或者通过完全可配置的自定义策略Azure AD B2C offers two methods of defining how users interact with your applications: though predefined user flows, or through fully configurable custom policies. 对于每种方法,本文中所需的步骤都不同。The steps required in this article are different for each method.

此功能仅适用于自定义策略。This feature is available for custom policies only. 对于设置步骤,请选择上面的“自定义策略”。For setup steps, choose Custom policy above.

在 Azure Active Directory B2C (Azure AD B2C) 中,可以使用提供给 Azure AD B2C 的检测密钥将事件数据直接发送到 Application InsightsIn Azure Active Directory B2C (Azure AD B2C), you can send event data directly to Application Insights by using the instrumentation key provided to Azure AD B2C. 使用 Application Insights 技术配置文件,你可以获取用户旅程的详细自定义事件日志,以便执行以下操作:With an Application Insights technical profile, you can get detailed and customized event logs for your user journeys to:

  • 洞察用户行为。Gain insights on user behavior.
  • 排查自己在开发或生产过程中的策略问题。Troubleshoot your own policies in development or in production.
  • 衡量性能。Measure performance.
  • 通过 Application Insights 创建通知。Create notifications from Application Insights.

概述Overview

若要启用自定义事件日志,请添加 Application Insights 技术配置文件。To enable custom event logs, add an Application Insights technical profile. 在技术配置文件中,定义要记录的 Application Insights 检测密钥、事件名称和声明。In the technical profile, you define the Application Insights instrumentation key, the event name, and the claims to record. 若要发布事件,请将技术配置文件作为业务流程步骤添加到用户旅程To post an event, add the technical profile as an orchestration step in a user journey.

使用 Application Insights 时,请注意以下内容:When you use Application Insights, consider the following:

  • Application Insights 中出现新日志之前会有一小段延迟(通常不到 5 分钟)。There's a short delay, typically less than five minutes, before new logs are available in Application Insights.
  • Azure AD B2C 允许选择要记录的声明。Azure AD B2C allows you to choose which claims to record. 不要包括具有个人数据的声明。Don't include claims with personal data.
  • 若要记录用户会话,可以使用相关 ID 来统一事件。To record a user session, you can use a correlation ID to unify events.
  • 直接从用户旅程子旅程调用 Application Insights 技术配置文件。Call the Application Insights technical profile directly from a user journey or a sub journey. 请勿将 Application Insights 技术配置文件用作验证技术配置文件Don't use an Application Insights technical profile as a validation technical profile.

先决条件Prerequisites

创建 Application Insights 资源Create an Application Insights resource

将 Azure AD B2C 与 Application Insights 配合使用时,只需创建资源并获取检测密钥。When you use Application Insights with Azure AD B2C, all you need to do is create a resource and get the instrumentation key. 有关信息,请参阅创建 Application Insights 资源For information, see Create an Application Insights resource.

  1. 登录到 Azure 门户Sign in to the Azure portal.
  2. 请确保使用的是具有 Azure 订阅的目录。Make sure you're using the directory that has your Azure subscription. 选择顶部菜单中的“目录 + 订阅”筛选器,然后选择包含 Azure 订阅的目录。Select the Directory + subscription filter in the top menu and choose the directory that contains your Azure subscription. 此租户不是 Azure AD B2C 租户。This tenant isn't your Azure AD B2C tenant.
  3. 选择 Azure 门户左上角的“创建资源”,然后搜索并选择“Application Insights” 。Choose Create a resource in the upper-left corner of the Azure portal, and then search for and select Application Insights.
  4. 选择“创建” 。Select Create.
  5. 对于“名称”,输入资源的名称。For Name, enter a name for the resource.
  6. 在“应用程序类型”下,选择“ASP.NET web 应用程序” 。For Application Type, select ASP.NET web application.
  7. 对于资源组,选择现有的组,或输入新组的名称。For Resource Group, select an existing group or enter a name for a new group.
  8. 选择“创建” 。Select Create.
  9. 打开新的 Application Insights 资源,展开“Essentials”并复制检测密钥。Open the new Application Insights resource, expand Essentials, and copy the instrumentation key.

屏幕截图显示 Application Insights“概述”选项卡上的检测密钥。

定义声明Define claims

声明可在 Azure AD B2C 策略执行过程中提供数据的临时存储。A claim provides temporary storage of data during an Azure AD B2C policy execution. ClaimsSchema 元素中宣布声明。You declare your claims in the ClaimsSchema element.

  1. 打开策略的扩展文件。Open the extensions file of your policy. 文件看起来可能类似于 SocialAndLocalAccounts/``TrustFrameworkExtensions.xmlThe file might look similar to SocialAndLocalAccounts/TrustFrameworkExtensions.xml.

  2. 搜索 BuildingBlocks 元素。Search for the BuildingBlocks element. 如果没看到该元素就添加它。If you don't see the element, add it.

  3. 查找 ClaimsSchema 元素。Find the ClaimsSchema element. 如果没看到该元素就添加它。If you don't see the element, add it.

  4. 将以下声明添加到 ClaimsSchema 元素:Add the following claims to the ClaimsSchema element:

    <ClaimType Id="EventType">
      <DisplayName>Event type</DisplayName>
      <DataType>string</DataType>
    </ClaimType>
    <ClaimType Id="EventTimestamp">
      <DisplayName>Event timestamp</DisplayName>
      <DataType>string</DataType>
    </ClaimType>
    <ClaimType Id="PolicyId">
      <DisplayName>Policy Id</DisplayName>
      <DataType>string</DataType>
    </ClaimType>
    <ClaimType Id="Culture">
      <DisplayName>Culture ID</DisplayName>
      <DataType>string</DataType>
    </ClaimType>
    <ClaimType Id="CorrelationId">
      <DisplayName>Correlation Id</DisplayName>
      <DataType>string</DataType>
    </ClaimType>
    <ClaimType Id="federatedUser">
      <DisplayName>Federated user</DisplayName>
      <DataType>boolean</DataType>
    </ClaimType>
    <ClaimType Id="parsedDomain">
      <DisplayName>Domain name</DisplayName>
      <DataType>string</DataType>
      <UserHelpText>The domain portion of the email address.</UserHelpText>
    </ClaimType>
    <ClaimType Id="userInLocalDirectory">
      <DisplayName>userInLocalDirectory</DisplayName>
      <DataType>boolean</DataType>
    </ClaimType>
    

新增技术配置文件Add new technical profiles

可以将技术配置文件视为自定义策略中的函数。Technical profiles can be considered functions in the custom policy. 这些函数使用技术配置文件包含方法,其中技术配置文件包含其他技术配置文件并更改设置或添加新功能。These functions use the technical profile inclusion approach, where a technical profile includes another technical profile and changes settings or adds new functionality. 下表定义技术配置文件,这些文件用于打开会话和发布事件。The following table defines the technical profiles that are used to open a session and post events.

技术配置文件Technical profile 任务Task
AppInsights-CommonAppInsights-Common 具有典型配置的通用技术配置文件。The common technical profile with typical configuration. 它包括 Application Insights 检测密钥、要记录的声明的集合以及开发人员模式。It includes the Application Insights instrumentation key, a collection of claims to record, and developer mode. 其他技术配置文件包括通用技术配置文件,并添加事件名称等更多声明。The other technical profiles include the common technical profile and add more claims, such as the event name.
AppInsights-SignInRequestAppInsights-SignInRequest 在收到登录请求后记录包含一组声明的 SignInRequest 事件。Records a SignInRequest event with a set of claims when a sign-in request has been received.
AppInsights-UserSignUpAppInsights-UserSignUp 当用户在注册或登录旅程中触发注册选项时记录 UserSignup 事件。Records a UserSignUp event when the user triggers the sign-up option in a sign-up or sign-in journey.
AppInsights-SignInCompleteAppInsights-SignInComplete 在成功进行身份验证(已将令牌发送到信赖方应用程序)时记录 SignInComplete 事件。Records a SignInComplete event upon successful authentication, when a token has been sent to the relying party application.

打开初学者包中的 TrustFrameworkExtensions.xml 文件。Open the TrustFrameworkExtensions.xml file from the starter pack. 将技术配置文件添加到 ClaimsProvider 元素:Add the technical profiles to the ClaimsProvider element:

<ClaimsProvider>
  <DisplayName>Application Insights</DisplayName>
  <TechnicalProfiles>
    <TechnicalProfile Id="AppInsights-Common">
      <DisplayName>Application Insights</DisplayName>
      <Protocol Name="Proprietary" Handler="Web.TPEngine.Providers.Insights.AzureApplicationInsightsProvider, Web.TPEngine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
      <Metadata>
        <!-- The ApplicationInsights instrumentation key, which you use for logging the events -->
        <Item Key="InstrumentationKey">xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx</Item>
        <Item Key="DeveloperMode">false</Item>
        <Item Key="DisableTelemetry ">false</Item>
      </Metadata>
      <InputClaims>
        <!-- Properties of an event are added through the syntax {property:NAME}, where NAME is the property being added to the event. DefaultValue can be either a static value or a value that's resolved by one of the supported DefaultClaimResolvers. -->
        <InputClaim ClaimTypeReferenceId="EventTimestamp" PartnerClaimType="{property:EventTimestamp}" DefaultValue="{Context:DateTimeInUtc}" />
        <InputClaim ClaimTypeReferenceId="tenantId" PartnerClaimType="{property:TenantId}" DefaultValue="{Policy:TrustFrameworkTenantId}" />
        <InputClaim ClaimTypeReferenceId="PolicyId" PartnerClaimType="{property:Policy}" DefaultValue="{Policy:PolicyId}" />
        <InputClaim ClaimTypeReferenceId="CorrelationId" PartnerClaimType="{property:CorrelationId}" DefaultValue="{Context:CorrelationId}" />
        <InputClaim ClaimTypeReferenceId="Culture" PartnerClaimType="{property:Culture}" DefaultValue="{Culture:RFC5646}" />
      </InputClaims>
    </TechnicalProfile>

    <TechnicalProfile Id="AppInsights-SignInRequest">
      <InputClaims>
        <!-- An input claim with a PartnerClaimType="eventName" is required. This is used by the AzureApplicationInsightsProvider to create an event with the specified value. -->
        <InputClaim ClaimTypeReferenceId="EventType" PartnerClaimType="eventName" DefaultValue="SignInRequest" />
      </InputClaims>
      <IncludeTechnicalProfile ReferenceId="AppInsights-Common" />
    </TechnicalProfile>

    <TechnicalProfile Id="AppInsights-UserSignUp">
      <InputClaims>
        <InputClaim ClaimTypeReferenceId="EventType" PartnerClaimType="eventName" DefaultValue="UserSignUp" />
      </InputClaims>
      <IncludeTechnicalProfile ReferenceId="AppInsights-Common" />
    </TechnicalProfile>

    <TechnicalProfile Id="AppInsights-SignInComplete">
      <InputClaims>
        <InputClaim ClaimTypeReferenceId="EventType" PartnerClaimType="eventName" DefaultValue="SignInComplete" />
        <InputClaim ClaimTypeReferenceId="federatedUser" PartnerClaimType="{property:FederatedUser}" DefaultValue="false" />
        <InputClaim ClaimTypeReferenceId="parsedDomain" PartnerClaimType="{property:FederationPartner}" DefaultValue="Not Applicable" />
        <InputClaim ClaimTypeReferenceId="identityProvider" PartnerClaimType="{property:IDP}" DefaultValue="Local" />
      </InputClaims>
      <IncludeTechnicalProfile ReferenceId="AppInsights-Common" />
    </TechnicalProfile>
  </TechnicalProfiles>
</ClaimsProvider>

重要

AppInsights-Common 技术配置文件中的检测密钥更改为 Application Insights 资源提供的 GUID。Change the instrumentation key in the AppInsights-Common technical profile to the GUID that your Application Insights resource provides.

添加技术配置文件,作为业务流程步骤Add the technical profiles as orchestration steps

添加引用技术配置文件的新的业务流程步骤。Add new orchestration steps that refer to the technical profiles.

重要

添加新的业务流程步骤以后,请按顺序对这些步骤重新编号,不要跳过从 1 到 N 的任何整数。After you add the new orchestration steps, renumber the steps sequentially without skipping any integers from 1 to N.

  1. 调用 AppInsights-SignInRequest(作为第二个业务流程步骤)。Call AppInsights-SignInRequest as the second orchestration step. 此步骤跟踪是否已收到登录或注册请求。This step tracks that a sign-up or sign-in request has been received.

    <!-- Track that we have received a sign in request -->
    <OrchestrationStep Order="2" Type="ClaimsExchange">
      <ClaimsExchanges>
        <ClaimsExchange Id="TrackSignInRequest" TechnicalProfileReferenceId="AppInsights-SignInRequest" />
      </ClaimsExchanges>
    </OrchestrationStep>
    
  2. 在执行 SendClaims 业务流程步骤之前,添加调用 AppInsights-UserSignup 的新步骤。Before the SendClaims orchestration step, add a new step that calls AppInsights-UserSignup. 当用户在注册或登录旅程中选择注册按钮时,会触发此步骤。It's triggered when the user selects the sign-up button in a sign-up or sign-in journey.

    <!-- Handles the user selecting the sign-up link in the local account sign-in page -->
    <OrchestrationStep Order="8" Type="ClaimsExchange">
      <Preconditions>
        <Precondition Type="ClaimsExist" ExecuteActionsIf="false">
          <Value>newUser</Value>
          <Action>SkipThisOrchestrationStep</Action>
        </Precondition>
        <Precondition Type="ClaimEquals" ExecuteActionsIf="true">
          <Value>newUser</Value>
          <Value>false</Value>
          <Action>SkipThisOrchestrationStep</Action>
        </Precondition>
      </Preconditions>
      <ClaimsExchanges>
        <ClaimsExchange Id="TrackUserSignUp" TechnicalProfileReferenceId="AppInsights-UserSignup" />
      </ClaimsExchanges>
    </OrchestrationStep>
    
  3. SendClaims 业务流程步骤后调用 AppInsights-SignInCompleteAfter the SendClaims orchestration step, call AppInsights-SignInComplete. 此步骤演示成功完成的过程。This step shows a successfully completed journey.

    <!-- Track that we have successfully sent a token -->
    <OrchestrationStep Order="10" Type="ClaimsExchange">
      <ClaimsExchanges>
        <ClaimsExchange Id="TrackSignInComplete" TechnicalProfileReferenceId="AppInsights-SignInComplete" />
      </ClaimsExchanges>
    </OrchestrationStep>
    

上传文件,运行策略,并查看事件Upload your file, run the policy, and view events

保存并上传 TrustFrameworkExtensions.xml 文件。Save and upload the TrustFrameworkExtensions.xml file. 然后通过应用程序调用信赖方策略,或者在 Azure 门户中使用“立即运行”。Then call the relying party policy from your application or use Run Now in the Azure portal. 等待事件出现在 Application Insights 中。Wait for your events to be available in Application Insights.

  1. 在 Azure Active Directory 租户中打开 Application Insights 资源。Open the Application Insights resource in your Azure Active Directory tenant.
  2. 选择“使用情况”,然后选择“事件” 。Select Usage, and then select Events.
  3. 将“期间”设置为“过去一小时”,将“截止时间”设置为“3 分钟”。 Set During to Last hour and By to 3 minutes. 可能需要刷新窗口来查看结果。You might need to refresh the window to see the results.

屏幕截图显示 Application Insights 事件统计信息。

收集更多数据Collect more data

为了满足业务需求,可能需要记录更多的声明。To fit your business needs, you might want to record more claims. 若要添加声明,请先定义声明,然后将声明添加到输入声明集合。To add a claim, first define a claim, then add the claim to the input claims collection. 添加到 AppInsights-Common 技术配置文件中的声明将出现在所有事件中。Claims that you add to the AppInsights-Common technical profile appear in all events. 添加到特定技术配置文件中的声明只出现在该事件中。Claims that you add to a specific technical profile appear only in that event. 输入声明元素包含以下属性:The input claim element contains the following attributes:

  • ClaimTypeReferenceId 是对声明类型的引用。ClaimTypeReferenceId is the reference to a claim type.
  • PartnerClaimType 是 Azure Insights 中显示的属性的名称。PartnerClaimType is the name of the property that appears in Azure Insights. 使用语法 {property:NAME},其中 NAME 是要添加到该事件的属性。Use the syntax of {property:NAME}, where NAME is a property being added to the event.
  • DefaultValue 是要记录的预定义值,例如事件名称。DefaultValue is a predefined value to be recorded, such as an event name. 如果用在用户旅程中的声明为空,则使用默认值。If a claim that is used in the user journey is empty, the default value is used. 例如,identityProvider 声明由联合技术配置文件进行设置。For example, the identityProvider claim is set by the federation technical profiles. 如果该声明为空,则表示用户使用本地帐户登录。If the claim is empty, it indicates the user signed in with a local account. 因此默认值设置为“本地”。Thus, the default value is set to Local. 还可以记录具有上下文值(例如应用程序 ID 或用户 IP 地址)的声明解析程序You can also record a claim resolver with a contextual value, such as the application ID or the user IP address.

操作声明Manipulate claims

可以使用输入声明转换在将输入声明发送到 Application Insights 之前对它们进行修改或者生成新的输入声明。You can use input claims transformations to modify the input claims or generate new ones before sending them to Application Insights. 在下面的示例中,技术配置文件包含 CheckIsAdmin 输入声明转换。In the following example, the technical profile includes the CheckIsAdmin input claims transformation.

<TechnicalProfile Id="AppInsights-SignInComplete">
  <InputClaimsTransformations>  
    <InputClaimsTransformation ReferenceId="CheckIsAdmin" />
  </InputClaimsTransformations>
  <InputClaims>
    <InputClaim ClaimTypeReferenceId="isAdmin" PartnerClaimType="{property:IsAdmin}"  />
    ...
  </InputClaims>
  <IncludeTechnicalProfile ReferenceId="AppInsights-Common" />
</TechnicalProfile>

添加事件Add events

若要添加事件,请创建包含 AppInsights-Common 技术配置文件的新技术配置文件。To add an event, create a new technical profile that includes the AppInsights-Common technical profile. 然后将新技术配置文件作为业务流程步骤添加到用户旅程Then add the new technical profile as an orchestration step to the user journey. 使用 Precondition 元素在准备就绪时触发事件。Use the Precondition element to trigger the event when you're ready. 例如,仅当用户通过多重身份验证运行时才报告事件。For example, report the event only when users run through multifactor authentication.

<TechnicalProfile Id="AppInsights-MFA-Completed">
  <InputClaims>
     <InputClaim ClaimTypeReferenceId="EventType" PartnerClaimType="eventName" DefaultValue="MFA-Completed" />
  </InputClaims>
  <IncludeTechnicalProfile ReferenceId="AppInsights-Common" />
</TechnicalProfile>

重要

向用户旅程添加事件时,请记得按顺序对业务流程步骤进行重新编号。When you add an event to the user journey, remember to renumber the orchestration steps sequentially.

<OrchestrationStep Order="8" Type="ClaimsExchange">
  <Precondition Type="ClaimsExist" ExecuteActionsIf="true">
    <Value>isActiveMFASession</Value>
    <Action>SkipThisOrchestrationStep</Action>
    </Precondition>
  </Preconditions>
  <ClaimsExchanges>
    <ClaimsExchange Id="TrackUserMfaCompleted" TechnicalProfileReferenceId="AppInsights-MFA-Completed" />
  </ClaimsExchanges>
</OrchestrationStep>

启用开发人员模式Enable developer mode

使用 Application Insights 定义事件时,可以指示是否启用开发人员模式。When you use Application Insights to define events, you can indicate whether developer mode is enabled. 开发人员模式控制如何缓冲事件。Developer mode controls how events are buffered. 在事件量最少的开发环境中,启用开发人员模式会导致系统立即将事件发送到 Application Insights。In a development environment with minimal event volume, enabling developer mode results in events being sent immediately to Application Insights. 默认值为 falseThe default value is false. 请勿在生产环境中启用开发人员模式。Don't enable developer mode in production environments.

若要启用开发人员模式,请在 AppInsights-Common 技术配置文件中将 DeveloperMode 元数据改为 trueTo enable developer mode, change the DeveloperMode metadata to true in the AppInsights-Common technical profile:

<TechnicalProfile Id="AppInsights-Common">
  <Metadata>
    ...
    <Item Key="DeveloperMode">true</Item>
  </Metadata>
</TechnicalProfile>

禁用遥测Disable telemetry

若要禁用 Application Insights 日志,请在 AppInsights-Common 技术配置文件中将 DisableTelemetry 元数据改为 trueTo disable Application Insights logs, change the DisableTelemetry metadata to true in the AppInsights-Common technical profile:

<TechnicalProfile Id="AppInsights-Common">
  <Metadata>
    ...
    <Item Key="DisableTelemetry">true</Item>
  </Metadata>
</TechnicalProfile>