在ASP.NET Core 2.1中设置自定义声明的方法如下所示:
Startup.cs
文件中配置JWT认证服务。添加以下代码到ConfigureServices
方法中:services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = "your_issuer",
ValidAudience = "your_audience",
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("your_secret_key")),
};
});
Configure
方法中启用认证中间件。添加以下代码到Configure
方法中:app.UseAuthentication();
var claims = new List
{
new Claim("custom_key", "custom_value")
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("your_secret_key"));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
issuer: "your_issuer",
audience: "your_audience",
claims: claims,
expires: DateTime.Now.AddMinutes(30),
signingCredentials: creds);
return new JwtSecurityTokenHandler().WriteToken(token);
在上述代码中,我们使用JwtSecurityToken
类来创建JWT令牌,并设置自定义声明。其中,"custom_key"
是自定义声明的键,"custom_value"
是自定义声明的值。
通过以上步骤,你就可以在ASP.NET Core 2.1应用程序中设置自定义声明并生成JWT令牌了。