Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

TokenManager.cs 2.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. using System;
  2. using System.Configuration;
  3. using System.IdentityModel.Tokens;
  4. using System.Security.Claims;
  5. namespace iiie.Authentication.Business.JWT
  6. {
  7. /// <summary>
  8. /// Token creation class
  9. /// </summary>
  10. public static class TokenManager
  11. {
  12. /// <summary>
  13. /// Create signing credentials to sign the token
  14. /// </summary>
  15. /// <returns>The credentials</returns>
  16. private static SigningCredentials CreateSigningCredentials()
  17. {
  18. string symmetricKey = ConfigurationManager.AppSettings["CredentialKey"];
  19. byte[] keybytes = Convert.FromBase64String(symmetricKey);
  20. SecurityKey securityKey = new InMemorySymmetricSecurityKey(keybytes);
  21. SigningCredentials signingCredentials =
  22. new SigningCredentials(securityKey,
  23. SecurityAlgorithms.HmacSha256Signature,
  24. SecurityAlgorithms.Sha256Digest);
  25. return signingCredentials;
  26. }
  27. /// <summary>
  28. /// Create a JWT token
  29. /// </summary>
  30. /// <param name="username">The user username</param>
  31. /// <param name="salt">The user salt</param>
  32. /// <returns>The token</returns>
  33. public static string GetToken(string username, string salt)
  34. {
  35. var stringValidator = ConfigurationManager.AppSettings["StringValidator"];
  36. JwtSecurityToken jst = new JwtSecurityToken("urn:" + stringValidator,
  37. stringValidator,
  38. new []
  39. {
  40. new Claim(ClaimTypes.Name, username),
  41. new Claim(ClaimTypes.Authentication, salt)
  42. }, null, DateTime.Now.AddDays(1),
  43. CreateSigningCredentials());
  44. JwtSecurityTokenHandler jh = new JwtSecurityTokenHandler();
  45. return jh.WriteToken(jst);
  46. }
  47. }
  48. }