注意
並非所有用戶端都被允許取得 mTLS PoP 憑證,因為此功能目前處於私人預覽階段。
憑證憑證綁定(亦稱為 mTLS PoP——互惠 TLS 擁有證明)是一種先進的安全功能,能以密碼學方式將存取憑證綁定到特定的 X.509 憑證上。 RFC 8705 描述了這種綁定方式。 綁定確保即使攔截了令牌,攻擊者也無法在未擁有相應私鑰的情況下使用該標記。
了解代幣綁定的運作方式
以下步驟描述從取得到驗證的代幣綁定流程。
- Token Acquisition:當請求啟用令牌綁定的存取令牌時,Microsoft Identity Web 會在令牌請求中包含憑證的指紋
-
令牌綁定:授權伺服器會在
cnf已發出的令牌中嵌入包含憑證 SHA-256 拇指印記(x5t#S256)的(確認)聲明 - API 呼叫:客戶端在呼叫下游 API 時,同時呈現綁定的代幣與憑證。
-
驗證:API 驗證所呈現的憑證是否
cnf符合憑證聲明中的憑證參考
sequenceDiagram
participant Client
participant EntraID as Microsoft Entra ID
participant API
Client->>EntraID: Token request with certificate thumbprint
EntraID->>Client: Token with cnf claim (bound to certificate)
Client->>API: MTLS_POP token + Client certificate
API->>API: Validate token and certificate binding
API->>Client: Protected resource
檢視安全效益
令牌綁定為保護您的申請提供了以下優勢。
- 代幣盜竊保護:沒有相應證書,被盜代幣毫無用處
- 重播攻擊防止:代幣不能從不同客戶端重放
- 增強認證:結合「你擁有的東西」(憑證)與傳統 OAuth2 流程
- 零信任 架構:透過將憑證綁定至特定裝置,符合zero trust原則
設定令牌綁定
同時設定用戶端應用程式和 API 伺服器,啟用 mTLS PoP 令牌綁定。
設定用戶端應用程式
完成以下步驟以設定客戶端應用程式進行令牌綁定。
1. 設定 Microsoft Entra ID 設定
在你的 appsettings.json 中,配置 Microsoft Entra 的設定,其中也包括憑證:
{
"AzureAd": {
"Instance": "https://login.microsoftonline.com/",
"TenantId": "your-tenant-id",
"ClientId": "your-client-id",
"ClientCredentials": [
{
"SourceType": "StoreWithDistinguishedName",
"CertificateStorePath": "CurrentUser/My",
"CertificateDistinguishedName": "CN=YourCertificate"
}
],
"SendX5c": true
}
}
2. 配置下游 API 的代幣綁定
請使用 MTLS_POP 協議配置您的下游 API 區段。
{
"DownstreamApi": {
"BaseUrl": "https://api.contoso.com/",
"RelativePath": "api/data",
"ProtocolScheme": "MTLS_POP",
"RequestAppToken": true,
"Scopes": [ "api://your-api-scope/.default" ]
}
}
重要配置特性:
-
ProtocolScheme: 必須設定為"MTLS_POP"才能啟用標記綁定 -
RequestAppToken: 必須是true(目前的標記綁定僅支援應用程式標記) -
Scopes: 下游 API 呼叫所需的 API 範圍
3. 登記服務
在應用程式的啟動程式碼中註冊下游的 API 服務。 以下範例展示了主控台應用程式與 ASP.NET Core 兩種方法。
using Microsoft.Identity.Web;
var builder = WebApplication.CreateBuilder(args);
// Option 1: Using TokenAcquirerFactory (for console apps, background services)
var tokenAcquirerFactory = TokenAcquirerFactory.GetDefaultInstance();
tokenAcquirerFactory.Services.AddDownstreamApi(
"DownstreamApi",
tokenAcquirerFactory.Configuration.GetSection("DownstreamApi"));
var serviceProvider = tokenAcquirerFactory.Build();
// Option 2: Using ASP.NET Core DI (for web apps, web APIs)
builder.Services.AddAuthentication()
.AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd"));
builder.Services.AddDownstreamApi(
"DownstreamApi",
builder.Configuration.GetSection("DownstreamApi"));
設定 API 伺服器
下游 API 必須同時驗證憑證與憑證綁定。 這是一個完整的範例:
1. 登錄認證處理程式
using Microsoft.Identity.Web;
var builder = WebApplication.CreateBuilder(args);
// Add standard JWT Bearer authentication
builder.Services.AddMicrosoftIdentityWebApiAuthentication(builder.Configuration);
// Add custom MTLS_POP authentication handler
builder.Services.AddAuthentication()
.AddScheme<AuthenticationSchemeOptions, MtlsPopAuthenticationHandler>(
"MTLS_POP",
options => { });
var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
2. 實作 mTLS PoP 認證處理程序
using System.Security.Claims;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text.Encodings.Web;
using System.Text.Json;
using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.JsonWebTokens;
using Microsoft.IdentityModel.Tokens;
public class MtlsPopAuthenticationHandler : AuthenticationHandler<AuthenticationSchemeOptions>
{
public const string ProtocolScheme = "MTLS_POP";
public MtlsPopAuthenticationHandler(
IOptionsMonitor<AuthenticationSchemeOptions> options,
ILoggerFactory logger,
UrlEncoder encoder)
: base(options, logger, encoder)
{
}
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
{
// 1. Extract the MTLS_POP authorization header
var authHeader = Request.Headers.Authorization.FirstOrDefault();
if (string.IsNullOrEmpty(authHeader) ||
!authHeader.StartsWith($"{ProtocolScheme} ", StringComparison.OrdinalIgnoreCase))
{
return AuthenticateResult.NoResult();
}
var authToken = authHeader.Substring($"{ProtocolScheme} ".Length).Trim();
try
{
// 2. Parse the JWT token
var handler = new JsonWebTokenHandler();
var token = handler.ReadJsonWebToken(authToken);
// 3. Extract the 'cnf' claim
var cnfClaim = token.Claims.FirstOrDefault(c => c.Type == "cnf");
if (cnfClaim == null)
{
return AuthenticateResult.Fail("Missing 'cnf' claim in MTLS_POP token");
}
// 4. Extract certificate thumbprint from cnf claim
var cnfJson = JsonDocument.Parse(cnfClaim.Value);
if (!cnfJson.RootElement.TryGetProperty("x5t#S256", out var x5tS256Element))
{
return AuthenticateResult.Fail("Missing 'x5t#S256' in cnf claim");
}
var expectedThumbprint = x5tS256Element.GetString();
// 5. Get client certificate from TLS connection
var clientCert = Context.Connection.ClientCertificate;
if (clientCert != null)
{
var actualThumbprint = GetCertificateThumbprint(clientCert);
// 6. Validate certificate binding
if (!string.Equals(actualThumbprint, expectedThumbprint,
StringComparison.OrdinalIgnoreCase))
{
return AuthenticateResult.Fail(
"Certificate thumbprint mismatch with cnf claim");
}
}
// 7. Create claims principal
var claims = token.Claims.Select(c => new Claim(c.Type, c.Value)).ToList();
var identity = new ClaimsIdentity(claims, ProtocolScheme);
var principal = new ClaimsPrincipal(identity);
var ticket = new AuthenticationTicket(principal, ProtocolScheme);
return AuthenticateResult.Success(ticket);
}
catch (Exception ex)
{
Logger.LogError(ex, "Error validating mTLS PoP token");
return AuthenticateResult.Fail($"Validation error: {ex.Message}");
}
}
private static string GetCertificateThumbprint(X509Certificate2 certificate)
{
using var sha256 = SHA256.Create();
var hash = sha256.ComputeHash(certificate.RawData);
return Base64UrlEncoder.Encode(hash);
}
}
在應用程式中使用令牌綁定
以下範例展示了如何在不同應用類型中整合 mTLS PoP 令牌綁定。
從主控台或守護程序應用程式呼叫 API
以下範例展示一個主控台或服務守護進程的應用,使用 mTLS PoP 令牌綁定來呼叫下游 API。
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Identity.Abstractions;
using Microsoft.Identity.Web;
public class Program
{
public static async Task Main(string[] args)
{
// Create and configure token acquirer
var tokenAcquirerFactory = TokenAcquirerFactory.GetDefaultInstance();
tokenAcquirerFactory.Services.AddDownstreamApi(
"SecureApi",
tokenAcquirerFactory.Configuration.GetSection("SecureApi"));
var serviceProvider = tokenAcquirerFactory.Build();
// Get IDownstreamApi instance
var downstreamApi = serviceProvider.GetRequiredService<IDownstreamApi>();
// Call API with mTLS PoP token
var response = await downstreamApi.GetForAppAsync<ApiResponse>("SecureApi");
Console.WriteLine($"Result: {response?.Data}");
}
}
public class ApiResponse
{
public string? Data { get; set; }
}
從 ASP.NET Core 網頁應用程式調用 API
以下範例展示了一個控制器呼叫下游 API,並以 mTLS PoP 令牌綁定。
using Microsoft.AspNetCore.Mvc;
using Microsoft.Identity.Abstractions;
[ApiController]
[Route("api/[controller]")]
public class DataController : ControllerBase
{
private readonly IDownstreamApi _downstreamApi;
private readonly ILogger<DataController> _logger;
public DataController(
IDownstreamApi downstreamApi,
ILogger<DataController> logger)
{
_downstreamApi = downstreamApi;
_logger = logger;
}
[HttpGet]
public async Task<IActionResult> GetSecureData()
{
try
{
// Call downstream API with mTLS PoP token binding
var data = await _downstreamApi.GetForAppAsync<SecureData>(
"SecureApi");
return Ok(data);
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to retrieve secure data");
return StatusCode(500, "Failed to retrieve data");
}
}
}
public class SecureData
{
public string? Id { get; set; }
public string? Value { get; set; }
}
透過程式配置 DownstreamApiOptions
以下範例直接以程式碼設定 mTLS PoP 選項,而非設定檔。
using Microsoft.Identity.Abstractions;
using Microsoft.Identity.Web;
public class SecureApiService
{
private readonly IDownstreamApi _downstreamApi;
public SecureApiService(IDownstreamApi downstreamApi)
{
_downstreamApi = downstreamApi;
}
public async Task<T?> CallSecureApiAsync<T>(string endpoint) where T : class
{
return await _downstreamApi.GetForAppAsync<T>(
serviceName: null,
downstreamApiOptionsOverride: options =>
{
options.BaseUrl = "https://api.secure.com";
options.RelativePath = endpoint;
options.ProtocolScheme = "MTLS_POP";
options.RequestAppToken = true;
options.Scopes = new[] { "api://secure-api/.default" };
});
}
}
使用 MicrosoftIdentityMessageHandler 搭配憑證綁定
MicrosoftIdentityMessageHandler 支援透過 AddMicrosoftIdentityMessageHandler 擴充方法綁定 mTLS PoP 令牌。 當 ProtocolScheme 設定為 "MTLS_POP"時,處理程序會自動取得綁定權杖,並透過已配置 mTLS 的 HTTP 用戶端發送請求。
設定內嵌選項
以下範例註冊一個具有內嵌 mTLS PoP 設定的 HTTP 用戶端,並展示其在服務中的使用情況。
// Program.cs
services.AddHttpClient("MtlsPopClient", client =>
{
client.BaseAddress = new Uri("https://api.contoso.com");
})
.AddMicrosoftIdentityMessageHandler(options =>
{
options.Scopes.Add("api://contoso/.default");
options.ProtocolScheme = "MTLS_POP";
options.RequestAppToken = true;
});
// Usage in a service
public class SecureApiService
{
private readonly HttpClient _httpClient;
public SecureApiService(IHttpClientFactory factory)
{
_httpClient = factory.CreateClient("MtlsPopClient");
}
public async Task<string> GetSecureDataAsync()
{
// Authentication and mTLS certificate binding are automatic
var response = await _httpClient.GetAsync("/api/secure-data");
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync();
}
}
從 appsettings.json 載入配置設定
你也可以從設定檔載入令牌綁定設定。
appsettings.json:
{
"DownstreamApis": {
"SecureApi": {
"Scopes": ["api://secure-api/.default"],
"ProtocolScheme": "MTLS_POP",
"RequestAppToken": true
}
}
}
Program.cs:以下程式碼透過設定區段註冊 HTTP 用戶端。
services.AddHttpClient("SecureApiClient", client =>
{
client.BaseAddress = new Uri("https://secure-api.example.com");
})
.AddMicrosoftIdentityMessageHandler(
configuration.GetSection("DownstreamApis:SecureApi"),
"SecureApi");
套用每個請求的標記綁定
當部分請求需要標記綁定,而其他請求不需要時,請使用每個請求的選項:
services.AddHttpClient("FlexibleClient")
.AddMicrosoftIdentityMessageHandler();
// In a service:
public async Task<string> CallWithTokenBindingAsync()
{
var request = new HttpRequestMessage(HttpMethod.Get, "https://api.contoso.com/secure")
.WithAuthenticationOptions(options =>
{
options.Scopes.Add("api://contoso/.default");
options.ProtocolScheme = "MTLS_POP";
options.RequestAppToken = true;
});
var response = await _httpClient.SendAsync(request);
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync();
}
欲了解更多相關MicrosoftIdentityMessageHandler資訊,請參閱自訂 API 文件。
建立一個帶有授權標頭提供者的自訂 HttpClient
這種方法適用於需要對 HTTP 請求更嚴格控制的情境。 以下範例取得綁定授權標頭,並建立一個 mTLS 設定的 HTTP 用戶端。
using Microsoft.Identity.Abstractions;
using System.Net.Http.Headers;
public class CustomApiClient
{
private readonly IAuthorizationHeaderProvider _authProvider;
private readonly IHttpClientFactory _httpClientFactory;
public CustomApiClient(
IAuthorizationHeaderProvider authProvider,
IHttpClientFactory httpClientFactory)
{
_authProvider = authProvider;
_httpClientFactory = httpClientFactory;
}
public async Task<string> CallApiWithCustomLogicAsync()
{
// Create downstream API options for mTLS PoP
var apiOptions = new DownstreamApiOptions
{
BaseUrl = "https://api.contoso.com",
ProtocolScheme = "MTLS_POP",
RequestAppToken = true,
Scopes = new[] { "api://contoso/.default" }
};
// Get authorization header with binding certificate info
var authResult = await (_authProvider as IBoundAuthorizationHeaderProvider)
?.CreateBoundAuthorizationHeaderAsync(apiOptions)!;
if (authResult.IsSuccess)
{
// Create HTTP client with certificate binding
var httpClient = authResult.Value.BindingCertificate != null
? CreateMtlsHttpClient(authResult.Value.BindingCertificate)
: _httpClientFactory.CreateClient();
// Set authorization header
httpClient.DefaultRequestHeaders.Authorization =
AuthenticationHeaderValue.Parse(authResult.Value.AuthorizationHeaderValue);
// Make API call
var response = await httpClient.GetAsync(
$"{apiOptions.BaseUrl}/api/endpoint");
return await response.Content.ReadAsStringAsync();
}
throw new InvalidOperationException("Failed to acquire token");
}
private HttpClient CreateMtlsHttpClient(X509Certificate2 certificate)
{
var handler = new HttpClientHandler();
handler.ClientCertificates.Add(certificate);
return new HttpClient(handler);
}
}
檢視代幣結構
以下範例說明標準標記與綁定標記的差異。
比較標準 OAuth2 代幣
標準的 OAuth2 令牌不含憑證綁定資訊。
{
"aud": "api://your-api",
"iss": "https://login.microsoftonline.com/tenant-id/",
"iat": 1234567890,
"exp": 1234571490,
"appid": "client-id",
"tid": "tenant-id"
}
檢視帶有綁定功能的 mTLS PoP 代幣
mTLS PoP 令牌包含 cnf 將該令牌綁定於特定憑證的權利要求。
{
"aud": "api://your-api",
"iss": "https://login.microsoftonline.com/tenant-id/",
"iat": 1234567890,
"exp": 1234571490,
"appid": "client-id",
"tid": "tenant-id",
"cnf": {
"x5t#S256": "buc7x2HxS_hPnVJb9J5mwPr6jCw8Y_2LHDz-gp_-6KM"
}
}
cnf 聲明包含憑證的 SHA-256 指紋,以 Base64Url 編碼。
瞭解目前的限制
在實作 mTLS PoP 令牌綁定前,請先檢視以下限制條件。
僅支援應用程式令牌
目前 Token 綁定 僅支援應用程式專用的 token。 不支援委派(使用者)代幣。
設定協定方案
ProtocolScheme屬性必須明確設定為"MTLS_POP",才能啟用權杖綁定。 若未設定,則使用標準承載者認證。
符合證書要求
- 憑證必須在
ClientCredentials中設定,並將SendX5c設為true - 證書必須在取得代幣時可取得
排除常見問題
請依照以下指引診斷並解決令牌綁定問題。
解決常見問題
1.「令牌中缺少『cnf』聲明」
原因:令牌綁定未正確設定,或令牌為標準持有人令牌。
解決方案:驗證 ProtocolScheme 是否已設定為 "MTLS_POP",且 RequestAppToken 是否為 true。
{
"DownstreamApi": {
"ProtocolScheme": "MTLS_POP", // ensure this is set
"RequestAppToken": true
}
}
2. 「證書指紋不符」
原因:API 所呈現的憑證與用於憑證取得的憑證不符。
解決方案:
- 確認同一憑證同時用於憑證取得與 API 呼叫
- 檢查
ClientCredentials中的憑證載入設定 - 確保證書未過期或續期
3.「一張用於代幣綁定的證書缺失」
Cause:Microsoft Entra設定中未設定憑證。
解決方案:在你的 ClientCredentials 設定中新增憑證並設定 SendX5c 為 true。
{
"AzureAd": {
"ClientCredentials": [
{
"SourceType": "StoreWithDistinguishedName",
"CertificateStorePath": "CurrentUser/My",
"CertificateDistinguishedName": "CN=YourCertificate"
}
],
"SendX5c": true // required for token binding
}
}
4. 「要使用令牌綁定,必須啟用應用程式令牌取得功能」
原因: RequestAppToken 未設定為 true。
解決方案:在你的選項中將RequestAppToken設定為true。
var options = new DownstreamApiOptions
{
ProtocolScheme = "MTLS_POP",
RequestAppToken = true, // must be true
};
除錯令牌綁定
請使用以下技術來調查代幣綁定問題。
啟用詳細記錄
新增以下設定以啟用 Microsoft.Identity.Web 的偵錯層級記錄。
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.Identity.Web": "Debug"
}
}
}
檢查代幣權利要求
請使用以下代碼列出令牌中的所有宣告並檢查其中是否包含 cnf 宣告。
var handler = new JsonWebTokenHandler();
var token = handler.ReadJsonWebToken(tokenString);
foreach (var claim in token.Claims)
{
Console.WriteLine($"{claim.Type}: {claim.Value}");
}
// Look for 'cnf' claim with x5t#S256
var cnfClaim = token.Claims.FirstOrDefault(c => c.Type == "cnf");
驗證證書指紋
請使用以下代碼計算並顯示憑證的 SHA-256 指紋以便比較。
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using Microsoft.IdentityModel.Tokens;
var cert = new X509Certificate2("path/to/cert.pfx", "password");
using var sha256 = SHA256.Create();
var hash = sha256.ComputeHash(cert.RawData);
var thumbprint = Base64UrlEncoder.Encode(hash);
Console.WriteLine($"Certificate thumbprint: {thumbprint}");
遵守安全指引
在實作令牌綁定時,請遵循以下安全措施。
管理憑證的安全性
- 安全儲存:使用 Azure Key Vault 或安全的憑證存儲庫
- 定期輪調:實施證書輪調程序
- 監控過期:設定憑證過期警示
- 限制存取權限:限制誰可以存取憑證私鑰
安全網路連線
- 要求 TLS 1.2+:確保所有連線使用現代 TLS 版本
- 驗證憑證:在伺服器上實施適當的憑證驗證
- 使用強密碼:配置安全密碼套件
安全處理標記
- 短壽命:使用短命代幣(建議:1小時)
- 妥善儲存:切勿記錄或公開代幣
- 徹底驗證:檢查所有主張、到期及綁定
遵循最佳做法
部署 mTLS PoP 令牌綁定時,請牢記以下建議。
- 一定要用 HTTPS:mTLS PoP 需要安全傳輸
- 使用將私鑰資料儲存在硬體中的憑證,例如TPM:使用硬體而非軟體安全性以獲得更好的保護
- 實施正確的錯誤處理:優雅地處理憑證與令牌錯誤
- 監控憑證到期:自動化憑證續期
- 每個環境使用不同的憑證:開發、測試和生產證書
- 記錄安全事件:追蹤令牌綁定失敗與憑證不符
- 測試憑證輪替:確保你的應用程式能處理憑證更新
- 記錄你的設定:保持清楚的憑證要求文件
相關內容
探索範例程式碼
完整的 mTLS PoP 令牌綁定工作範例可在倉庫中取得:
-
客戶應用:
tests/DevApps/MtlsPop/MtlsPopClient -
Web API 伺服器:
tests/DevApps/MtlsPop/MtlsPopWebApi
這些範例展示了:
- 完整的用戶端與伺服器配置
- 憑證綁定的令牌取得
- 自訂認證處理程式實作
- 憑證驗證與指紋驗證