1.安装jwt nuget包
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="6.0.25" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="7.0.3" />
1.1创建jwt配置类
namespace webapi
{
/// <summary>
/// 有效载荷配置信息
/// </summary>
public class JwtTokenOption
{
/// <summary>
/// Token 过期时间,默认为60分钟
/// </summary>
public int TokenExpireTime { get; set; } = 60;
/// <summary>
/// 接收人
/// </summary>
public string Audience { get; set; }
/// <summary>
/// 秘钥(RSA)
/// </summary>
public string SecurityKey { get; set; }
/// <summary>
/// 签发人
/// </summary>
public string Issuer { get; set; }
}
}
2.配置jwt信息
//注入jwt配置服务
var jwtOption = builder.Configuration.GetSection("JwtTokenOption");
builder.Services.Configure<JwtTokenOption>(jwtOption);
JwtTokenOption jwtTokenOption = jwtOption.Get<JwtTokenOption>();
//认证
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(jwtBearerOptions =>
{
jwtBearerOptions.TokenValidationParameters = new TokenValidationParameters
{
ValidAlgorithms = new string[] { "HS256" },//对称加密
IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(jwtTokenOption.SecurityKey)),//拿到SecurityKey
ValidateIssuer = true,//是否验证Issuer
ValidateAudience = true,//是否验证Audience
ValidateLifetime = false,//是否验证失效时间
ClockSkew = TimeSpan.FromSeconds(30),//时钟脉冲相位差
ValidateIssuerSigningKey = true,//是否验证SecurityKey
ValidAudience = jwtTokenOption.Audience,//Audience
ValidIssuer = jwtTokenOption.Issuer,//Issuer,这两项和前面签发jwt的设置一致
};
});;
3.生成token
[HttpPost("{username}")]
[AllowAnonymous]
public IActionResult tokensc()
{
// 有效载荷,大家可以自己写,爱写多少写多少;尽量避免敏感信息
var claims = new[]
{
new Claim(ClaimTypes.Name, "pzx"),
new Claim("NickName","aa"),
new Claim("Role","Administrator"),//传递其他信息
};
// payload 中的信息声明
var jwtSecurityToken = new JwtSecurityToken(
claims: claims,
expires: DateTime.Now.AddMinutes(_jwtTokenOption.TokenExpireTime),
signingCredentials: new SigningCredentials(new SymmetricSecurityKey(Encoding.ASCII.GetBytes(_jwtTokenOption.SecurityKey)), SecurityAlgorithms.HmacSha256),
issuer: _jwtTokenOption.Issuer,
audience: _jwtTokenOption.Audience);
var tokenString = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken); ;
return Ok(tokenString);
}
4.在需要的控制器或方法上,使用过滤器(只有token解析成功,没有过期才可以访问接口)
[Authorize]
[HttpGet]
public IActionResult Get(){
return ok();
}
5.可以结合IdentityService4身份认证框架使用