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.2KB

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