ASP.NET Core中使用JSON Web Token(JWT)进行身份验证时,Audience属性代表预期的JWT接收方。这个属性是可选的,如果有的话,它通常包含应用程序的客户端ID或名称作为接收方。
要设置和验证JWT的Audience属性,可以使用ASP.NET Core的Microsoft.AspNetCore.Authentication.JwtBearer包。在Startup.cs的ConfigureServices方法中,添加如下代码:
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
options.Audience = "Your audience";
options.Authority = "https://your-auth-server-url.com";
});
在上面的代码中,Audience属性设置为“Your audience”,这是您自己的值。Authority属性指定用于身份验证的JWT颁发者的URL。
要验证传入的JWT的Audience属性,可以使用以下代码示例:
[Authorize]
[HttpGet]
public IActionResult YourAction()
{
// Get the audience claim
var audience = User.Claims.FirstOrDefault(c => c.Type == JwtRegisteredClaimNames.Aud)?.Value;
if (audience != null && audience.Equals("Your audience"))
{
// Your action logic
return Ok();
}
else
{
return Forbid();
}
}
在上述示例中,我们首先获取身份验证的用户中的Audience声明,并将其与预期的值“Your audience”进行比较。如果它们匹配,我们将执行动作逻辑,否则我们将返回Forbid()。