Search code examples
delphihttpsoapfiremonkeydelphi-xe8

SOAP message - Add authentication in http header


I have to send a SOAP message to a WebService that needs BASIC authentication in the HTTP request, but I can't find a way to do it.

After searching, I found some solutions and workarounds, but none of them worked.

Here's my code:

procedure TMyForm.HTTPRIOHTTPWebNode1BeforePost(
 const HTTPReqResp: THTTPReqResp; Data: Pointer);
var
 UserName: string;
 PassWord: string;
begin

UserName := 'aaa';
Password := 'bbb';

if not InternetSetOption(Data,
                  INTERNET_OPTION_USERNAME,
                  PChar(UserName),
                  Length(UserName)) then
 raise Exception(SysErrorMessage(GetLastError));

if not InternetSetOption(Data,
                  INTERNET_OPTION_PASSWORD,
                  PChar(Password),
                  Length(Password)) then
 raise Exception(SysErrorMessage(GetLastError));


end;

I tried setting the Username and Password in the HTTPRIO.HTTPWebNode, but it ignores them, and it doesn't rise the exceptions.

The WebService keeps telling me that credentials are missing.

I managed to do it in C#:

protected override WebRequest GetWebRequest(Uri uri)
{
    HttpWebRequest request = (HttpWebRequest)base.GetWebRequest(uri);
    Byte[] credentialBuffer = new UTF8Encoding().GetBytes("aaa:bbb");
    request.Headers.Add("Authorization", string.Format("Basic {0}", Convert.ToBase64String(credentialBuffer)));
    return request;
}

but I can't find a way to do it in Delphi.

Am I missing something, or am I doing it wrong?

I use Delphi XE8 with FireMonkey.


Solution

  • Ok I did it thanks to the comments.

    procedure TMyForm.HTTPRIOHTTPWebNode1BeforePost(
     const HTTPReqResp: THTTPReqResp; Data: Pointer);
    var
     auth: String;
    begin
    
      auth := 'Authorization: Basic ' + idEncoderMIME1.EncodeString('aaa:bbb' );
      HttpAddRequestHeaders(Data, PChar(auth), Length(auth), HTTP_ADDREQ_FLAG_ADD);
    
    end;
    

    I just add to the header 'Authorization: Basic ' + username:password encoded.

    Actually I only did what I was doing in c#, but I couldn't figure it out before.

    Thanks