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

TokenValidationHandler.cs 3.7KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. using System;
  2. using System.IdentityModel.Tokens;
  3. using System.Linq;
  4. using System.Net;
  5. using System.Net.Http;
  6. using System.Security.Claims;
  7. using System.ServiceModel.Security.Tokens;
  8. using System.Threading;
  9. using System.Threading.Tasks;
  10. namespace iiie.Authentication.Business.JWT
  11. {
  12. /// <summary>
  13. /// Handler for token authentication
  14. /// </summary>
  15. public class TokenValidationHandler : DelegatingHandler
  16. {
  17. /// <summary>
  18. /// Gets the token from the HTTP AUthorization header
  19. /// </summary>
  20. /// <param name="request">The HTTP request</param>
  21. /// <param name="token">The variable to store the token</param>
  22. /// <returns>True if the token has been found, false otherwise</returns>
  23. private static bool TryRetrieveToken(HttpRequestMessage request, out string token)
  24. {
  25. token = null;
  26. var auth = request.Headers.Authorization;
  27. if (auth == null || auth.Scheme != "Bearer")
  28. return false;
  29. token = auth.Parameter;
  30. return true;
  31. }
  32. /// <summary>
  33. /// Attempts to verify user token
  34. /// </summary>
  35. /// <param name="request">The HTTP request</param>
  36. /// <param name="cancellationToken">Token used for cancelation</param>
  37. /// <returns>The HTTP response</returns>
  38. protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
  39. {
  40. HttpStatusCode statusCode;
  41. string token;
  42. if (!TryRetrieveToken(request, out token))
  43. {
  44. return base.SendAsync(request, cancellationToken);
  45. }
  46. try
  47. {
  48. JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler
  49. {
  50. Configuration = new SecurityTokenHandlerConfiguration()
  51. {
  52. MaxClockSkew = new TimeSpan(0, 1, 0)
  53. }
  54. };
  55. var stringValidator = AuthProvider.GetValidatorString();
  56. TokenValidationParameters validationParameters = new TokenValidationParameters()
  57. {
  58. RequireSignedTokens = true,
  59. RequireExpirationTime = true,
  60. ValidAudience = stringValidator,
  61. ValidateIssuerSigningKey = true,
  62. ValidIssuer = "urn:" + stringValidator,
  63. IssuerSigningToken = new BinarySecretSecurityToken(Convert.FromBase64String(AuthProvider.GetCredentialKey()))
  64. };
  65. SecurityToken validateToken;
  66. ClaimsPrincipal claim = tokenHandler.ValidateToken(token, validationParameters, out validateToken);
  67. Thread.CurrentPrincipal = claim;
  68. var name = ((ClaimsIdentity)claim.Identity).Claims.FirstOrDefault(x => x.Type == ClaimTypes.Name);
  69. var salt = ((ClaimsIdentity)claim.Identity).Claims.FirstOrDefault(x => x.Type == ClaimTypes.Authentication);
  70. if (name == null || salt == null)
  71. statusCode = HttpStatusCode.Unauthorized;
  72. else
  73. {
  74. var user = GetUserDbo(name.Value, salt.Value);
  75. if (user == null)
  76. statusCode = HttpStatusCode.Unauthorized;
  77. else
  78. return base.SendAsync(request, cancellationToken);
  79. }
  80. }
  81. catch (Exception e)
  82. {
  83. statusCode = HttpStatusCode.Unauthorized;
  84. }
  85. return Task<HttpResponseMessage>.Factory.StartNew(() =>
  86. new HttpResponseMessage(statusCode), cancellationToken);
  87. }
  88. }
  89. }