Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

TokenValidationHandler.cs 3.8KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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. OpResult<bool> error = null;
  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. error = OpResult<bool>.Error(ResultStatus.LoginError, string.Format("Incomplete token; username is present: {0}; salt is present {1}", name != null, salt != null), "Incomplete token").Log();
  67. }
  68. else
  69. {
  70. var user = GetUserDbo(name.Value, salt.Value);
  71. if (user == null)
  72. {
  73. error = OpResult<bool>.Error(ResultStatus.LoginError,
  74. string.Format("Username {0} not found", name.Value), "").Log();
  75. }
  76. else
  77. {
  78. UserStorage.BasicUserDbo = user;
  79. return base.SendAsync(request, cancellationToken);
  80. }
  81. }
  82. }
  83. catch (Exception e)
  84. {
  85. error = OpResult<bool>.Error(ResultStatus.LoginError, e, "Failed to validate token").Log();
  86. }
  87. var resp = request.CreateErrorResponse(HttpStatusCode.Unauthorized, error.PublicDetails);
  88. return Task<HttpResponseMessage>.Factory.StartNew(() => resp, cancellationToken);
  89. }
  90. }
  91. }