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.

TokenValidationHandler.cs 4.4KB

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