我想根据 docs 配置受 Microsoft Entra ID 保护的 ASP.Net Core 8.0 API。该 API 将仅由守护程序应用程序调用。
在 Visual Studio 2022 中,我创建了一个新的 Asp.Net Core 8.0 Web API 项目,启用了身份验证,使用 Microsoft 身份平台作为身份验证类型。
在我的默认
WeatherForecastController
中,我得到了[Authorize(Roles = "MyApp.Read.All")]
,这是我在Azure中的客户端和API应用程序注册中配置的相同应用程序角色。
在我的 Program.cs 中我得到了
builder.Services
.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("AzureAd"));
其中
appsettings.json
似乎在 AzureAd
对象中具有适合我的租户的值。例如Instance
、TenantId
等
使用这些默认设置,我实际上需要使用我在
here找到的
JwtBearerOptions
来验证令牌吗?
我的问题是关于如何确保特定的验证 诸如 aud 之类的令牌声明。我现有的配置是否已解决这一问题,或者 我需要设置 JwtBearerOptions 吗?
是的,它会自动验证特定的令牌声明,例如
aud
(受众)。您当前的配置检查是否只有经过身份验证且具有有效令牌的请求才能访问您的 API。但是,当您想要验证特定的令牌声明(例如 aud
(受众))时,您可能需要一些额外的配置。
默认情况下,当您使用
.AddMicrosoftIdentityWebApi
配置身份验证时,它会设置 JWT Bearer 令牌中间件来验证多个标准声明,例如 iss
(颁发者)、aud
(受众)、nbf
(之前没有)、和 exp
(到期)等。这意味着默认情况下会检查受众 (aud
) 声明,以确保其与您的 API 标识符(应用程序 ID URI)匹配。但对于自定义令牌验证,您需要使用 JwtBearerOptions
。
以下是示例代码:
builder.Services
.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("AzureAd"),
jwtBearerOptions =>
{
//Custom validation for the audience
jwtBearerOptions.TokenValidationParameters.ValidAudience = "your-audience-uri";
jwtBearerOptions.TokenValidationParameters.NameClaimType = "preferred_username";
jwtBearerOptions.Events = new JwtBearerEvents
{
OnTokenValidated = context =>
{
var claims = context.Principal.Claims;
var audience = claims.FirstOrDefault(c => c.Type == "aud")?.Value;
if (audience != "expected-audience-value")
{
context.Fail("Invalid audience");
}
return Task.CompletedTask;
}
};
});
这里是您可以考虑作为参考的官方文档,它指导您如何在应用程序中自定义 JWT 令牌的处理: