這很重要
自 2025 年 5 月 1 日起,Azure AD B2C 將不再可供新客戶購買。 在我們的常見問題中深入瞭解。
本文說明如何為您的 Web 應用程式啟用、自定義及增強 Azure Active Directory B2C (Azure AD B2C) 驗證體驗。
開始之前,請務必先熟悉下列文章:
使用自訂網域
藉由使用 自定義網域,您可以完全將驗證 URL 品牌化。 從使用者的角度來看,使用者在驗證過程中會停留在您的網域上,而不會被重新導向至 Azure AD B2C b2clogin.com 網域名稱。
若要完全移除 URL 中對「b2c」的所有提及,您也可以將驗證請求 URL 中的 B2C 租使用者名稱 contoso.onmicrosoft.com 取代為您的租使用者 ID GUID。 例如,您可以變更 https://fabrikamb2c.b2clogin.com/contoso.onmicrosoft.com/
變更為 https://account.contosobank.co.uk/<tenant ID GUID>/
。
若要在驗證 URL 中使用自訂網域和租使用者識別碼,請遵循 啟用自定義網域中的指引。 開啟專案根資料夾下的 appsettings.json 檔案。 此檔案包含 Azure AD B2C 識別提供者的相關信息。
在 appsettings.json 檔案中,執行下列動作:
下列 JSON 會在變更之前顯示應用程式設定:
"AzureAdB2C": {
"Instance": "https://contoso.b2clogin.com",
"Domain": "tenant-name.onmicrosoft.com",
...
}
下列 JSON 會在變更之後顯示應用程式設定:
"AzureAdB2C": {
"Instance": "https://login.contoso.com",
"Domain": "00000000-0000-0000-0000-000000000000",
...
}
支援進階案例
AddMicrosoftIdentityWebAppAuthentication
Microsoft身分識別平臺 API 中的 方法可讓開發人員為進階驗證案例新增程式代碼,或訂閱 OpenIdConnect 事件。 例如,您可以訂閱 OnRedirectToIdentityProvider,這可讓您自定義應用程式傳送至 Azure AD B2C 的驗證要求。
若要支援進階案例,請開啟 Startup.cs 檔案,然後在 函式中 ConfigureServices
,將 取代 AddMicrosoftIdentityWebAppAuthentication
為下列代碼段:
// Configuration to sign-in users with Azure AD B2C
//services.AddMicrosoftIdentityWebAppAuthentication(Configuration, "AzureAdB2C");
services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(options =>
{
Configuration.Bind("AzureAdB2C", options);
options.Events ??= new OpenIdConnectEvents();
options.Events.OnRedirectToIdentityProvider += OnRedirectToIdentityProviderFunc;
});
上述程式代碼會新增 OnRedirectToIdentityProvider 事件與 方法的 OnRedirectToIdentityProviderFunc
參考。 將下列代碼段新增至 Startup.cs
類別。
private async Task OnRedirectToIdentityProviderFunc(RedirectContext context)
{
// Custom code here
// Don't remove this line
await Task.CompletedTask.ConfigureAwait(false);
}
您可以使用內容參數,在控制器與 OnRedirectToIdentityProvider
函式之間傳遞參數。
預先填入登入名稱
在登入使用者旅程圖期間,您的應用程式可能會以特定用戶為目標。 當應用程式以用戶為目標時,可以在授權要求 login_hint
中指定具有使用者登入名稱的查詢參數。 Azure AD B2C 會自動填入登入名稱,而且使用者只需要提供密碼。
若要預填登入名稱,請執行以下步驟:
如果您使用自定義原則,請新增必要的輸入宣告,如 設定直接登入中所述。
完成 支援進階案例 程式。
將下列程式代碼列新增至 函
OnRedirectToIdentityProvider
式:private async Task OnRedirectToIdentityProviderFunc(RedirectContext context) { context.ProtocolMessage.LoginHint = "emily@contoso.com"; // More code await Task.CompletedTask.ConfigureAwait(false); }
預先選取識別提供者
如果您將應用程式的登入旅程設定為包含社交帳戶,例如 Facebook、LinkedIn 或 Google,您可以指定 domain_hint
參數。 此查詢參數會針對應該用於登入的社交識別提供者,提供 Azure AD B2C 的提示。 例如,如果應用程式指定 domain_hint=facebook.com
,則登入流程會直接移至 Facebook 登入頁面。
若要將使用者重新導向至外部識別提供者,請執行下列動作:
檢查您的外部身份提供者的網域名稱。 如需詳細資訊,請參閱 將登入重新導向至社交提供者。
完成 支援進階案例 程式。
在函式中
OnRedirectToIdentityProviderFunc
,將下列程式代碼行新增至 函OnRedirectToIdentityProvider
式:private async Task OnRedirectToIdentityProviderFunc(RedirectContext context) { context.ProtocolMessage.DomainHint = "facebook.com"; // More code await Task.CompletedTask.ConfigureAwait(false); }
指定UI語言
Azure AD B2C 中的語言自定義可讓您的使用者流程適應各種語言,以符合客戶需求。 如需詳細資訊,請參閱 語言自定義。
若要設定慣用的語言,請執行下列動作:
完成 支援進階案例 程式。
將下列程式代碼列新增至 函
OnRedirectToIdentityProvider
式:private async Task OnRedirectToIdentityProviderFunc(RedirectContext context) { context.ProtocolMessage.UiLocales = "es"; // More code await Task.CompletedTask.ConfigureAwait(false); }
傳遞自訂查詢字串參數
使用自定義原則,您可以傳遞自定義查詢字串參數。 良好的使用案例範例是當您想要 動態變更頁面內容時。
若要傳遞自訂查詢字串參數,請執行下列動作:
設定 ContentDefinitionParameters 元素。
完成 支援進階案例 程式。
將下列程式代碼列新增至 函
OnRedirectToIdentityProvider
式:private async Task OnRedirectToIdentityProviderFunc(RedirectContext context) { context.ProtocolMessage.Parameters.Add("campaignId", "123"); // More code await Task.CompletedTask.ConfigureAwait(false); }
傳遞 ID 令牌提示
信賴方應用程式可以在 OAuth2 授權要求中傳送入境 JSON Web 令牌(JWT)。 輸入令牌提供有關用戶或授權請求的線索。 Azure AD B2C 會驗證令牌,然後擷取聲明。
若要在驗證要求中包含識別元令牌提示,請執行下列動作:
完成 支援進階案例 程式。
在您的自定義原則中,定義 ID 令牌提示技術設定檔。
將下列程式代碼列新增至 函
OnRedirectToIdentityProvider
式:private async Task OnRedirectToIdentityProviderFunc(RedirectContext context) { // The idTokenHint variable holds your ID token context.ProtocolMessage.IdTokenHint = idTokenHint // More code await Task.CompletedTask.ConfigureAwait(false); }
帳戶控制者
如果您想要自定義 SignIn、 SignUp 或 SignOut 動作,建議您建立自己的控制器。 擁有您自己的控制器可讓您在控制器與驗證連結庫之間傳遞參數。
AccountController
是 NuGet 套件的一 Microsoft.Identity.Web.UI
部分,可處理登入和註銷動作。 您可以在 Microsoft Identity Web 連結庫中找到其實作。
新增帳戶控制器
在 Visual Studio 專案中,以滑鼠右鍵按兩下 Controllers 資料夾,然後新增 控制器。 選取 [MVC - 空白控制器],然後提供 名稱MyAccountController.cs。
下列代碼段示範使用MyAccountController
巨集指令的自定義。
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace mywebapp.Controllers
{
[AllowAnonymous]
[Area("MicrosoftIdentity")]
[Route("[area]/[controller]/[action]")]
public class MyAccountController : Controller
{
[HttpGet("{scheme?}")]
public IActionResult SignIn([FromRoute] string scheme)
{
scheme ??= OpenIdConnectDefaults.AuthenticationScheme;
var redirectUrl = Url.Content("~/");
var properties = new AuthenticationProperties { RedirectUri = redirectUrl };
return Challenge(properties, scheme);
}
}
}
在 _LoginPartial.cshtml 檢視中,變更控制器的登入連結。
<form method="get" asp-area="MicrosoftIdentity" asp-controller="MyAccount" asp-action="SignIn">
傳遞 Azure AD B2C 原則標識碼
下列代碼段示範使用 MyAccountController
和 SignUp 動作的自定義。 動作會將名為 policy
的參數傳遞至驗證連結庫。 這可讓您針對特定動作提供正確的 Azure AD B2C 原則標識碼。
public IActionResult SignIn([FromRoute] string scheme)
{
scheme ??= OpenIdConnectDefaults.AuthenticationScheme;
var redirectUrl = Url.Content("~/");
var properties = new AuthenticationProperties { RedirectUri = redirectUrl };
properties.Items["policy"] = "B2C_1_SignIn";
return Challenge(properties, scheme);
}
public IActionResult SignUp([FromRoute] string scheme)
{
scheme ??= OpenIdConnectDefaults.AuthenticationScheme;
var redirectUrl = Url.Content("~/");
var properties = new AuthenticationProperties { RedirectUri = redirectUrl };
properties.Items["policy"] = "B2C_1_SignUp";
return Challenge(properties, scheme);
}
在 _LoginPartial.cshtml 檢視中,將任何其他驗證連結的值變更 asp-controller
為 MyAccountController
,例如註冊或編輯配置檔。
傳遞自定義參數
下列代碼段示範使用MyAccountController
巨集指令的自定義。 動作會將名為 campaign_id
的參數傳遞至驗證連結庫。
public IActionResult SignIn([FromRoute] string scheme)
{
scheme ??= OpenIdConnectDefaults.AuthenticationScheme;
var redirectUrl = Url.Content("~/");
var properties = new AuthenticationProperties { RedirectUri = redirectUrl };
properties.Items["policy"] = "B2C_1_SignIn";
properties.Items["campaign_id"] = "1234";
return Challenge(properties, scheme);
}
完成 支援進階案例 程式,然後在 方法中 OnRedirectToIdentityProvider
讀取自定義參數:
private async Task OnRedirectToIdentityProviderFunc(RedirectContext context)
{
// Read the custom parameter
var campaign_id = context.Properties.Items.FirstOrDefault(x => x.Key == "campaign_id").Value;
// Add your custom code here
if (campaign_id != null)
{
// Send parameter to authentication request
context.ProtocolMessage.SetParameter("campaign_id", campaign_id);
}
await Task.CompletedTask.ConfigureAwait(false);
}
保護您的登出重定向
註銷之後,不論為應用程式指定的回復 URL 為何,用戶都會重新導向至 參數中指定的 post_logout_redirect_uri
URI。 不過,如果傳遞有效 id_token_hint
且開啟 註銷要求中的 [需要標識符令牌 ],Azure AD B2C 會在 post_logout_redirect_uri
執行重新導向之前,先確認的值符合其中一個應用程式設定的重新導向 URI。 如果未為應用程式設定相符的回復 URL,則會顯示錯誤訊息,而且不會重新導向使用者。
若要在應用程式中支援安全的註銷重新導向,請先遵循 帳戶控制器 及 支援進階案例 一節中的步驟。 然後遵循下列步驟:
在控制器中
MyAccountController.cs
,使用下列代碼段新增 SignOut 動作:[HttpGet("{scheme?}")] public async Task<IActionResult> SignOutAsync([FromRoute] string scheme) { scheme ??= OpenIdConnectDefaults.AuthenticationScheme; //obtain the id_token var idToken = await HttpContext.GetTokenAsync("id_token"); //send the id_token value to the authentication middleware properties.Items["id_token_hint"] = idToken; return SignOut(properties,CookieAuthenticationDefaults.AuthenticationScheme,scheme); }
在 Startup.cs 類別中,剖析值,
id_token_hint
並將值附加至驗證要求。 下列代碼段示範如何將值傳遞id_token_hint
至驗證要求:private async Task OnRedirectToIdentityProviderForSignOutFunc(RedirectContext context) { var id_token_hint = context.Properties.Items.FirstOrDefault(x => x.Key == "id_token_hint").Value; if (id_token_hint != null) { // Send parameter to authentication request context.ProtocolMessage.SetParameter("id_token_hint", id_token_hint); } await Task.CompletedTask.ConfigureAwait(false); }
在函式中
ConfigureServices
SaveTokens
,新增 Controllers 的 選項可存取id_token
值:services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme) .AddMicrosoftIdentityWebApp(options => { Configuration.Bind("AzureAdB2C", options); options.Events ??= new OpenIdConnectEvents(); options.Events.OnRedirectToIdentityProviderForSignOut += OnRedirectToIdentityProviderForSignOutFunc; options.SaveTokens = true; });
在 appsettings.json 組態檔中,將註銷重新導向 URI 路徑新增至
SignedOutCallbackPath
密鑰。"AzureAdB2C": { "Instance": "https://<your-tenant-name>.b2clogin.com", "ClientId": "<web-app-application-id>", "Domain": "<your-b2c-domain>", "SignedOutCallbackPath": "/signout/<your-sign-up-in-policy>", "SignUpSignInPolicyId": "<your-sign-up-in-policy>" }
在上述範例中,傳入註銷要求的 post_logout_redirect_uri 格式為: https://your-app.com/signout/<your-sign-up-in-policy>
。 此 URL 必須新增至應用程式註冊的回復 URL。
角色型存取控制
透過 ASP.NET Core 中的授權 ,您可以檢查使用者是否有權使用下列其中一種方法來存取受保護的資源:
在方法中 ConfigureServices
,新增 AddAuthorization
方法,以新增授權模型。 下列範例會建立名為 EmployeeOnly
的原則。 原則會檢查以確認宣告 EmployeeNumber
是否存在。 宣告的值必須是下列其中一個標識碼:1、2、3、4 或 5。
services.AddAuthorization(options =>
{
options.AddPolicy("EmployeeOnly", policy =>
policy.RequireClaim("EmployeeNumber", "1", "2", "3", "4", "5"));
});
您可以使用 AuthorizeAttribute 及其各種參數來控制 ASP.NET Core 中的授權。 以最基本的形式,將 Authorize
屬性套用至控制器、動作或Razor Page 會限制對該元件已驗證使用者的存取。
您可以使用具有原則名稱的屬性,將原則套用 Authorize
至控制器。 下列程式代碼會將動作的 Claims
存取限制為原則授權 EmployeeOnly
的使用者:
[Authorize(Policy = "EmployeeOnly")]
public IActionResult Claims()
{
return View();
}
後續步驟
- 若要深入瞭解授權,請參閱 ASP.NET Core 中的授權簡介。