在ASP.NET Core 7中,实现JWT授权可以通过以下步骤进行。假设你已经安装了Microsoft.AspNetCore.Authentication.JwtBearer
包。
Startup.cs
文件中,添加必要的命名空间:using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
ConfigureServices
方法中,配置JWT授权: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
方法中启用JWT授权:app.UseAuthentication();
var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("your_secret_key"));
var signingCredentials = new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
issuer: "your_issuer",
audience: "your_audience",
expires: DateTime.Now.AddHours(1),
signingCredentials: signingCredentials,
claims: new[]
{
new Claim("claim_name", "claim_value")
});
var tokenString = new JwtSecurityTokenHandler().WriteToken(token);
[Authorize]
属性:[Authorize]
public class MyController : ControllerBase
{
// ...
}
现在,当用户访问需要授权的接口时,系统会验证JWT令牌中的声明是否满足要求,如果满足则通过授权,否则会返回401未授权错误。
注意:上述代码示例中的"your_issuer"、"your_audience"和"your_secret_key"应根据实际情况进行替换。