Share via


在 ASP.NET Core 中使用 Azure Active Directory B2C 進行雲端驗證

作者 Damien Bowden

Azure Active Directory B2C (Azure AD B2C) 是 Web 和行動應用程式的雲端身分識別管理解決方案。 服務會為裝載於雲端和內部部署的應用程式提供驗證。 驗證類型包括個別帳戶、社交網路帳戶和同盟企業帳戶。 此外,Azure AD B2C 可以使用最少的設定來提供多重要素驗證。

提示

Microsoft Entra ID、Microsoft Entra 外部 ID 和 Azure AD B2C 是個別的產品供應專案。 Entra ID 租使用者通常代表組織,而 Azure AD B2C 租使用者或 Microsoft Entra 外部 ID 租使用者則代表要與信賴憑證者應用程式搭配使用的身分識別集合。 若要深入了解,請參閱 Azure AD B2C:常見問題 (FAQ)

提示

客戶 Microsoft Entra 外部 ID 是 Microsoft 的新客戶身分識別和存取管理 (CIAM) 解決方案。

在本教學課程中,您將了解如何設定 ASP.NET Core 應用程式,以向 Azure AD B2C 進行驗證。

必要條件

準備

  1. 建立 Azure Active Directory B2C 租用戶

  2. 建立新的 ASP.NET Core Razor 頁面應用程式:

    dotnet new razor -o azure-ad-b2c
    

    上一個命令會在名為 azure-ad-b2c 的目錄中建立 Razor 頁面應用程式。

  3. 在租用戶中建立 Web 應用程式註冊。 針對重新導向 URI,請使用 https://localhost:5001/signin-oidc。 使用 Visual Studio 產生的連接埠時,將 5001 取代為應用程式所使用的連接埠。

修改應用程式

  1. Microsoft.Identity.WebMicrosoft.Identity.Web.UI 套件新增到專案。 如果您使用 Visual Studio,可以使用 NuGet 套件管理員

    dotnet add package Microsoft.Identity.Web
    dotnet add package Microsoft.Identity.Web.UI
    

    在上述:

    • Microsoft.Identity.Web 包含使用 Microsoft Identity 平台進行驗證的基本相依性集合。
    • Microsoft.Identity.Web.UI 包含封裝在名為 MicrosoftIdentity 區域中的 UI 功能。
  2. AzureADB2C 物件新增至 appsettings.json

    注意

    使用 Azure B2C 使用者流程時,您必須設定執行個體和流程類型的 PolicyId。

    {
      "AzureADB2C": {
        "Instance": "https://--your-domain--.b2clogin.com",
        "Domain": "[Enter the domain of your B2C tenant, e.g. contoso.onmicrosoft.com]",
        "TenantId": "[Enter 'common', or 'organizations' or the Tenant Id (Obtained from the Azure portal. Select 'Endpoints' from the 'App registrations' blade and use the GUID in any of the URLs), e.g. da41245a5-11b3-996c-00a8-4d99re19f292]",
        "ClientId": "[Enter the Client Id (Application ID obtained from the Azure portal), e.g. ba74781c2-53c2-442a-97c2-3d60re42f403]",
        // Use either a secret or a certificate. ClientCertificates are recommended.
        "ClientSecret": "[Copy the client secret added to the app from the Azure portal]",
        "ClientCertificates": [
        ],
        // the following is required to handle Continuous Access Evaluation challenges
        "ClientCapabilities": [ "cp1" ],
        "CallbackPath": "/signin-oidc",
        // Add your policy here
        "SignUpSignInPolicyId": "B2C_1_signup_signin",
        "SignedOutCallbackPath": "/signout-callback-oidc"
      },
      "Logging": {
        "LogLevel": {
          "Default": "Information",
          "Microsoft": "Warning",
          "Microsoft.Hosting.Lifetime": "Information"
        }
      },
      "AllowedHosts": "*"
    }
    
    • 針對網域,請使用 Azure AD B2C 租用戶的網域。
    • 針對 ClientId,請使用您租用戶中建立的應用程式註冊應用程式 (用戶端) 識別碼
    • 針對執行個體,請使用 Azure AD B2C 租用戶的網域。
    • 針對 SignUpSignInPolicyId,請使用 Azure B2C 租用戶中定義的使用者流程原則
    • 使用 ClientSecretClientCertificates 組態。 建議使用 ClientCertificates。
    • 讓所有其他值保持原樣。
  3. Pages/Shared 中,建立名為 _LoginPartial.cshtml 的檔案。 包含下列程式碼:

    @using System.Security.Principal
    
    <ul class="navbar-nav">
    @if (User.Identity?.IsAuthenticated == true)
    {
            <span class="navbar-text text-dark">Hello @User.Identity?.Name!</span>
            <li class="nav-item">
                <a class="nav-link text-dark" asp-area="MicrosoftIdentity" asp-controller="Account" asp-action="SignOut">Sign out</a>
            </li>
    }
    else
    {
            <li class="nav-item">
                <a class="nav-link text-dark" asp-area="MicrosoftIdentity" asp-controller="Account" asp-action="SignIn">Sign in</a>
            </li>
    }
    </ul>
    

    上述 程式碼:

    • 檢查使用者是否已通過驗證。
    • 視需要轉譯 登出登入 連結。
      • 連結會指向 MicrosoftIdentity 區域中 Account 控制器上的動作方法。
  4. Pages/Shared/_Layout.cshtml中,在 <header> 元素內新增醒目提示的行:

    <header>
        <nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3">
            <div class="container">
                <a class="navbar-brand" asp-area="" asp-page="/Index">azure_ad_b2c</a>
                <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target=".navbar-collapse" aria-controls="navbarSupportedContent"
                        aria-expanded="false" aria-label="Toggle navigation">
                    <span class="navbar-toggler-icon"></span>
                </button>
                <div class="navbar-collapse collapse d-sm-inline-flex justify-content-between">
                    <ul class="navbar-nav flex-grow-1">
                        <li class="nav-item">
                            <a class="nav-link text-dark" asp-area="" asp-page="/Index">Home</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link text-dark" asp-area="" asp-page="/Privacy">Privacy</a>
                        </li>
                    </ul>
                    <partial name="_LoginPartial" />
                </div>
            </div>
        </nav>
    </header>
    

    新增 <partial name="_LoginPartial" /> 會在使用此版面配置的每個頁面要求中,呈現 _LoginPartial.cshtml 部分檢視。

  5. Program.cs中,進行下列變更:

    1. 新增下列 using 指示詞:

      using Microsoft.Identity.Web;
      using Microsoft.Identity.Web.UI;
      using Microsoft.AspNetCore.Authentication.OpenIdConnect;
      

      上述程式碼會解析後續步驟中使用的參考。

    2. 使用下列程式碼更新 builder.Services 行:

      builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
              .AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureADB2C"));
      
      builder.Services.AddAuthorization(options =>
      {
          // By default, all incoming requests will be authorized according to 
          // the default policy
          options.FallbackPolicy = options.DefaultPolicy;
      });
      builder.Services.AddRazorPages(options => {
          options.Conventions.AllowAnonymousToPage("/Index");
      })
      .AddMvcOptions(options => { })
      .AddMicrosoftIdentityUI();
      

      在上述程式碼中:

      • 呼叫 AddAuthenticationAddMicrosoftIdentityWebApp 方法時,會將應用程式設定為使用 Open ID Connect,特別針對 Microsoft Identity 平台進行設定。
      • AddAuthorization 會初始化 ASP.NET Core 授權。
      • AddRazorPages 呼叫會設定應用程式,讓匿名瀏覽器可以檢視 [索引] 頁面。 所有其他要求都需要驗證。
      • AddMvcOptionsAddMicrosoftIdentityUI 新增必要的 UI 元件,以重新導向至 Azure AD B2C 或從 Azure AD B2C。
    3. 將反白顯示的行更新為 Configure 方法:

      app.UseRouting();
      
      app.UseAuthentication();
      app.UseAuthorization();
      
      app.MapRazorPages();
      

      上述程式碼會在 ASP.NET Core 中啟用驗證。

執行應用程式

注意

使用符合 Azure App 註冊的設定檔重新導向 URI

  1. 執行應用程式。

    dotnet run --launch-profile https
    
  2. 瀏覽至應用程式的安全端點,例如 https://localhost:5001/

    • [索引] 頁面不會呈現驗證挑戰。
    • 標頭包含登入連結,因為您未通過驗證。
  3. 選取 Privacy 連結。

    • 瀏覽器會重新導向至租用戶的已設定驗證方法。
    • 登入之後,標頭會顯示歡迎訊息和登出連結。

下一步

在本教學課程中,您已了解如何設定 ASP.NET Core 應用程式,以向 Azure AD B2C 進行驗證。

現在,ASP.NET Core 應用程式已設定為使用 Azure AD B2C 進行驗證,Authorize 屬性可用來保護您的應用程式。 繼續開發您的應用程式,方法是學習: