Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading