分享方式:


教學課程:將登入新增至應用程式

上一個教學課程中,已建立並設定 ASP.NET Core 專案以進行驗證。 本教學課程將安裝必要的套件,並將實作驗證的代碼新增至登入和登出體驗。

在本教學課程中:

  • 識別並安裝驗證所需的 NuGet 套件
  • 在代碼中實作驗證
  • 新增登入和登出體驗

必要條件

安裝身分識別套件

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

  1. 在 Visual Studio 的頂端功能表中,選取 [工具]>[NuGet 套件管理員]>[管理解決方案的 NuGet 套件]
  2. 選取 [瀏覽] 索引標籤後,搜尋並選取 [Microsoft.Identity.Web.UI]。 選取 [專案] 核取方塊,然後選取 [安裝]
  3. 針對 Microsoft.Identity.Web.Diagnostics 和 Microsoft.Identity.Web.DownstreamApi 重複此作業。

實作驗證並取得權杖

  1. 開啟 Program.cs,並以下列程式碼片段取代整個檔案內容:

    // <ms_docref_import_types>
    using Microsoft.AspNetCore.Authorization;
    using Microsoft.AspNetCore.Mvc.Authorization;
    using Microsoft.Identity.Web;
    using Microsoft.Identity.Web.UI;
    // </ms_docref_import_types>
    
    // <ms_docref_add_msal>
    WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
    IEnumerable<string>? initialScopes = builder.Configuration["DownstreamApi:Scopes"]?.Split(' ');
    
    
    builder.Services.AddMicrosoftIdentityWebAppAuthentication(builder.Configuration, "AzureAd")
        .EnableTokenAcquisitionToCallDownstreamApi(initialScopes)
            .AddDownstreamApi("DownstreamApi", builder.Configuration.GetSection("DownstreamApi"))
            .AddInMemoryTokenCaches();
    // </ms_docref_add_msal>
    
    // <ms_docref_add_default_controller_for_sign-in-out>
    builder.Services.AddRazorPages().AddMvcOptions(options =>
        {
            var policy = new AuthorizationPolicyBuilder()
                          .RequireAuthenticatedUser()
                          .Build();
            options.Filters.Add(new AuthorizeFilter(policy));
        }).AddMicrosoftIdentityUI();
    // </ms_docref_add_default_controller_for_sign-in-out>
    
    // <ms_docref_enable_authz_capabilities>
    WebApplication app = builder.Build();
    
    app.UseAuthentication();
    app.UseAuthorization();
    // </ms_docref_enable_authz_capabilities>
    
    app.UseHttpsRedirection();
    app.UseStaticFiles();
    
    app.UseRouting();
    
    app.MapRazorPages();
    app.MapControllers();
    
    app.Run();
    

新增登入和登出體驗

安裝 NuGet 套件並新增必要的驗證代碼之後,請新增登入和登出體驗。

建立 _LoginPartial.cshtml 檔案

  1. 展開 [頁面],以滑鼠右鍵按一下 [共用],然後選取 [新增 > Razor]頁面
  2. 選取 [Razor 頁面 - 空白],然後選取 [新增]
  3. 在名稱輸入 [_LoginPartial.cshtml],然後選取 [新增]

編輯 [_LoginPartial.cshtml] 檔案

  1. 開啟 [_LoginPartial.cshtml] 並新增下列代碼以新增登入和登出體驗:

    @using System.Security.Principal
    
    <ul class="navbar-nav">
    @if (User.Identity?.IsAuthenticated == true)
    {
            <li class="nav-item">
                <span class="navbar-text text-dark">Hello @User.Identity?.Name!</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>
    
  2. 開啟 [_Layout.cshtml] 並將參考新增至上一個步驟中建立的 _LoginPartial。 這一行應該放在 </ul></div> 之間:

        </ul>
        <partial name="_LoginPartial" />
    </div>
    

下一步