如何 activate/force THTTPClient 上的基本身份验证

How to activate/force Basic Auth on THTTPClient

我在 THTTPClient 上找不到激活基本身份验证的选项。

我的主要“问题”是第一个带有 HTTP/1.1 401 Unauthorized 的请求响应,它会触发一个身份验证事件。我想在第一次“尝试”时就做。

这是我的代码:

uses
  System.Net.HTTPClient, System.Net.URLClient, System.NetEncoding;

procedure DoRequest(const url, username, password, filename: string);
var
  http: THTTPClient;
  ss: TStringStream;
  base64: TBase64Encoding;
begin
  http := THTTPClient.Create;
  ss := TStringStream.Create('', TEncoding.UTF8);
  base64 := TBase64Encoding.Create(0);
  try
    // option #1 - build in credential storage
    http.CredentialsStorage.AddCredential(
      TCredentialsStorage.TCredential.Create(
        TAuthTargetType.Server, '', url, username, password
    ));
    // option #2 - custom "Authorization"
    http.CustomHeaders['Authorization'] := 'Basic ' + base64.Encode(username + ':' + password);

    http.ProxySettings.Create('127.0.0.1', 8888); // for fiddler
    http.Get(url, ss);
    ss.SaveToFile(filename);
  finally
    base64.Free;
    ss.Free;
    http.Free;
  end;
end;

选项 #2 在第一个请求中包含授权。选项#1 没有。

我该怎么做?

更新 - PreemptiveAuthentication 在西雅图不存在

在 Delphi 11 及更高版本中,使用 THTTPClient.CredentialsStorage 应该可以,您只需将 THTTPClient.PreemptiveAuthentication 设置为 true:

Property controls preemptive authentication. When set to True, then basic authentication will be provided before the server gives an unauthorized response.

但是,PreemptiveAuthentication 在 Delphi 10.x 中不存在,包括西雅图,因此您必须坚持使用 CustomHeaders 解决方案,直到您可以升级到现代 Delphi 版本。