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 3.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  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. var claim = TokenManager.ParseToken(token);
  61. Thread.CurrentPrincipal = claim;
  62. var name = ((ClaimsIdentity)claim.Identity).Claims.FirstOrDefault(x => x.Type == ClaimTypes.Name);
  63. var salt = ((ClaimsIdentity)claim.Identity).Claims.FirstOrDefault(x => x.Type == ClaimTypes.Authentication);
  64. if (name == null || salt == null)
  65. {
  66. OpResult<bool>.Error(ResultStatus.LoginError, string.Format("Incomplete token; username is present: {0}; salt is present {1}", name != null, salt != null)).Log();
  67. statusCode = HttpStatusCode.Unauthorized;
  68. }
  69. else
  70. {
  71. var user = GetUserDbo(name.Value, salt.Value);
  72. if (user == null)
  73. {
  74. OpResult<bool>.Error(ResultStatus.LoginError,
  75. string.Format("Username {0} not found", name.Value)).Log();
  76. statusCode = HttpStatusCode.Unauthorized;
  77. }
  78. else
  79. {
  80. UserStorage.BasicUserDbo = user;
  81. return base.SendAsync(request, cancellationToken);
  82. }
  83. }
  84. }
  85. catch (Exception e)
  86. {
  87. OpResult<bool>.Error(ResultStatus.LoginError, e).Log();
  88. statusCode = HttpStatusCode.Unauthorized;
  89. }
  90. return Task<HttpResponseMessage>.Factory.StartNew(() =>
  91. new HttpResponseMessage(statusCode), cancellationToken);
  92. }
  93. }
  94. }