TokenHelper.cs 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. using Microsoft.IdentityModel.Tokens;
  2. using System.IdentityModel.Tokens.Jwt;
  3. using System.Security.Claims;
  4. using System.Text;
  5. namespace ERP.Framework.Security
  6. {
  7. public static class TokenHelper
  8. {
  9. /// <summary>
  10. /// 创建Token
  11. /// </summary>
  12. /// <param name="securityKey">密匙</param>
  13. /// <param name="userId">用户Id</param>
  14. /// <param name="expires">Token 过期时间</param>
  15. /// <param name="tokenId">tokenId</param>
  16. /// <returns></returns>
  17. public static string CreateToken(
  18. string securityKey
  19. , long userId
  20. , string userName
  21. , int expires
  22. , out string tokenId)
  23. {
  24. tokenId = Guid.NewGuid().ToString();
  25. var claims = new Claim[]
  26. {
  27. new Claim(JwtRegisteredClaimNames.UniqueName,tokenId),
  28. new Claim(JwtRegisteredClaimNames.NameId,userId.ToString()),
  29. new Claim(ClaimTypes.Name,userName)
  30. };
  31. var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(securityKey));
  32. var token = new JwtSecurityToken(
  33. issuer: "ERP",
  34. audience: "ERP",
  35. claims: claims,
  36. notBefore: DateTime.Now,
  37. expires: DateTime.Now.AddMinutes(expires),
  38. signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256)
  39. );
  40. return new JwtSecurityTokenHandler().WriteToken(token);
  41. }
  42. public static bool ValidateToken(
  43. string? token,
  44. string secutityKey)
  45. {
  46. if (token == null)
  47. {
  48. return false;
  49. }
  50. var tokenHandler = new JwtSecurityTokenHandler();
  51. var validationParameters = new TokenValidationParameters
  52. {
  53. ValidateIssuer = true, //是否验证Issuer
  54. ValidateAudience = true, //是否验证Audience
  55. ValidateLifetime = true, //是否验证失效时间---默认添加300s后过期
  56. ValidateIssuerSigningKey = true, //是否验证SecurityKey
  57. ClockSkew = TimeSpan.Zero,
  58. ValidIssuer = "ERP",
  59. ValidAudience = "ERP",
  60. IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secutityKey)),
  61. };
  62. try
  63. {
  64. tokenHandler.ValidateToken(token, validationParameters, out _);
  65. return true;
  66. }
  67. catch
  68. {
  69. return false;
  70. }
  71. }
  72. public static IEnumerable<Claim> GetClaims(string token)
  73. {
  74. var tokenHandler = new JwtSecurityTokenHandler();
  75. var jwtToken = tokenHandler.ReadJwtToken(token);
  76. return jwtToken.Claims;
  77. }
  78. }
  79. }