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.

TokenManager.cs 2.0KB

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