BearerTokenAuthenticator.cs 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. namespace Best.HTTP.Request.Authenticators
  2. {
  3. /// <summary>
  4. /// An <see cref="IAuthenticator"/> implementation for Bearer Token authentication.
  5. /// </summary>
  6. /// <remarks>
  7. /// Bearer Token authentication is a method used to access protected resources on a server.
  8. /// It involves including a bearer token in the Authorization header of an HTTP request to prove the identity of the requester.
  9. /// </remarks>
  10. public class BearerTokenAuthenticator : IAuthenticator
  11. {
  12. /// <summary>
  13. /// Initializes a new instance of the BearerTokenAuthenticator class with the specified Bearer Token.
  14. /// </summary>
  15. /// <param name="token">The Bearer Token to use for authentication.</param>
  16. public string Token { get; private set; }
  17. /// <summary>
  18. /// Sets up the required Authorization header with the Bearer Token for the HTTP request.
  19. /// </summary>
  20. /// <param name="request">The HTTP request for which the Authorization header should be added.</param>
  21. /// <remarks>
  22. /// When sending an HTTP request to a server that requires Bearer Token authentication,
  23. /// this method sets the Authorization header with the Bearer Token to prove the identity of the requester.
  24. /// This allows the requester to access protected resources on the server.
  25. /// </remarks>
  26. public BearerTokenAuthenticator(string token) => this.Token = token;
  27. public void SetupRequest(HTTPRequest request)
  28. {
  29. if (!string.IsNullOrEmpty(this.Token))
  30. request.SetHeader("Authorization", $"Bearer {this.Token}");
  31. }
  32. /// <summary>
  33. /// Handles the server response with a 401 (Unauthorized) status code and a WWW-Authenticate header.
  34. /// This authenticator does not handle challenges and always returns <c>false</c>.
  35. /// </summary>
  36. /// <param name="req">The HTTP request that received the 401 response.</param>
  37. /// <param name="resp">The HTTP response containing the 401 (Unauthorized) status.</param>
  38. /// <returns><c>false</c>, as this authenticator does not handle challenges.</returns>
  39. /// <remarks>
  40. /// Bearer Token authentication typically does not require handling challenges,
  41. /// as the Bearer Token is included directly in the Authorization header of the request.
  42. /// This method always returns <c>false</c>, as no additional challenge processing is needed.
  43. /// </remarks>
  44. public bool HandleChallange(HTTPRequest req, HTTPResponse resp) => false;
  45. }
  46. }