共用方式為


教學課程:設定 ASP.NET Core Web 應用程式以進行授權和驗證

適用於帶有白色核取記號符號的綠色圓圈,表示以下內容適用於員工租戶。 員工租戶 帶有白色核取記號符號的綠色圓圈,表示以下內容適用於外部租戶。 外部租用戶 (深入瞭解

在本教學課程中,您會將驗證和授權元素新增至 ASP.NET Core Web 應用程式。 在 上一個教學課程中,您已建立 ASP.NET Core 專案,並設定它以進行驗證。

在本教學課程中,您會:

  • 將授權和驗證元素新增至程序代碼
  • 啟用查看標識元令牌中的聲明
  • 新增登入和登出體驗

先決條件

新增驗證和授權元素

必須修改 HomeController.csProgram.cs 檔案,才能將驗證和授權元素新增至 ASP.NET Core Web 應用程式。 這包括管理首頁、新增正確的命名空間和設定登入。

將授權新增至 HomeController.cs

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

  1. 在您的 Web 應用程式中,開啟 Controllers/HomeController.cs,並將下列代碼段新增至檔案頂端:

    using System.Diagnostics;
    using Microsoft.AspNetCore.Authorization;
    using Microsoft.AspNetCore.Mvc;
    using dotnetcore_webapp.Models;
    
  2. [Authorize] 類別定義上方新增 HomeController 屬性,如下列代碼段所示:

    [Authorize]
    public class HomeController : Controller
    {
    ...
    

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

Program.cs 檔案是應用程式的進入點,需要修改才能將驗證和授權新增至 Web 應用程式。 必須新增服務,才能讓應用程式使用 appsettings.json 中定義的設定來進行驗證。

  1. 將下列命名空間新增至檔案頂端。

    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. 接下來,新增 Microsoft Identity Web 應用程式驗證服務,以設定應用程式使用Microsoft身分識別進行驗證。

    // 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.
    // 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();
    
    
  3. 接下來,中間件必須設定為啟用驗證功能。 以下列代碼段取代其餘的程序代碼。

    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();
    

新增登錄和登出功能的使用體驗

UI 必須更新,以提供更友善的使用者登入和註銷體驗。本節說明如何建立新的檔案,以根據使用者的驗證狀態顯示導覽項目。 程式碼會讀取 ID 令牌宣告,以確認使用者是否已通過驗證,並使用 User.Claims 來擷取 ID 令牌宣告。

  1. Views/Shared 中建立新檔案,並將名稱命名為 _LoginPartial.cshtml

  2. 開啟 檔案,並新增下列程式代碼以新增登入和註銷體驗:

    @using System.Security.Principal
    
    <ul class="navbar-nav">
    @if (User.Identity is not null && User.Identity.IsAuthenticated)
    {
            <li class="nav-item">
                <span class="nav-link text-dark">Hello @User.Claims.First(c => c.Type == "preferred_username").Value!</span>
            </li>
            <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>
    
  3. 開啟 Views/Shared/_Layout.cshtml,並將上一個步驟中建立的 _LoginPartial 的參考加入。 將此放在 navbar-nav 類別的結尾附近,如下列代碼段所示:

    <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>
    

使用自訂網址 (選擇性)

適用於帶有白色核取記號符號的綠色圓圈,表示下列內容適用於外部租用戶。 外部租用戶 (深入瞭解

使用自定義網域來進行完整的品牌化驗證 URL。 從用戶的觀點來看,用戶在驗證過程中會停留在您的網域上,而不是被重新導向至 ciamlogin.com 網域名稱。

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

  1. 使用「外部租使用者中的應用程式啟用自訂 URL 網域」中的步驟,來為您的外部租使用者啟用自訂 URL 網域(參見)。

  2. 開啟 appsettings.json 檔案:

    1. InstanceTenantId 參數更新為 Authority 屬性。
    2. 將下列字串新增至 Authority 值和 https://Enter_the_Custom_Domain_Here/Enter_the_Tenant_ID_Here。 將 Enter_the_Custom_Domain_Here 替換為您的自訂 URL 網域,並將 Enter_the_Tenant_ID_Here 替換為您的租用戶 ID。 如果您沒有租使用者標識碼,請瞭解如何 閱讀租使用者詳細數據
    3. 新增 knownAuthorities 屬性,並設值為 [Enter_the_Custom_Domain_Here]

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",
    "ClientCertificates": [
      {
        "SourceType": "StoreWithThumbprint",
        "CertificateStorePath": "CurrentUser/My",
        "CertificateThumbprint": "AA11BB22CC33DD44EE55FF66AA77BB88CC99DD00"
      }   
    ],
    "CallbackPath": "/signin-oidc",
    "SignedOutCallbackPath": "/signout-callback-oidc",
    "KnownAuthorities": ["login.contoso.com"]
    ...

下一步