Home > other >  How to activate/force Basic Auth on THTTPClient
How to activate/force Basic Auth on THTTPClient

Time:05-17

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

CodePudding user response:

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.

  • Related