共用方式為


使用 Azure AD B2C 啟用 Python Web 應用程式驗證選項

本文描述如何啟用、自訂和增強 Python Web 應用程式的 Azure Active Directory B2C (Azure AD B2C) 驗證體驗。

開始之前,請務必先熟悉如何使用 Azure AD B2C 在範例 Python Web 應用程式中設定驗證

使用自訂網域

透過使用自訂網域,您可以完全標記驗證 URL。 就使用者而言,使用者在驗證過程中一直停留在您的網域中,並沒有重新導向至 Azure AD B2C b2clogin.com 網域名稱。

若要移除 URL 中對 "b2c" 的所有參考,您也可以將驗證要求 URL 中的 B2C 租用戶名稱 contoso.onmicrosoft.com 換成您自己的租用戶識別碼 GUID。 例如,您可以將 https://fabrikamb2c.b2clogin.com/contoso.onmicrosoft.com/ 變更為 https://account.contosobank.co.uk/<tenant ID GUID>/

若要在驗證 URL 中使用自訂網域和租用戶識別碼:

  1. 遵循啟用自訂網域中的指導方針。
  2. app_config.py 檔案中,以您的自訂網域更新 authority_template 類別成員。

下列 Python 程式碼顯示變更前的應用程式設定:

authority_template = "https://{tenant}.b2clogin.com/{tenant}.onmicrosoft.com/{user_flow}"

下列 Python 程式碼顯示變更後的應用程式設定:

authority_template = "https://custom.domain.com/00000000-0000-0000-0000-000000000000/{user_flow}" 

預先填入登入名稱

在登入使用者旅程圖中,您的應用程式可能會將特定使用者當作目標。 當應用程式將使用者當作目標時,可在授權要求中指定 login_hint 查詢參數與使用者的登入名稱。 Azure AD B2C 會自動填入登入名稱,而使用者只需提供密碼。

若要預先填入登入名稱,請執行下列動作:

  1. 如果您使用的是自訂原則,請新增必要的輸入宣告,如設定直接登入中所述。
  2. 找出 initiate_auth_code_flow 方法,然後新增 login_hint 參數與識別提供者網域名稱 (例如 facebook.com)。
def _build_auth_code_flow(authority=None, scopes=None):
    return _build_msal_app(authority=authority).initiate_auth_code_flow(
        scopes or [],
        redirect_uri=url_for("authorized", _external=True),
        login_hint="bob@contoso.com")

預先選取識別提供者

如果您已將應用程式的登入旅程圖設定為包含社交帳戶 (例如 Facebook、LinkedIn 或 Google),您可以指定 domain_hint 參數。 此查詢參數會向 Azure AD B2C 提供應該用於登入的社交識別提供者相關提示。 例如,如果應用程式指定 domain_hint=facebook.com,則登入流程會直接移至 Facebook 登入頁面。

若要將使用者重新導向至外部識別提供者,請執行下列動作:

  1. 檢查外部識別提供者的網域名稱。 如需詳細資訊,請參閱將登入重新導向至社交提供者

  2. 找出 initiate_auth_code_flow 方法,然後新增 domain_hint 參數與登入提示。

    def _build_auth_code_flow(authority=None, scopes=None):
        return _build_msal_app(authority=authority).initiate_auth_code_flow(
            scopes or [],
            redirect_uri=url_for("authorized", _external=True),
            domain_hint="facebook.com")
    

後續步驟