JwtHelper.cs 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  1. using Microsoft.AspNetCore.Authentication;
  2. using Microsoft.AspNetCore.Authentication.Cookies;
  3. using Microsoft.AspNetCore.Http;
  4. using NetTaste;
  5. using OASystem.API.OAMethodLib.JuHeAPI;
  6. using OASystem.Domain.Dtos.Business;
  7. using SqlSugar.Extensions;
  8. using System.IdentityModel.Tokens.Jwt;
  9. using System.Security.Claims;
  10. using static NPOI.HSSF.Util.HSSFColor;
  11. namespace OASystem.API.OAMethodLib
  12. {
  13. public class JWTHelper
  14. {
  15. public class JwtHelper
  16. {
  17. private readonly static IHttpContextAccessor _httpContextAccessor = AutofacIocManager.Instance.GetService<IHttpContextAccessor>();
  18. /// <summary>
  19. /// 颁发JWT字符串
  20. /// </summary>
  21. /// <param name="tokenModel"></param>
  22. /// <returns></returns>
  23. public static async Task<string> IssueJwtAsync(TokenModelJwt tokenModel)
  24. {
  25. // appsettign.json 操作类
  26. string iss = "OASystem.com";
  27. string aud = "OASystem.com";
  28. string secret = AppSettingsHelper.Get("JwtSecurityKey");
  29. var claims = new List<Claim>
  30. {
  31. /*
  32. * 特别重要:
  33. 1、这里将用户的部分信息,比如 uid 存到了Claim 中,如果你想知道如何在其他地方将这个 uid从 Token 中取出来,请看下边的SerializeJwt() 方法,或者在整个解决方案,搜索这个方法,看哪里使用了!
  34. 2、你也可以研究下 HttpContext.User.Claims ,具体的你可以看看 Policys/PermissionHandler.cs 类中是如何使用的。
  35. */
  36. new Claim(JwtRegisteredClaimNames.Jti, tokenModel.UserId.ToString()),
  37. //new Claim(JwtRegisteredClaimNames.GivenName, tokenModel.UserName),
  38. new Claim("UserName", tokenModel.UserName),
  39. //new Claim("UserId", tokenModel.UserId.ToString()),
  40. new Claim(JwtRegisteredClaimNames.Iat, $"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}"),
  41. new Claim(JwtRegisteredClaimNames.Nbf,$"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}") ,
  42. //这个就是过期时间,目前是过期7200秒,可自定义,注意JWT有自己的缓冲过期时间
  43. new Claim(JwtRegisteredClaimNames.Exp,$"{new DateTimeOffset(DateTime.Now.AddSeconds(7200)).ToUnixTimeSeconds()}"),
  44. new Claim(JwtRegisteredClaimNames.Iss,iss),
  45. new Claim(JwtRegisteredClaimNames.Aud,aud),
  46. //new Claim(ClaimTypes.Role,tokenModel.Role),//为了解决一个用户多个角色(比如:Admin,System),用下边的方法
  47. };
  48. // 可以将一个用户的多个角色全部赋予;
  49. claims.AddRange(tokenModel.Role.Split(',').Select(s => new Claim(ClaimTypes.Role, s)));
  50. //秘钥 (SymmetricSecurityKey 对安全性的要求,密钥的长度太短会报出异常)
  51. var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secret));
  52. var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
  53. var jwt = new JwtSecurityToken(
  54. issuer: iss,
  55. claims: claims,
  56. signingCredentials: creds
  57. //,expires:DateTime.Now.AddMinutes(1)
  58. );
  59. // var indentity = new ClaimsIdentity(claims, "FMGJ-OASystem");
  60. // var principal = new ClaimsPrincipal(indentity);
  61. //await _httpContextAccessor.HttpContext?.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal);
  62. var jwtHandler = new JwtSecurityTokenHandler();
  63. var encodedJwt = jwtHandler.WriteToken(jwt);
  64. return encodedJwt;
  65. }
  66. /// <summary>
  67. /// 解析
  68. /// </summary>
  69. /// <param name="jwtStr"></param>
  70. /// <returns></returns>
  71. public static TokenModelJwt SerializeJwt(string jwtStr)
  72. {
  73. var jwtHandler = new JwtSecurityTokenHandler();
  74. JwtSecurityToken jwtToken = jwtHandler.ReadJwtToken(jwtStr);
  75. object role,userName;
  76. try
  77. {
  78. jwtToken.Payload.TryGetValue(ClaimTypes.Role, out role);
  79. jwtToken.Payload.TryGetValue("UserName", out userName);
  80. }
  81. catch (Exception e)
  82. {
  83. Console.WriteLine(e);
  84. throw;
  85. }
  86. var tm = new TokenModelJwt
  87. {
  88. UserId = (jwtToken.Id).ObjToInt(),
  89. UserName = userName != null ? userName.ObjToString() : "",
  90. Role = role != null ? role.ObjToString() : "",
  91. };
  92. return tm;
  93. }
  94. }
  95. /// <summary>
  96. /// 令牌
  97. /// </summary>
  98. public class TokenModelJwt
  99. {
  100. /// <summary>
  101. /// Id
  102. /// </summary>
  103. public int UserId { get; set; }
  104. public string UserName { get; set; }
  105. public string Role { get; set; } = "Admin";
  106. /// <summary>
  107. /// 过期时间,默认过期7200秒
  108. /// 注意JWT有自己的缓冲过期时间
  109. /// </summary>
  110. public int ExpirationTime { get; set; } = 7200;
  111. }
  112. }
  113. }