分享方式:


使用 Azure Active Directory B2C 自定義原則建立和讀取用戶帳戶

Azure Active Directory B2C (Azure AD B2C) 是以 Microsoft Entra ID 為基礎所建置,因此會使用 Microsoft Entra ID 記憶體來儲存使用者帳戶。 Azure AD B2C 目錄使用者配置檔隨附一組內建屬性,例如指定的名稱、姓氏、城市、郵遞區號,但您可以 透過自己的自定義屬性 擴充使用者配置檔,而不需要外部數據存放區。

您的自定義原則可以使用 Microsoft Entra ID 技術配置檔來儲存、更新或刪除使用者資訊,以連線到 Microsoft Entra ID 記憶體。 在本文中,您將瞭解如何設定一組 Microsoft Entra ID 技術配置檔,以在傳回 JWT 令牌之前儲存和讀取用戶帳戶。

案例概觀

使用 Azure Active Directory B2C 自定義原則 呼叫 REST API 一文中,我們會從使用者收集資訊、驗證數據、稱為 REST API,最後傳回 JWT 而不儲存用戶帳戶。 我們必須儲存使用者資訊,這樣一旦原則完成執行,就不會遺失資訊。 這次,一旦收集使用者資訊並加以驗證,我們需要將使用者資訊儲存在 Azure AD B2C 記憶體中,然後在我們傳回 JWT 令牌之前讀取。 下圖顯示完整的程式。

A flowchart of creating a user account in Azure AD.

必要條件

注意

本文是 Azure Active Directory B2C 操作指南系列中建立和執行您自己的自定義原則的一部分。 建議您從第一篇文章開始此系列。

步驟 1 - 宣告宣告

您必須再宣告宣告兩個宣告: userPrincipalNamepasswordPolicies

  1. 在 檔案中 ContosoCustomPolicy.XML ,找出 ClaimsSchema 元素,並使用下列程式代碼宣告 userPrincipalNamepasswordPolicies 宣告:

        <ClaimType Id="userPrincipalName">
            <DisplayName>UserPrincipalName</DisplayName>
            <DataType>string</DataType>
            <UserHelpText>Your user name as stored in the Azure Active Directory.</UserHelpText>
        </ClaimType>
        <ClaimType Id="passwordPolicies">
            <DisplayName>Password Policies</DisplayName>
            <DataType>string</DataType>
            <UserHelpText>Password policies used by Azure AD to determine password strength, expiry etc.</UserHelpText>
        </ClaimType>
    

    深入了解使用者配置檔屬性一文中的 passwordPolicies 宣告用法userPrincipalName

步驟 2 - 建立 Microsoft Entra ID 技術配置檔

您必須設定兩個 Microsoft Entra ID 技術配置檔。 其中一個技術配置檔會將使用者詳細數據寫入 Microsoft Entra ID 記憶體,另一個配置檔會從 Microsoft Entra ID 記憶體讀取用戶帳戶。

  1. 在檔案中 ContosoCustomPolicy.XML ,找出 ClaimsProviders 元素,並使用下列程式代碼新增宣告提供者。 此宣告提供者會保存 Microsoft Entra ID 技術設定檔:

        <ClaimsProvider>
            <DisplayName>Azure AD Technical Profiles</DisplayName>
            <TechnicalProfiles>
                <!--You'll add you Azure AD Technical Profiles here-->
            </TechnicalProfiles>
        </ClaimsProvider>
    
  2. 在您剛建立的宣告提供者中,使用下列程式代碼新增 Microsoft Entra ID 技術配置檔:

        <TechnicalProfile Id="AAD-UserWrite">
            <DisplayName>Write user information to AAD</DisplayName>
            <Protocol Name="Proprietary" Handler="Web.TPEngine.Providers.AzureActiveDirectoryProvider, Web.TPEngine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
            <Metadata>
                <Item Key="Operation">Write</Item>
                <Item Key="RaiseErrorIfClaimsPrincipalAlreadyExists">true</Item>
                <Item Key="UserMessageIfClaimsPrincipalAlreadyExists">The account already exists. Try to create another account</Item>
            </Metadata>
            <InputClaims>
                <InputClaim ClaimTypeReferenceId="email" PartnerClaimType="signInNames.emailAddress" Required="true" />
            </InputClaims>
            <PersistedClaims>
                <PersistedClaim ClaimTypeReferenceId="email" PartnerClaimType="signInNames.emailAddress" />        
                <PersistedClaim ClaimTypeReferenceId="displayName" />
                <PersistedClaim ClaimTypeReferenceId="givenName" />
                <PersistedClaim ClaimTypeReferenceId="surname" />
                <PersistedClaim ClaimTypeReferenceId="password"/>
                <PersistedClaim ClaimTypeReferenceId="passwordPolicies" DefaultValue="DisablePasswordExpiration,DisableStrongPassword" />
            </PersistedClaims>
            <OutputClaims>
                <OutputClaim ClaimTypeReferenceId="objectId" />
                <OutputClaim ClaimTypeReferenceId="userPrincipalName" />
                <OutputClaim ClaimTypeReferenceId="email" PartnerClaimType="signInNames.emailAddress" />
            </OutputClaims>
        </TechnicalProfile>
    

    我們已新增 Microsoft Entra ID 技術設定檔 AAD-UserWrite。 您必須記下技術設定檔的下列重要部分:

    • 作業:作業會指定要執行的動作,在此案例中為 Write。 深入瞭解 Microsoft Entra ID 技術提供者中的其他作業。

    • 保存的宣告PersistedClaims 元素包含應該儲存至 Microsoft Entra ID 記憶體的所有值。

    • InputClaims:InputClaims 元素包含宣告,用來查閱目錄中的帳戶,或建立新的宣告。 所有 Microsoft Entra ID 技術設定檔的輸入宣告集合中必須只有一個輸入宣告專案。 此技術配置檔會 使用電子郵件 宣告作為用戶帳戶的金鑰標識碼。 深入瞭解 您可以唯一識別用戶帳戶的其他密鑰標識碼。

  3. 在 檔案中ContosoCustomPolicy.XMLAAD-UserWrite,找出技術配置檔,然後使用下列程序代碼,在之後新增技術配置檔:

        <TechnicalProfile Id="AAD-UserRead">
            <DisplayName>Read user from Azure AD storage</DisplayName>
            <Protocol Name="Proprietary" Handler="Web.TPEngine.Providers.AzureActiveDirectoryProvider, Web.TPEngine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
            <Metadata>
                <Item Key="Operation">Read</Item>
                <Item Key="RaiseErrorIfClaimsPrincipalAlreadyExists">false</Item>
                <Item Key="RaiseErrorIfClaimsPrincipalDoesNotExist">false</Item>
            </Metadata>
            <InputClaims>
                <InputClaim ClaimTypeReferenceId="email" PartnerClaimType="signInNames.emailAddress" Required="true" />
            </InputClaims>
            <OutputClaims>
                <OutputClaim ClaimTypeReferenceId="objectId" />
                <OutputClaim ClaimTypeReferenceId="userPrincipalName" />
                <OutputClaim ClaimTypeReferenceId="givenName"/>
                <OutputClaim ClaimTypeReferenceId="surname"/>
                <OutputClaim ClaimTypeReferenceId="displayName"/>
            </OutputClaims>
        </TechnicalProfile>
    

    我們已新增 Microsoft Entra ID 技術設定檔 AAD-UserRead。 我們已設定此技術配置檔來執行讀取作業,並在找到區段中具有 InputClaimemail 的用戶帳戶時傳回 objectIduserPrincipalNamegivenNamesurnamedisplayName 宣告。

步驟 3 - 使用 Microsoft Entra ID 技術配置檔

在使用自我判斷技術配置檔收集使用者詳細數據 UserInformationCollector 之後,我們需要使用 AAD-UserWrite 技術配置檔將用戶帳戶寫入 Microsoft Entra ID 記憶體。 若要這樣做,請使用 AAD-UserWrite 技術配置檔作為自我判斷技術配置檔中的 UserInformationCollector 驗證技術配置檔。

在 檔案中ContosoCustomPolicy.XMLUserInformationCollector,找出技術配置檔,然後將技術配置檔新增AAD-UserWrite為集合中的ValidationTechnicalProfiles驗證技術配置檔。 您必須在 CheckCompanyDomain 驗證技術配置檔之後新增此專案。

我們將使用 AAD-UserRead 使用者旅程圖協調流程步驟中的技術配置檔,先讀取使用者詳細數據,再發出 JWT 令牌。

步驟 4 - 更新 ClaimGenerator 技術配置檔

ClaimGenerator我們使用技術配置檔來執行三個宣告轉換:GenerateRandomObjectIdTransformation、CreateDisplayNameTransformationCreateMessageTransformation

  1. 在 檔案中ContosoCustomPolicy.XMLClaimGenerator,找出技術配置檔,並將它取代為下列程序代碼:

        <TechnicalProfile Id="UserInputMessageClaimGenerator">
            <DisplayName>User Message Claim Generator Technical Profile</DisplayName>
            <Protocol Name="Proprietary"
                Handler="Web.TPEngine.Providers.ClaimsTransformationProtocolProvider, Web.TPEngine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
            <OutputClaims>
                <OutputClaim ClaimTypeReferenceId="message" />
            </OutputClaims>
            <OutputClaimsTransformations>
                <OutputClaimsTransformation ReferenceId="CreateMessageTransformation" />
            </OutputClaimsTransformations>
        </TechnicalProfile>
    
        <TechnicalProfile Id="UserInputDisplayNameGenerator">
            <DisplayName>Display Name Claim Generator Technical Profile</DisplayName>
            <Protocol Name="Proprietary"
                Handler="Web.TPEngine.Providers.ClaimsTransformationProtocolProvider, Web.TPEngine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
            <OutputClaims>
                <OutputClaim ClaimTypeReferenceId="displayName" />
            </OutputClaims>
            <OutputClaimsTransformations>
                <OutputClaimsTransformation ReferenceId="CreateDisplayNameTransformation" />
            </OutputClaimsTransformations>
        </TechnicalProfile>
    

    我們已將技術配置檔分成兩個不同的技術配置檔。 UserInputMessageClaimGenerator 技術配置檔會產生在 JWT 令牌中以宣告方式傳送的訊息。 UserInputDisplayNameGenerator 技術配置檔會產生displayName宣告。 在 displayName 技術配置檔將用戶記錄寫入 Microsoft Entra ID 記憶體之前 AAD-UserWrite ,必須先提供宣告值。 在新的程序代碼中,我們會移除 GenerateRandomObjectIdTransformation ,因為 objectId 建立帳戶之後由 Microsoft Entra ID 建立並傳回,因此我們不需要在原則內自行產生它。

  2. 在 檔案中 ContosoCustomPolicy.XML ,找出 UserInformationCollector 自我判斷技術配置檔,然後將技術配置檔新增 UserInputDisplayNameGenerator 為驗證技術配置檔。 執行此動作之後, UserInformationCollector 技術配置檔的 ValidationTechnicalProfiles 集合看起來應該類似下列程式代碼:

        <!--<TechnicalProfile Id="UserInformationCollector">-->
            <ValidationTechnicalProfiles>
                <ValidationTechnicalProfile ReferenceId="CheckCompanyDomain">
                    <Preconditions>
                        <Precondition Type="ClaimEquals" ExecuteActionsIf="false">
                            <Value>accountType</Value>
                            <Value>work</Value>
                            <Action>SkipThisValidationTechnicalProfile</Action>
                        </Precondition>
                    </Preconditions>
                </ValidationTechnicalProfile>                        
                <ValidationTechnicalProfile ReferenceId="DisplayNameClaimGenerator"/>
                <ValidationTechnicalProfile ReferenceId="AAD-UserWrite"/>
            </ValidationTechnicalProfiles>
        <!--</TechnicalProfile>-->
    

    在技術配置檔將用戶記錄寫入 Microsoft Entra ID 記憶體之前AAD-UserWrite,您必須先新增驗證技術配置檔AAD-UserWrite,因為displayName宣告值必須可用。

步驟 5 - 更新使用者旅程圖協調流程步驟

找出您的 HelloWorldJourney 使用者旅程圖,並以下列程式代碼取代所有協調流程步驟:

    <!--<OrchestrationSteps>-->
        <OrchestrationStep Order="1" Type="ClaimsExchange">
            <ClaimsExchanges>
                <ClaimsExchange Id="AccountTypeInputCollectorClaimsExchange" TechnicalProfileReferenceId="AccountTypeInputCollector"/>
            </ClaimsExchanges>
        </OrchestrationStep>
        <OrchestrationStep Order="2" Type="ClaimsExchange">
            <ClaimsExchanges>
                <ClaimsExchange Id="GetAccessCodeClaimsExchange" TechnicalProfileReferenceId="AccessCodeInputCollector" />
            </ClaimsExchanges>
            </OrchestrationStep>
        <OrchestrationStep Order="3" Type="ClaimsExchange">
            <ClaimsExchanges>
                <ClaimsExchange Id="GetUserInformationClaimsExchange" TechnicalProfileReferenceId="UserInformationCollector"/>
            </ClaimsExchanges>
        </OrchestrationStep>
        <OrchestrationStep Order="4" Type="ClaimsExchange">
            <ClaimsExchanges>
                <ClaimsExchange Id="AADUserReaderExchange" TechnicalProfileReferenceId="AAD-UserRead"/>
            </ClaimsExchanges>
        </OrchestrationStep>
        <OrchestrationStep Order="5" Type="ClaimsExchange">
            <ClaimsExchanges>
                <ClaimsExchange Id="GetMessageClaimsExchange" TechnicalProfileReferenceId="UserInputMessageClaimGenerator"/>
            </ClaimsExchanges>
        </OrchestrationStep>
        <OrchestrationStep Order="6" Type="SendClaims" CpimIssuerTechnicalProfileReferenceId="JwtIssuer"/>
    <!--</OrchestrationSteps>-->

在協調流程步驟 4AAD-UserRead ,我們會執行技術配置檔,以從建立的使用者帳戶讀取使用者詳細數據(要包含在 JWT 令牌中)。

由於我們不會將宣告儲存 message 在協調流程步驟 5中,因此我們會執行 UserInputMessageClaimGenerator 來產生 message 宣告以包含在 JWT 令牌上。

步驟 6 - 上傳原則

請遵循上傳自定義原則檔案中的步驟來上傳您的原則檔案。 如果您要上傳與入口網站中已有相同名稱的檔案,請確定您已選取 [覆寫自定義原則] ,如果檔案已經存在

步驟 7 - 測試原則

請遵循測試自定義原則中的步驟來測試您的自定義原則。

原則完成執行之後,您會收到標識符令牌,請檢查是否已建立用戶記錄:

  1. 使用全域 管理員 istrator 或 Privileged Role 管理員 istrator 許可權登入 Azure 入口網站。

  2. 如果您有多個租使用者的存取權,請選取頂端功能表中的 [設定] 圖示,以從 [目錄 + 訂用帳戶] 功能表切換至您的 Azure AD B2C 租使用者。

  3. 在 [Azure 服務] 底下,選取 [Azure AD B2C]。 或使用搜尋方塊來尋找並選取 [Azure AD B2C]。

  4. 管理下方,選取使用者

  5. 找出您剛才建立的用戶帳戶,然後加以選取。 帳戶配置檔看起來與下列螢幕快照類似:

    A screenshot of creating a user account in Azure AD.

在我們的 AAD-UserWrite Microsoft Entra ID 技術配置檔中,我們會指定如果使用者已經存在,我們會引發錯誤訊息。

使用相同的 電子郵件位址再次測試您的自定義原則。 您應該會看到類似以下螢幕快照的錯誤訊息,而不是執行至完成以發出標識元令牌的原則。

A screenshot of error as account already exists.

注意

密碼宣告值是一個非常重要的資訊片段,因此請非常小心您在自定義原則中處理它的方式。 基於類似的原因,Azure AD B2C 會將密碼宣告值視為特殊值。 當您在自我判斷技術配置檔中收集密碼宣告值時,該值只能在相同的技術配置檔或相同自我判斷技術配置檔所參考的驗證技術配置檔內使用。 一旦執行該自我判斷技術配置檔完成,並移至另一個技術配置檔,此值就會遺失。

確認使用者電子郵件位址

建議您先確認使用者的電子郵件,再使用它來建立用戶帳戶。 當您確認電子郵件位址時,請確定帳戶是由真實使用者所建立。 您也可以協助使用者確定他們使用正確的電子郵件位址來建立帳戶。

Azure AD B2C 的自定義原則可讓您使用 驗證顯示控件來驗證電子郵件位址。 您會將驗證碼傳送至電子郵件。 傳送程式代碼之後,使用者會讀取訊息、將驗證碼輸入顯示控件所提供的控件,然後選取 [ 驗證碼 ] 按鈕。

顯示控件是使用者介面元素,具有特殊功能,並與 Azure Active Directory B2C(Azure AD B2C) 後端服務互動。 它可讓使用者在後端叫用驗證技術配置檔的頁面上執行動作。 顯示控件會顯示在頁面上,並由自我判斷技術配置文件參考。

若要使用顯示控制項新增電子郵件驗證,請使用下列步驟:

宣告宣告

您必須宣告要用來保存驗證碼的宣告。

若要宣告宣告,請在 檔案中 ContosoCustomPolicy.XML 找出 ClaimsSchema 元素,並使用下列程式代碼宣告 verificationCode 宣告:

    <!--<ClaimsSchema>-->
        ...
        <ClaimType Id="verificationCode">
            <DisplayName>Verification Code</DisplayName>
            <DataType>string</DataType>
            <UserHelpText>Enter your verification code</UserHelpText>
            <UserInputType>TextBox</UserInputType>
        </ClaimType>
    <!--</ClaimsSchema>-->

設定傳送和驗證程式代碼技術配置檔

Azure AD B2C 使用 Microsoft Entra ID SSPR 技術配置檔 來驗證電子郵件位址。 此技術配置檔可以產生程式碼並傳送至電子郵件位址,或根據您設定的方式驗證程序代碼。

在 檔案中 ContosoCustomPolicy.XML ,找出 元素, ClaimsProviders 並使用下列程式代碼來新增宣告提供者:

    <ClaimsProvider>
        <DisplayName>Azure AD self-service password reset (SSPR)</DisplayName>
        <TechnicalProfiles>
            <TechnicalProfile Id="AadSspr-SendCode">
            <DisplayName>Send Code</DisplayName>
            <Protocol Name="Proprietary" Handler="Web.TPEngine.Providers.AadSsprProtocolProvider, Web.TPEngine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
            <Metadata>
                <Item Key="Operation">SendCode</Item>
            </Metadata>
            <InputClaims>
                <InputClaim ClaimTypeReferenceId="email" PartnerClaimType="emailAddress" />
            </InputClaims>
            </TechnicalProfile>
            <TechnicalProfile Id="AadSspr-VerifyCode">
            <DisplayName>Verify Code</DisplayName>
            <Protocol Name="Proprietary" Handler="Web.TPEngine.Providers.AadSsprProtocolProvider, Web.TPEngine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
            <Metadata>
                <Item Key="Operation">VerifyCode</Item>
            </Metadata>
            <InputClaims>
                <InputClaim ClaimTypeReferenceId="verificationCode" />
                <InputClaim ClaimTypeReferenceId="email" PartnerClaimType="emailAddress" />
            </InputClaims>
            </TechnicalProfile>
        </TechnicalProfiles>
    </ClaimsProvider>

我們已設定兩個技術設定檔 AadSspr-SendCodeAadSspr-VerifyCodeAadSspr-SendCode 會產生程式碼,並將程式碼傳送至 區段中指定的 InputClaims 電子郵件地址,並 AadSspr-VerifyCode 驗證程式代碼。 您可以指定要在技術設定檔中繼資料中執行的動作。

設定顯示控制項

您必須設定電子郵件驗證顯示控制項,才能驗證使用者電子郵件。 您設定的電子郵件驗證顯示控制項將會取代您用來從使用者收集電子郵件的電子郵件顯示宣告。

若要設定顯示控制項,請使用下列步驟:

  1. 在 檔案中 ContosoCustomPolicy.XMLBuildingBlocks ,找出 區段,然後使用下列程式碼,將顯示控制項新增為子專案:

        <!--<BuildingBlocks>-->
            ....
            <DisplayControls>
                <DisplayControl Id="emailVerificationControl" UserInterfaceControlType="VerificationControl">
                  <DisplayClaims>
                    <DisplayClaim ClaimTypeReferenceId="email" Required="true" />
                    <DisplayClaim ClaimTypeReferenceId="verificationCode" ControlClaimType="VerificationCode" Required="true" />
                  </DisplayClaims>
                  <OutputClaims></OutputClaims>
                  <Actions>
                    <Action Id="SendCode">
                      <ValidationClaimsExchange>
                        <ValidationClaimsExchangeTechnicalProfile TechnicalProfileReferenceId="AadSspr-SendCode" />
                      </ValidationClaimsExchange>
                    </Action>
                    <Action Id="VerifyCode">
                      <ValidationClaimsExchange>
                        <ValidationClaimsExchangeTechnicalProfile TechnicalProfileReferenceId="AadSspr-VerifyCode" />
                      </ValidationClaimsExchange>
                    </Action>
                  </Actions>
                </DisplayControl>
            </DisplayControls> 
        <!--</BuildingBlocks>-->
    

    我們已宣告顯示控制項 emailVerificationControl 。 記下下列重要部分:

    • DisplayClaims - 就像在自我判斷技術設定檔中一樣,本節會指定要從顯示控制項內的使用者收集的宣告集合。

    • 動作 - 指定要由顯示控制項執行的動作順序。 每個動作都會參考負責執行動作的技術設定檔。 例如, SendCode 會參考 AadSspr-SendCode 技術設定檔,其會產生程式碼並將其傳送至電子郵件地址。

  2. 在 檔案中 ContosoCustomPolicy.XML ,找出 UserInformationCollector 自我判斷技術設定檔,並取代 電子郵件 顯示宣告以顯示 emailVerificationControl 控制項:

    從:

        <DisplayClaim ClaimTypeReferenceId="email" Required="true"/>
    

    變更為:

        <DisplayClaim DisplayControlReferenceId="emailVerificationControl" />
    
  3. 使用步驟 6 步驟 7 中的 程式來上傳原則檔案,並加以測試。 這次,您必須在建立使用者帳戶之前驗證電子郵件地址。

使用 Microsoft Entra ID 技術設定檔更新使用者帳戶

您可以設定 Microsoft Entra ID 技術設定檔來更新使用者帳戶,而不是嘗試建立新的帳戶。 若要這樣做,請使用下列程式碼,將 Microsoft Entra ID 技術設定檔設定為在集合中 Metadata 不存在指定的使用者帳戶時擲回錯誤。 作業 必須設定為 [寫入 ]:

    <Item Key="Operation">Write</Item>
    <Item Key="RaiseErrorIfClaimsPrincipalDoesNotExist">true</Item>

使用自訂屬性

在本文中,您已瞭解如何使用 內建使用者設定檔屬性 來儲存使用者詳細資料。 不過,您通常需要建立自己的自訂屬性來管理您的特定案例。 若要這樣做,請遵循在 Azure Active Directory B2C 中定義自訂屬性一文中的 指示。

下一步