FZ95
FZ95

Reputation: 107

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.

Upvotes: 3

Views: 9423

Answers (3)

Hugues Van Landeghem
Hugues Van Landeghem

Reputation: 6808

In newer version of Delphi (before 10.3 Rio)

procedure TClientSOAP.DoHTTPWebNodeBeforePost(
  const HTTPReqResp: THTTPReqResp; Data: Pointer);
var
  auth: String;
begin
  auth := 'Authorization: Basic ' + TNetEncoding.Base64.Encode(FUserName + ':' + FPassword);
  HttpAddRequestHeaders(Data, PChar(auth), Length(auth), HTTP_ADDREQ_FLAG_ADD);
end;

With 10.3 Rio you have to use mjn42 answer even if you have proxy

Upvotes: 1

mjn42
mjn42

Reputation: 840

For HTTP Basic Authentication, this code (placed before calling the SOAP service) should work:

HTTPRIO.HTTPWebNode.UserName := 'aaa';
HTTPRIO.HTTPWebNode.Password := 'bbb';

instead of the TMyForm.HTTPRIOHTTPWebNode1BeforePost event handler

Upvotes: 0

FZ95
FZ95

Reputation: 107

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

Upvotes: 2

Related Questions