complete_stranger
complete_stranger

Reputation: 908

How to activate/force Basic Auth on THTTPClient

I can't find an option to activate Basic Auth on THTTPClient.

My main "issue" is that the first request response with a HTTP/1.1 401 Unauthorized and it triggers an auth event. I want to do it on the first "try".

Here is my code:

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;

Option #2 includes the Authorization in the first request. Option #1 does not. basic auth

How can I do that?

Update - PreemptiveAuthentication does not exist in Seattle PreemptiveAuthentication

Upvotes: 0

Views: 1938

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 595339

In Delphi 11 and later, using THTTPClient.CredentialsStorage should work, you just need to set THTTPClient.PreemptiveAuthentication to true:

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

However, PreemptiveAuthentication does not exist in Delphi 10.x, including Seattle, so you will have to stick with your CustomHeaders solution until you can upgrade to a modern Delphi version.

Upvotes: 3

Related Questions