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

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