华恒Mes鼎捷代码
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

61 lines
1.7 KiB

5 months ago
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using JWT;
  6. using JWT.Algorithms;
  7. using JWT.Serializers;
  8. using JWT.Builder;
  9. using JWT.Exceptions;
  10. namespace WebApplication1
  11. {
  12. public static class JwtHelper
  13. {
  14. static string secret = System.Configuration.ConfigurationManager.AppSettings["secret"].ToString();
  15. public static string CreateTocken(string UserName)
  16. {
  17. var tocken=JwtBuilder.Create().WithAlgorithm(new HMACSHA256Algorithm())
  18. .ExpirationTime(DateTime.Now.AddMinutes(10))
  19. .WithSecret(secret)
  20. .AddClaim("UserName",UserName)
  21. .AddClaim("DateTime",DateTime.Now)
  22. .WithValidationParameters(
  23. new ValidationParameters
  24. {
  25. ValidateExpirationTime = true,
  26. }).Encode(); ;
  27. return tocken;
  28. }
  29. public static bool Validate(string tocken)
  30. {
  31. try
  32. {
  33. var mes = JwtBuilder.Create()
  34. .WithAlgorithm(new HMACSHA256Algorithm())
  35. .WithSecret(secret)
  36. .Decode(tocken);
  37. return true;
  38. }
  39. catch (TokenNotYetValidException )
  40. {
  41. throw new Exception("Token is not valid yet");
  42. }
  43. catch (TokenExpiredException)
  44. {
  45. throw new Exception("Token has expired");
  46. }
  47. catch (SignatureVerificationException)
  48. {
  49. throw new Exception("Token has invalid signature");
  50. }
  51. }
  52. }
  53. }