Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Basic Authentication Error
#1
Hi,

I have a problem on a API REST call.

I always get the authentication error: HTTP/1.1 401 Unauthorized

this is my code in delphi 11.3

thanks
Alessandro Romano
//-----------------------------------------------------------
var
lHTTP: TIdHTTP;
SSL : TIdSSLIOHandlerSocketOpenSSL;
Comando, RisultatoPost : Ansistring;
lPostData: TStringStream;
base64: TBase64Encoding;
myUser, MyPass : string;
begin
  Comando := 'https://apirest... etc';
  base64 := TBase64Encoding.Create(0);

  myUser := 'myuser';
  MyPass := 'mypass';

  lPostData := TStringStream.Create('', TEncoding.UTF8);
  with TJSONObject.Create do
  try
      AddPair('Authorization', 'Basic ' + base64.Encode(myUser + ':' + MyPass));
      lPostData.Writestring(ToJSON);
  finally
    Free;
  end;

  lPostData.Position := 0;
  try
    lHTTP := TIdHTTP.Create;
    SSL := TIdSSLIOHandlerSocketOpenSSL.Create(lHTTP);
    SSL.SSLOptions.Method := sslvTLSv1_2;

        lHTTP.IOHandler := TIdSSLIOHandlerSocketOpenSSL.Create(lHTTP);
        lHTTP.IOHandler := SSL;
        lHTTP.HandleRedirects := True;
        lHTTP.Request.CustomHeaders.Clear;
        lHTTP.Request.CustomHeaders.FoldLines := False;
        lHTTP.Request.Accept := 'application/json';

        //lHTTP.Request.ContentType := 'application/json';
        //lHTTP.Request.CharSet := 'UTF-8';

        RisultatoPost := lHTTP.Post(Comando, lPostData);
         

    finally
      SSL.Free;
      lHTTP.Free;
      lPostData.Free;
      base64.Free;
  end;
Reply
#2
(12-04-2023, 11:20 AM)staff@ergosoft.it Wrote: I have a problem on a API REST call.

I always get the authentication error: HTTP/1.1 401 Unauthorized

TIdHTTP has built-in support for BASIC authentication at the HTTP layer. Are you sure you should be sending your credentials in the POST body? Do you get the same error if you use the standard HTTP Authorization header instead? TIdHTTP has properties for that purpose:

Code:
lHTTP.Request.BasicAuthentication := True;
lHTTP.Request.Username := myUser;
lHTTP.Request.Password := MyPass;

Reply
#3
(12-04-2023, 05:48 PM)rlebeau Wrote:
(12-04-2023, 11:20 AM)staff@ergosoft.it Wrote: I have a problem on a API REST call.

I always get the authentication error: HTTP/1.1 401 Unauthorized

TIdHTTP has built-in support for BASIC authentication at the HTTP layer.  Are you sure you should be sending your credentials in the POST body?  Do you get the same error if you use the standard HTTP Authorization header instead? TIdHTTP has properties for that purpose:

Code:
lHTTP.Request.BasicAuthentication := True;
lHTTP.Request.Username := myUser;
lHTTP.Request.Password := MyPass;

Thank you ! works


Alessandro Romano
Reply


Forum Jump:


Users browsing this thread: 1 Guest(s)