开启 JWT 验证的两种方式:
1、通过配置文件启动,文件位置:Setting/Jwt.json
{ "Expiration": 1200, "Security": "此信息需要加密,建议加密前的字符不要太短,16位以上。", "ErrorMessage": "Unauthorized", "Issuer": "Issuer", "Audience": "Audience" }
2、Program.cs 文件中添加配置,优先级低于 Jwt.json 文件
FlexibleCoreInit.Build(args, (opt, cft) => { opt.SetJwtSetting(x => { x.Expiration = 1200; x.Security = "此信息需要加密,建议加密前的字符不要太短,16位以上。"; x.ErrorMessage = "Unauthorized"; x.Issuer = "Issuer"; x.Audience = "Audience"; }); }).Run();
在需要 JWT 验证的 Controller 上添加 Authorize 特性。在不需要 JWT 验证的 Controller 上添加 AllowAnonymous 特性。
[Route("api/[controller]")] [ApiController] [Authorize] public class ValuesController : ControllerBase { [HttpGet] [AllowAnonymous] public IEnumerableGet() { return new string[] { "value1", "value2" }; } }
生成 JWT
[AllowAnonymous] [HttpPost("login")] public async TaskLogin([FromBody] LoginDto dto) { TokenModelJwt tokenModel = new TokenModelJwt { Id = 1, Name = "User", DisplayName = "UserName", Role = "admin" }; return AspNetJwtHelper.IssueJwt(tokenModel); }
解析 JWT
TokenModelJwt tokenModel = AspNetJwtHelper.SerializeJwt(jwtToken); string token = AspNetJwtHelper.IssueJwt(tokenModel);
其中,TokenModelJwt 对象中,Id 保存用户主键,可以通过以下方式在 Controller 中获取:
User.FindFirstValue(JwtRegisteredClaimNames.Jti);