JwtTokenHandler.cs 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. using System;
  2. using System.IdentityModel.Tokens.Jwt;
  3. using System.Linq;
  4. using System.Text;
  5. using Microsoft.Extensions.Configuration;
  6. using Microsoft.IdentityModel.Tokens;
  7. namespace jsonjumble.Library
  8. {
  9. public class JwtTokenHandler
  10. {
  11. private readonly IConfiguration Configuration;
  12. public JwtTokenHandler(IConfiguration configuration)
  13. {
  14. Configuration = configuration;
  15. }
  16. public JwtSecurityToken ParseToken(string token)
  17. {
  18. SecurityToken validatedToken;
  19. new JwtSecurityTokenHandler().ValidateToken(token, GetParameters(), out validatedToken);
  20. return validatedToken as JwtSecurityToken;
  21. }
  22. public TokenValidationParameters GetParameters()
  23. {
  24. return new TokenValidationParameters()
  25. {
  26. ValidateIssuerSigningKey = true,
  27. IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JwtSettings:SecretKey"])),
  28. ValidateIssuer = true,
  29. ValidIssuer = Configuration["JwtSettings:Issuer"],
  30. ValidateAudience = true,
  31. ValidAudience = Configuration["JwtSettings:Audience"],
  32. ValidateLifetime = true,
  33. ClockSkew = TimeSpan.FromMinutes(Configuration.GetValue<int>("JwtSettings:ExpirationInHours"))
  34. };
  35. }
  36. public string GetTokenValue(string token, string key)
  37. {
  38. var parsedToken = ParseToken(token);
  39. dynamic value;
  40. parsedToken.Payload.TryGetValue(key, out value);
  41. return value.ToString();
  42. }
  43. public string GetTokenPath(string token)
  44. {
  45. return GetTokenValue(token, "path");
  46. }
  47. }
  48. }