401 With Indy IdHttp Digest Authentication in Delphi XE

Richard Holland picture Richard Holland · Aug 21, 2012 · Viewed 9.3k times · Source

Trying to do a get() with Digest to a partner's web service with Delphi XE.

I have included IdAuthenticationDigest to the uses clause which should automatically work from what I've read - but I must be missing something because I'm getting a 401 Unauthorized.

Code:

begin
  // Init request:   
  IdHttp := TIdHttp.Create(nil);
  try
    idHttp.Request.ContentType := self.inputType; // 'application/xml'
    idHttp.Request.Accept := self.outputType; //'application/json';

    // Set request method:
    idHttp.Request.Method := Method; // 'Get'
    // Set username and password:
    idHttp.Request.BasicAuthentication := False;
    // IdHttp.Request.Username/Password also fails
    IdHttp.Request.Authentication.Username := 'xx';
    IdHttp.Request.Authentication.password := 'xx';

    IdHttp.Request.ContentLength := Length(Body);

    // Send request:
    if Method = 'GET' then
      Result := idHttp.Get(self.ServiceHost + URI)
    else
    if Method = 'POST' then
      Result := idHttp.Post(self.ServiceHost + URI, SendStream);

   finally
    idHttp.Free;
   end;
end;

Answer

Remy Lebeau picture Remy Lebeau · Aug 21, 2012

You need to set the Request.Username and Request.Password properties instead of using the Request.Authentication property. Also, do not set the Request.Method or Request.ContentLength properties at all. All three of those properties are managed by TIdHTTP internally.

  // Init request:   
  IdHttp := TIdHttp.Create(nil);
  try
    idHttp.Request.ContentType := self.inputType; // 'application/xml'
    idHttp.Request.Accept := self.outputType; //'application/json';

    // Set username and password:
    idHttp.Request.BasicAuthentication := False;
    IdHttp.Request.Username := 'xx';
    IdHttp.Request.Password := 'xx';

    // Send request:
    if Method = 'GET' then
      Result := IdHttp.Get(self.ServiceHost + URI)
    else
    if Method = 'POST' then
      Result := IdHttp.Post(self.ServiceHost + URI, SendStream);
   finally
    IdHttp.Free;
   end;