JwtHelper.cs 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  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 _httpContext = 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.Name, tokenModel.UserName),
  38. new Claim(JwtRegisteredClaimNames.FamilyName, tokenModel.Department),
  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 jwtHandler = new JwtSecurityTokenHandler();
  60. var encodedJwt = jwtHandler.WriteToken(jwt);
  61. return encodedJwt;
  62. }
  63. /// <summary>
  64. /// 解析
  65. /// </summary>
  66. /// <param name="jwtStr"></param>
  67. /// <returns></returns>
  68. public static TokenModelJwt SerializeJwt(string jwtStr)
  69. {
  70. if (string.IsNullOrEmpty(jwtStr)) return null;
  71. jwtStr = jwtStr.Replace("Bearer ", "");
  72. if (string.IsNullOrEmpty(jwtStr)) return null;
  73. var jwtHandler = new JwtSecurityTokenHandler();
  74. JwtSecurityToken jwtToken = jwtHandler.ReadJwtToken(jwtStr);;
  75. object role,userName,department;
  76. try
  77. {
  78. jwtToken.Payload.TryGetValue(ClaimTypes.Role, out role);
  79. jwtToken.Payload.TryGetValue("family_name", out department);
  80. jwtToken.Payload.TryGetValue("name", out userName);
  81. }
  82. catch (Exception e)
  83. {
  84. Console.WriteLine(e);
  85. throw;
  86. }
  87. var tm = new TokenModelJwt
  88. {
  89. UserId = (jwtToken.Id).ObjToInt(),
  90. UserName = userName != null ? userName.ObjToString() : "",
  91. Department = department != null ? department.ObjToString() : "",
  92. Role = role != null ? role.ObjToString() : "",
  93. };
  94. return tm;
  95. }
  96. }
  97. /// <summary>
  98. /// 令牌
  99. /// </summary>
  100. public class TokenModelJwt
  101. {
  102. /// <summary>
  103. /// Id
  104. /// </summary>
  105. public int UserId { get; set; }
  106. public string UserName { get; set; }
  107. public string Department { get; set; } = "信息部";
  108. public string Role { get; set; } = "Admin";
  109. /// <summary>
  110. /// 过期时间,默认过期7200秒
  111. /// 注意JWT有自己的缓冲过期时间
  112. /// </summary>
  113. public int ExpirationTime { get; set; } = 7200;
  114. }
  115. }
  116. }