本文承接上一篇在Asp.Net Core Web API中使用JWT鉴权(1)创建鉴权中心。
1、创建Asp.Net Core Web API项目
这里使用的环境是VS2019 + .Net Core 3.1。
2、在Startup中注册JWT鉴权
(1) 使用Nuget安装Microsoft.AspNetCore.Authentication.JwtBearer。
(2) 注册JWT鉴权
#region 注册JWT鉴权 var issuer = Configuration["issuer"]; var audience = Configuration["audience"]; var securityKey = Configuration["SecurityKey"]; services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) //默认授权机制名称 .AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, //是否验证Issuer ValidateAudience = true, //是否验证Audience ValidateLifetime = true, //是否验证失效时间 ValidateIssuerSigningKey = true, //是否验证IssuerSigningKey ValidAudience = audience, ValidIssuer = issuer, IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(securityKey)), //自定义校验规则:新登录后,之前的token无效 //AudienceValidator = (audiences, securityToken, validationParameters) => //{ // return audiences != null && audiences.FirstOrDefault().Equals(audience); //} }; }); #endregion
(3) 启用鉴权中间件
//启用鉴权中间件 app.UseAuthentication();
3、添加JWT配置信息(appsettings.json)
"issuer": "http://localhost:9527", "audience": "http://localhost:9527", "SecurityKey": "4A9A70D2-B8AD-42E1-B002-553BDEF4E76F"
注意issuer、audience、SecurityKey要和鉴权中心的配置保持一致。
4、在控制器的接口中使用[Authorize]属性
using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using System; using System.Linq; using System.Security.Claims; namespace TestWebApi.Controllers { [Route("api/[controller]")] [ApiController] public class TestController : ControllerBase { [HttpGet] [Route("GetAuthData")] [Authorize] public IActionResult GetAuthData() { var claims = HttpContext.AuthenticateAsync().Result.Principal.Claims; var name = claims.FirstOrDefault(t => t.Type.Equals(ClaimTypes.Name))?.Value; var exp = claims.FirstOrDefault(t => t.Type.Equals("exp"))?.Value; var expDateTime = DateTime.Now; if (!string.IsNullOrWhiteSpace(exp)) { long expValue; if (long.TryParse(exp, out expValue)) { expDateTime = TimeZoneInfo.ConvertTime(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc), TimeZoneInfo.Local); expDateTime = expDateTime.AddSeconds(expValue); } } Console.WriteLine($"name: {name}, expDateTime: {expDateTime}"); return new JsonResult(new { ExpDateTime = expDateTime, Name = name, Data = "已授权", Type = "GetAuthorizeData" }); } } }
5、运行
(1) 运行Web API项目,在Postman中输入http://localhost:5000/api/Test/GetAuthData,正常情况下会有401 Unauthorized错误。
(2) 在Postman的Authorization选项卡中选择"Bearer Token",并输入鉴权中心登录后的token,正常情况下会输出类似下面的内容:
{ "expDateTime": "2021-02-22T10:02:25+08:00", "name": "admin", "data": "已授权", "type": "GetAuthorizeData" }