当代理使用自己的标识(而不是充当用户的委托)执行作时,它们称为 自治代理。 若要执行作,代理必须先使用 Microsoft Entra ID 进行身份验证,然后使用其代理标识(代理 ID)获取访问令牌。 本文指导你完成使用两个步骤在 Microsoft Entra ID 中为代理标识请求访问令牌的过程。 你将:
- 获取代理标识蓝图的令牌。
- 将代理标识蓝图令牌交换为代理 ID 令牌。
先决条件
在实现代理令牌身份验证之前,请确保:
获取客户端凭据详细信息。 这可能是客户端机密、证书或用作联合标识凭据的托管标识。
警告
由于安全风险,客户端机密不应在生产环境中用作代理标识蓝图的客户端凭据。 而是使用更安全的身份验证方法 ,例如将联合标识凭据(FIC)与托管标识 或客户端证书配合使用。 这些方法通过消除直接在应用程序配置中存储敏感机密的需要,从而提供增强的安全性。
{
"AzureAd": {
"Instance": "https://login.microsoftonline.com/",
"TenantId": "<your-tenant-id>",
"ClientId": "<agent-blueprint-clientid>",
"ClientCredentials": [
{
"SourceType": "ClientSecret",
"ClientSecret": "your-client-secret"
}
]
}
}
请求代理标识蓝图的令牌
请求代理标识蓝图的令牌时,请在参数中 fmi_path 提供代理 ID 的客户端 ID。
client_secret在本地开发期间提供参数而不是client_assertionclient_assertion_type使用客户端密码作为凭据时。 对于证书和托管标识,请使用 client_assertion 和 client_assertion_type。
POST https://login.microsoftonline.com/<my-test-tenant>/oauth2/v2.0/token
Content-Type: application/x-www-form-urlencoded
client_id=<agent-blueprint-client-id>
&scope=api://AzureADTokenExchange/.default
&grant_type=client_credentials
&client_secret=<client-secret>
&fmi_path=<agent-identity-client-id>
使用 Microsoft.Identity.Web,无需显式请求代理标识蓝图的令牌。
Microsoft.Identity.Web 为你执行该作。
dotnet add package Microsoft.Identity.Web
dotnet add package Microsoft.Identity.Web.AgentIdentities
请求代理标识令牌
拥有代理标识蓝图令牌(T1)后,使用它来请求代理标识令牌。
POST https://login.microsoftonline.com/<my-test-tenant>/oauth2/v2.0/token
Content-Type: application/x-www-form-urlencoded
client_id=<agent-identity-client-id>
&scope=https://graph.microsoft.com/.default
&grant_type=client_credentials
&client_assertion_type=urn:ietf:params:oauth:client-assertion-type:jwt-bearer
&client_assertion=<agent-blueprint-token-T1>
Microsoft.Identity.Web 处理令牌获取协议的详细信息,前提是你在应用程序的初始化时使用服务集合中的新 services.AddAgentIdentities() 内容。
初始化应用程序:
// Program.cs
using Microsoft.AspNetCore.Authorization;
using Microsoft.Identity.Abstractions;
using Microsoft.Identity.Web;
using Microsoft.Identity.Web.Resource;
using Microsoft.Identity.Web.TokenCacheProviders.InMemory;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddMicrosoftIdentityWebApiAuthentication(builder.Configuration);
builder.Services.AddAgentIdentities();
builder.Services.AddInMemoryTokenCaches();
使用 .WithAgentIdentity() 模式请求访问令牌:
// Get the service to call the downstream API (preconfigured in the appsettings.json file)
IAuthorizationHeaderProvider authorizationHeaderProvider = serviceProvider.GetService<IAuthorizationHeaderProvider>();
AuthorizationHeaderProviderOptions options = new AuthorizationHeaderProviderOptions().WithAgentIdentity("<agent-identity-client-id>");
// Request agent identity tokens
string authorizationHeaderWithAppTokens = await authorizationHeaderProvider.CreateAuthorizationHeaderForAppAsync("https://resource/.default", options);
// The authHeader contains "Bearer " + the access token (or another protocol
// depending on the options)
相关内容