Via Cà Matta 2 - Peschiera Borromeo (MI)
+39 02 00704272
info@synaptica.info

Delphi NetHttpClient Basic Auth

Digital solution partner

Delphi NetHttpClient Basic Auth

First method:

 if (mUsername <> '') and (mPassword <> '') then
    begin
      LCredentials := TCredentialsStorage.TCredential.Create
        (TAuthTargetType.Server, '', mURL, '', '');

      LCredentials.Username := mUsername; 
      LCredentials.Password := mPassword; 
      NetHTTPClient1.CredentialsStorage.AddCredential(LCredentials);
      NetHTTPClient1.UseDefaultCredentials := false;
    end;

 

Second one:

procedure TForm3.NetHTTPClient1AuthEvent(const Sender: TObject;
  AnAuthTarget: TAuthTargetType; const ARealm, AURL: string; var AUserName,
  APassword: string; var AbortAuth: Boolean;
  var Persistence: TAuthPersistenceType);
begin
  APassword := 'pippo';
  AUserName := 'pluto';
end;

 

PreemptiveAuthentication:

Generally, when the server receives the request, it replies that it needs a user and password to access it, so your basic authentication works. There are cases in which the server is configured to accept only calls that in the first instance send the authentication data. To force the NetHttpClient class to work this way:

 ... 
 NetHttp := TNetHTTPClient.Create(nil);

 NetHttp.PreemptiveAuthentication := True;
 NetHttp.OnAuthEvent := HTTPAuthEvent;
 ...