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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  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 UserDboAuth GetUserDbo(string username, string salt)
  40. {
  41. return null;
  42. }
  43. /// <summary>
  44. /// Attempts to verify user token
  45. /// </summary>
  46. /// <param name="request">The HTTP request</param>
  47. /// <param name="cancellationToken">Token used for cancelation</param>
  48. /// <returns>The HTTP response</returns>
  49. protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
  50. {
  51. HttpStatusCode statusCode;
  52. string token;
  53. if (!TryRetrieveToken(request, out token))
  54. {
  55. return base.SendAsync(request, cancellationToken);
  56. }
  57. try
  58. {
  59. JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler
  60. {
  61. Configuration = new SecurityTokenHandlerConfiguration()
  62. {
  63. MaxClockSkew = new TimeSpan(0, 1, 0)
  64. }
  65. };
  66. var stringValidator = "";//AuthProvider.Instance.GetValidatorString();
  67. TokenValidationParameters validationParameters = new TokenValidationParameters()
  68. {
  69. RequireSignedTokens = true,
  70. RequireExpirationTime = true,
  71. ValidAudience = stringValidator,
  72. ValidateIssuerSigningKey = true,
  73. ValidIssuer = "urn:" + stringValidator,
  74. IssuerSigningToken = new BinarySecretSecurityToken(Convert.FromBase64String(/*AuthProvider.Instance.GetCredentialKey()*/""))
  75. };
  76. SecurityToken validateToken;
  77. ClaimsPrincipal claim = tokenHandler.ValidateToken(token, validationParameters, out validateToken);
  78. Thread.CurrentPrincipal = claim;
  79. var name = ((ClaimsIdentity)claim.Identity).Claims.FirstOrDefault(x => x.Type == ClaimTypes.Name);
  80. var salt = ((ClaimsIdentity)claim.Identity).Claims.FirstOrDefault(x => x.Type == ClaimTypes.Authentication);
  81. if (name == null || salt == null)
  82. statusCode = HttpStatusCode.Unauthorized;
  83. else
  84. {
  85. var user = GetUserDbo(name.Value, salt.Value);
  86. if (user == null)
  87. statusCode = HttpStatusCode.Unauthorized;
  88. else
  89. return base.SendAsync(request, cancellationToken);
  90. }
  91. }
  92. catch (Exception e)
  93. {
  94. statusCode = HttpStatusCode.Unauthorized;
  95. }
  96. return Task<HttpResponseMessage>.Factory.StartNew(() =>
  97. new HttpResponseMessage(statusCode), cancellationToken);
  98. }
  99. }
  100. }