適用於:
員工租戶
外部租用戶 (深入瞭解)
在本教學課程中,您會將驗證和授權元素新增至 ASP.NET Core Web 應用程式。 在 上一個教學課程中,您已建立 ASP.NET Core 專案,並設定它以進行驗證。
在本教學課程中,您會:
- 將授權和驗證元素新增至程序代碼
- 啟用查看標識元令牌中的聲明
- 新增登入和登出體驗
先決條件
新增驗證和授權元素
必須修改 HomeController.cs 和 Program.cs 檔案,才能將驗證和授權元素新增至 ASP.NET Core Web 應用程式。 這包括管理首頁、新增正確的命名空間和設定登入。
將授權新增至 HomeController.cs
應用程式的首頁必須能夠授權使用者。
Microsoft.AspNetCore.Authorization 命名空間提供類別和介面,以實作 Web 應用程式的授權。
[Authorize] 屬性可用來指定只有已驗證的使用者可以使用 Web 應用程式。
在您的 Web 應用程式中,開啟 Controllers/HomeController.cs,並將下列代碼段新增至檔案頂端:
using System.Diagnostics; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using dotnetcore_webapp.Models;在
[Authorize]類別定義上方新增HomeController屬性,如下列代碼段所示:[Authorize] public class HomeController : Controller { ...
將驗證和授權元素新增至 Program.cs
Program.cs 檔案是應用程式的進入點,需要修改才能將驗證和授權新增至 Web 應用程式。 必須新增服務,才能讓應用程式使用 appsettings.json 中定義的設定來進行驗證。
將下列命名空間新增至檔案頂端。
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;接下來,新增 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();接下來,中間件必須設定為啟用驗證功能。 以下列代碼段取代其餘的程序代碼。
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 令牌宣告。
在 Views/Shared 中建立新檔案,並將名稱命名為 _LoginPartial.cshtml。
開啟 檔案,並新增下列程式代碼以新增登入和註銷體驗:
@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>開啟 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 網域名稱。
請遵循下列步驟來使用自訂網域:
開啟 appsettings.json 檔案:
- 將
Instance和TenantId參數更新為Authority屬性。 - 將下列字串新增至
Authority值和https://Enter_the_Custom_Domain_Here/Enter_the_Tenant_ID_Here。 將Enter_the_Custom_Domain_Here替換為您的自訂 URL 網域,並將Enter_the_Tenant_ID_Here替換為您的租用戶 ID。 如果您沒有租使用者標識碼,請瞭解如何 閱讀租使用者詳細數據。 - 新增
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"]
...