代码如下:
using Newtonsoft.Json; using Simple_Asp.Net_Core.Dtos; using System.Collections.Generic; using System.Linq; using System.Security.Claims; namespace Simple_Asp.Net_Core.Extensions { public static class ClaimLoginUserExtensions { private const string USER = "User"; public static ClaimsIdentity GetClaimsIdentity(this UserProviderDto user) { return new ClaimsIdentity(new Claim[] { new Claim(USER, JsonConvert.SerializeObject(user)) }); } public static UserProviderDto GetLoginUser(this IEnumerable<Claim> claims) { var user = JsonConvert.DeserializeObject<UserProviderDto>(claims.Get(USER)); return user; } public static string Get(this IEnumerable<Claim> claims, string claimType) { return claims.Where(v => v.Type == claimType).First().Value; } } } 启动项目,调用api/OAuth接口获取Token 得到Token "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJVc2VyIjoie1wiSURcIjpudWxsLFwiTmFtZVwiOlwiYWRtaW5cIixcIlBob25lXCI6bnVsbCxcIk1haWxcIjpudWxsLFwiUGFzc3dvcmRcIjpcIjEyMzQ1NlwifSIsIm5iZiI6MTYxNDIzOTAwNSwiZXhwIjoxNjE0MjgyMjA1LCJpYXQiOjE2MTQyMzkwMDUsImF1ZCI6ImFkbWluXzIwMjEvMi8yNSDmmJ_mnJ_lm5sgMTU6NDM6MjUifQ.yrjK8qX45mNOQ3taecIc-QVaBDlN4QUOdBPRExvpejk" 将Token赋到我们的请求上,在swagger上可以直接配置,点击 Authorize 按钮 将Token附上,注意开头为Bearer (Bearer后面接着一个空格!):实例如下:
Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJVc2VyIjoie1wiSURcIjpudWxsLFwiTmFtZVwiOlwiYWRtaW5cIixcIlBob25lXCI6bnVsbCxcIk1haWxcIjpudWxsLFwiUGFzc3dvcmRcIjpcIjEyMzQ1NlwifSIsIm5iZiI6MTYxNDIzOTAwNSwiZXhwIjoxNjE0MjgyMjA1LCJpYXQiOjE2MTQyMzkwMDUsImF1ZCI6ImFkbWluXzIwMjEvMi8yNSDmmJ_mnJ_lm5sgMTU6NDM6MjUifQ.yrjK8qX45mNOQ3taecIc-QVaBDlN4QUOdBPRExvpejk 再点击 Authorize 按钮 调用/api/Commands请求 - 请求成功 代码编写与配置已经全部完成可以利用JWT在线解析工具( 将前面获取的JWT的信息解析出来
总结本文为Simple项目增加JWT(JSON Web Token)的应用,除了用户请求认证接口之外的其余请求都需要带着JWT,本文还简单的实现了用户单一登入,扩展类JWT.cs的AudienceValidator方法会判断用户使用的Token是否是最新的,如果用户重复登入则旧的Token会失效!目前只是简单的使用了静态变量来保存Token的信息,可以结合具体情况将Token保存至Redis或者数据库中。
JWT的更多配置可以参考官方API资料 https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.authentication.jwtbearer?view=aspnetcore-5.0
注意:源码调试过程中如果出现xml文件路径错误,需要参照第一章(后端项目搭建与Swagger配置步骤)Swagger配置“配置XML 文档文件”步骤,取消勾选然后再选中 ,将XML路径设置成与你的电脑路径匹配!
https://github.com/Impartsoft/Simple_Asp.Net_Core/tree/master/Simple_Asp.Net_Core 5.SDK Update %26 JWT
参考资料博客JWT(推荐学习) https://www.cnblogs.com/7tiny/archive/2019/06/13/11012035.html
官方资料 https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.authentication.jwtbearer?view=aspnetcore-5.0
jwt官方资料 https://jwt.io