分享方式:


教學課程:準備 ASP.NET Core Web 應用程式,以在外部租用戶進行驗證

本教學課程是系列的第 2 部分,示範如何建置 ASP.NET Core Web 應用程式,並準備使用 Microsoft Entra 系統管理中心,對其進行驗證。 在 本系列的第 1 部分中,您已在外部租用戶中註冊應用程式並設定使用者流程。 本教學課程示範如何建立 ASP.NET Core Web 應用程式,並將其設定為驗證。

在本教學課程中,您將會;

  • 在 Visual Studio Code 中建立 ASP.NET Core 專案
  • 新增必要的 NuGet 套件
  • 設定應用程式的設定
  • 新增程式碼以實作驗證

必要條件

建立 ASP.NET Core 專案

  1. 開啟 Visual Studio Code,選取 [檔案]>[開啟資料夾...]。瀏覽至並選取您要在其中建立專案的位置。

  2. 選取 [終端機]>[新增終端機] 以開啟新的終端機。

  3. 輸入下列命令,使模型檢視控制器 (MVC) ASP.NET Core 專案。

    dotnet new mvc -n dotnetcore_webapp
    

安裝身分識別套件

身分識別相關的 NuGet 套件必須安裝在專案中,才能驗證使用者。

  1. 輸入下列命令以變更至 dotnetcore_webapp 資料夾,並安裝相關的 NuGet 套件:

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

設定應用程式以進行驗證

  1. 開啟 appsettings.json 檔案,並以下列程式碼片段取代現有的程式碼。

    {
      "AzureAd": {
        "Authority": "https://Enter_the_Tenant_Subdomain_Here.ciamlogin.com/",
        "ClientId": "Enter_the_Application_Id_Here",
        "ClientCredentials": [
          {
            "SourceType": "ClientSecret",
            "ClientSecret": "Enter_the_Client_Secret_Here"
          }
        ],
        "CallbackPath": "/signin-oidc",
        "SignedOutCallbackPath": "/signout-callback-oidc"
      },
      "Logging": {
        "LogLevel": {
          "Default": "Information",
          "Microsoft.AspNetCore": "Warning"
        }
      },
      "AllowedHosts": "*"
    }
    
    • Authority - 應用程式的識別提供者執行個體和登入物件。 以外部租用戶的子網域取代 Enter_the_Tenant_Subdomain_Here。 若要尋找此專案,請在提要欄位中選取 [概觀],然後切換至 [概觀索引標籤]。在 caseyjensen.onmicrosoft.com 表單尋找主要網域。 子網域 caseyjensen
    • ClientId - 應用程式 (也稱為用戶端) 的識別碼。 將引號中的文字取代為先前從已註冊應用程式 [概觀] 頁面記錄的 [應用程式 (用戶端) 識別碼]
    • ClientSecret - 您在準備租用戶中建立的客戶端密碼值。 將引號中的文字取代為 Microsoft Entra 系統管理中心的用戶端密碼
    • CallbackPath - 這是協助伺服器將回應重新導向至適當應用程式的識別碼。
  2. 將變更儲存到 檔案。

  3. 開啟 Properties/launchSettings.json 檔案。

  4. profileshttps 區段中,變更 applicationUrl 中的 https URL,使其讀取 https://localhost:7274。 您已使用此 URL 來定義重新導向 URI

  5. 將變更儲存至檔案。

使用自訂 URL 網域 (選用)

使用自訂網域對驗證 URL 進行完整品牌化。 就使用者而言,使用者在驗證過程中一直停留在您的網域中,而不會重新導向至 ciamlogin.com 網域名稱。

遵循下列步驟來使用 自訂網域:

  1. 使用針對外部租用戶中的應用程式啟用自訂 URL 網域中的步驟,為外部租用戶啟用自訂 URL 網域。

  2. 開啟 appsettings.json 檔案:

    1. Authority 屬性的值更新為 https://Enter_the_Custom_Domain_Here/Enter_the_Tenant_ID_Here。 以您的自訂 URL 網域取代 Enter_the_Custom_Domain_Here,並以您的租用戶識別碼取代 Enter_the_Tenant_ID_Here。 如果您沒有租用戶識別碼,請了解如何讀取租用戶詳細資料
    2. 新增具有值 [Enter_the_Custom_Domain_Here]knownAuthorities 屬性。

appsettings.json 檔案進行變更之後,如果您的自訂 URL 網域為 login.contoso.com,且您的租用戶識別碼為 aaaabbbb-0000-cccc-1111-dddd2222eeee,則您的檔案看起來應該類似以下程式碼片段:

{
  "AzureAd": {
    "Authority": "https://login.contoso.com/aaaabbbb-0000-cccc-1111-dddd2222eeee",
    "ClientId": "Enter_the_Application_Id_Here",
    "ClientCredentials": [
      {
        "SourceType": "ClientSecret",
        "ClientSecret": "Enter_the_Client_Secret_Here"
      }
    ],
    "CallbackPath": "/signin-oidc",
    "SignedOutCallbackPath": "/signout-callback-oidc",
    "KnownAuthorities": ["login.contoso.com"]
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*"
}

將授權新增至 HomeController.cs

HomeController.cs 檔案包含應用程式首頁的程式碼,而且必須能夠授權使用者。 Microsoft.AspNetCore.Authorization 命名空間提供類別和介面來實作 Web 應用程式的授權,而 [Authorize] 屬性則用來指定只有已驗證的使用者可以使用 Web 應用程式。

  1. 在您的程式碼編輯器中,開啟 Controllers\HomeController.cs 檔案。

  2. 授權必須新增至控制器,新增 Microsoft.AspNetCore.Authorization 以便檔案頂端與下列程式碼片段相同:

    using System.Diagnostics;
    using Microsoft.AspNetCore.Authorization;
    using Microsoft.AspNetCore.Mvc;
    using dotnetcore_webapp.Models;
    
  3. 此外,直接在 HomeController 類別定義上方新增 [Authorize] 屬性。

    [Authorize]
    

將驗證和授權新增至 Program.cs

必須修改 Program.cs,才能將驗證和授權新增至 Web 應用程式。 這包括新增驗證和授權的命名空間,以及能夠使用 Microsoft 身分識別平台登入使用者。

  1. 若要新增必要的命名空間,請開啟 Program.cs,並將下列程式碼片段新增至檔案頂端:

    using Microsoft.AspNetCore.Authentication.OpenIdConnect;
    using Microsoft.AspNetCore.Authorization;
    using Microsoft.AspNetCore.Mvc.Authorization;
    using Microsoft.Identity.Web;
    using Microsoft.Identity.Web.UI;
    using System.IdentityModel.Tokens.Jwt;
    
  2. 接下來,將驗證服務新增至應用程式,讓 Web 應用程式能夠使用 Microsoft 身分識別平台登入使用者。 您可以使用下列程式碼片段取代 Program.cs 中的其餘程式碼:

    var builder = WebApplication.CreateBuilder(args);
    
    // Add services to the container.
    builder.Services.AddControllersWithViews();
    
    // This is required to be instantiated before the OpenIdConnectOptions starts getting configured.
    // By default, the claims mapping will map claim names in the old format to accommodate older SAML applications.
    // For instance, 'http://schemas.microsoft.com/ws/2008/06/identity/claims/role' instead of 'roles' claim.
    // This flag ensures that the ClaimsIdentity claims collection will be built from the claims in the token
    JwtSecurityTokenHandler.DefaultMapInboundClaims = false;
    
    // Sign-in users with the Microsoft identity platform
    builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
        .AddMicrosoftIdentityWebApp(builder.Configuration)
        .EnableTokenAcquisitionToCallDownstreamApi()
        .AddInMemoryTokenCaches();
    
    builder.Services.AddControllersWithViews(options =>
    {
        var policy = new AuthorizationPolicyBuilder()
            .RequireAuthenticatedUser()
            .Build();
        options.Filters.Add(new AuthorizeFilter(policy));
    }).AddMicrosoftIdentityUI();
    
    var app = builder.Build();
    
    // Configure the HTTP request pipeline.
    if (!app.Environment.IsDevelopment())
    {
        app.UseExceptionHandler("/Home/Error");
        // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
        app.UseHsts();
    }
    
    app.UseHttpsRedirection();
    app.UseStaticFiles();
    
    app.UseRouting();
    app.UseAuthorization();
    
    app.MapControllerRoute(
        name: "default",
        pattern: "{controller=Home}/{action=Index}/{id?}");
    
    app.Run();
    
    

後續步驟