CredentialAuthenticator.cs 4.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. using System;
  2. using System.Text;
  3. using Best.HTTP.Request.Authentication;
  4. using Best.HTTP.Shared;
  5. namespace Best.HTTP.Request.Authenticators
  6. {
  7. /// <summary>
  8. /// An <see cref="IAuthenticator"/> implementation for HTTP Basic or Digest authentication.
  9. /// </summary>
  10. public class CredentialAuthenticator : IAuthenticator
  11. {
  12. /// <summary>
  13. /// Gets or sets the <see cref="Authentication.Credentials"/> associated with this authenticator.
  14. /// </summary>
  15. public Credentials Credentials { get; set; }
  16. /// <summary>
  17. /// Initializes a new instance of the CrendetialAuthenticator class with the specified <see cref="Authentication.Credentials"/>.
  18. /// </summary>
  19. /// <param name="credentials">The <see cref="Authentication.Credentials"/> to use for authentication.</param>
  20. /// <exception cref="ArgumentNullException">Thrown if <paramref name="credentials"/> is null.</exception>
  21. public CredentialAuthenticator(Credentials credentials)
  22. {
  23. if (credentials == null)
  24. throw new ArgumentNullException(nameof(credentials));
  25. this.Credentials = credentials;
  26. }
  27. /// <summary>
  28. /// Sets up the required headers for the HTTP request based on the provided credentials.
  29. /// </summary>
  30. /// <param name="request">The HTTP request for which headers should be added.</param>
  31. public void SetupRequest(HTTPRequest request)
  32. {
  33. HTTPManager.Logger.Information(nameof(CredentialAuthenticator), $"SetupRequest({request}, {Credentials?.Type})", request.Context);
  34. if (Credentials == null)
  35. return;
  36. switch (Credentials.Type)
  37. {
  38. case AuthenticationTypes.Basic:
  39. // With Basic authentication we don't want to wait for a challenge, we will send the hash with the first request
  40. request.SetHeader("Authorization", string.Concat("Basic ", Convert.ToBase64String(Encoding.UTF8.GetBytes(Credentials.UserName + ":" + Credentials.Password))));
  41. break;
  42. case AuthenticationTypes.Unknown:
  43. case AuthenticationTypes.Digest:
  44. var digest = DigestStore.Get(request.CurrentUri);
  45. if (digest != null)
  46. {
  47. string authentication = digest.GenerateResponseHeader(Credentials, false, request.MethodType, request.CurrentUri);
  48. if (!string.IsNullOrEmpty(authentication))
  49. request.SetHeader("Authorization", authentication);
  50. }
  51. break;
  52. }
  53. }
  54. /// <summary>
  55. /// Handles the server response with a 401 (Unauthorized) status code and a WWW-Authenticate header.
  56. /// The authenticator might determine the authentication method to use and initiate authentication if needed.
  57. /// </summary>
  58. /// <param name="req">The HTTP request that received the 401 response.</param>
  59. /// <param name="resp">The HTTP response containing the 401 (Unauthorized) status.</param>
  60. /// <returns><c>true</c> if the challenge is handled by the authenticator and the request can be resent with authentication; otherwise, <c>false</c>.</returns>
  61. public bool HandleChallange(HTTPRequest req, HTTPResponse resp)
  62. {
  63. var www_authenticate = resp.GetHeaderValues("www-authenticate");
  64. HTTPManager.Logger.Information(nameof(CredentialAuthenticator), $"HandleChallange({req}, {resp}, \"{www_authenticate}\")", req.Context);
  65. string authHeader = DigestStore.FindBest(www_authenticate);
  66. if (!string.IsNullOrEmpty(authHeader))
  67. {
  68. var digest = DigestStore.GetOrCreate(req.CurrentUri);
  69. digest.ParseChallange(authHeader);
  70. if (this.Credentials != null && digest.IsUriProtected(req.CurrentUri) && (!req.HasHeader("Authorization") || digest.Stale))
  71. return true;
  72. }
  73. return false;
  74. }
  75. }
  76. }