services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = Configuration["Jwt:Issuer"],
ValidAudience = Configuration["Jwt:Audience"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
};
});
以上代码中,我们使用AddAuthentication来添加JWT授权,并指定授权方案为JwtBearerDefaults.AuthenticationScheme。然后,我们使用AddJwtBearer来添加JWT Bearer授权程序,并配置TokenValidationParameters,该参数允许我们指定哪些值需要验证以确保JWT有效。
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
public class MyProtectedController : ControllerBase
{
// 使用授权验证进行身份验证和授权
[HttpGet]
public IActionResult Get()
{
// 可以在这里访问受保护的资源
return Ok();
}
}
使用Authorize特性,我们指定了授权方案为JwtBearerDefaults.AuthenticationScheme。这表示只有经过授权才能访问此控制器的操作。可以在该操作中访问受保护资源。
private string GenerateJwtToken(User user)
{
var claims = new List
{
new Claim(JwtRegisteredClaimNames.Sub, user.Email),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
new Claim(ClaimTypes.Role, "Admin")
};
var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]));
var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
var expires = DateTime.Now.AddDays(Convert.ToInt32(Configuration["Jwt:ExpireDays"]));
var token = new JwtSecurityToken(
Configuration["Jwt:Issuer"],
Configuration["Jwt:Audience"],
claims,
expires: expires,
signingCredentials: credentials
);
return new JwtSecurityTokenHandler().WriteToken(token);
}
以上代码中,我们生成一个包含用户信息和声明的JWT令牌,其中我们使用SymmetricSecurityKey和SigningCredentials来对令牌进行加密,以确保令牌不会被篡改。最后,我们返回写入的令牌。
上一篇:ASP.NETCore中基于HTTP协议限制HTTP请求的方法
下一篇:ASP.NETCore中JWT授权失败,提示“AuthenticationScheme:Bearerwasnotauthenticated”错误。