JWTUtils.cs 3.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. using JWT;
  2. using JWT.Algorithms;
  3. using JWT.Exceptions;
  4. using JWT.Serializers;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Linq;
  8. using System.Text;
  9. namespace CollectInformation.Tools
  10. {
  11. public class JWTUtils
  12. {
  13. /// <summary>
  14. /// 创建token
  15. /// </summary>
  16. /// <returns></returns>
  17. public static string CreateJwtToken(IDictionary<string, object> payload, string secret, IDictionary<string, object> extraHeaders = null)
  18. {
  19. IJwtAlgorithm algorithm = new HMACSHA256Algorithm();
  20. IJsonSerializer serializer = new JsonNetSerializer();
  21. IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
  22. IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder);
  23. var token = encoder.Encode(payload, secret);
  24. return token;
  25. }
  26. /// <summary>
  27. /// 校验解析token
  28. /// </summary>
  29. /// <returns></returns>
  30. public static string ValidateJwtToken(string token)
  31. {
  32. try
  33. {
  34. IJsonSerializer serializer = new JsonNetSerializer();
  35. IDateTimeProvider provider = new UtcDateTimeProvider();
  36. IJwtValidator validator = new JwtValidator(serializer, provider);
  37. IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
  38. IJwtAlgorithm alg = new HMACSHA256Algorithm();
  39. IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder, alg);
  40. string json = decoder.Decode(token);
  41. //校验通过,返回解密后的字符串
  42. return json;
  43. }
  44. catch (TokenExpiredException)
  45. {
  46. //表示过期
  47. return "expired";
  48. }
  49. catch (SignatureVerificationException)
  50. {
  51. //表示验证不通过
  52. return "invalid";
  53. }
  54. catch (Exception)
  55. {
  56. return "error";
  57. }
  58. }
  59. /// <summary>
  60. /// 校验解析token
  61. /// </summary>
  62. /// <returns></returns>
  63. public static string ValidateJwtToken(string token, string secret)
  64. {
  65. try
  66. {
  67. IJsonSerializer serializer = new JsonNetSerializer();
  68. IDateTimeProvider provider = new UtcDateTimeProvider();
  69. IJwtValidator validator = new JwtValidator(serializer, provider);
  70. IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
  71. IJwtAlgorithm alg = new HMACSHA256Algorithm();
  72. IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder, alg);
  73. var json = decoder.Decode(token, secret, true);
  74. //校验通过,返回解密后的字符串
  75. return json;
  76. }
  77. catch (TokenExpiredException)
  78. {
  79. //表示过期
  80. return "expired";
  81. }
  82. catch (SignatureVerificationException)
  83. {
  84. //表示验证不通过
  85. return "invalid";
  86. }
  87. catch (Exception)
  88. {
  89. return "error";
  90. }
  91. }
  92. }
  93. }