2010. május 27., csütörtök

Add proxy authorization support to the TNMHTTP component


Problem/Question/Abstract:

The NMHTTP component is a nice and simple way to retrieve URLs within your application using http. Although the component supports a proxy, it does not support proxy authentication (proxy username/password). This method solves this drawback.

Answer:

{
To add proxy authentication support you must:

  1. Have a proxy username and password (strings)
  2. Merge these strings with a ':' between as:

       totalString := UserName + ':' + PassWord

  3. Base-64 encode totalString
  4. On the OnAboutToSend event of the NMHTTP, add

     'Proxy-authorization: ' + totalString

     to the http header

The routine below encodes the Proxy username/password
to a string accepted by the proxy
}

uses Forms, Classes, NMUUE; // Don't forget these !

function EncodeAuth(username, password: string): string;
var
  uu: TNMUUProcessor;
  si, so: TStringStream;
  decoded: string;
  encoded: string;
begin
  decoded := username + ':' + password; // Username:Password
  SetLength(encoded, 20 * length(decoded)); // Estimate len
  uu := TNMUUProcessor.Create(Application); // UU Processor
  si := TStringStream.Create(decoded); // Input
  so := TStringStream.Create(encoded); // Output
  uu.InputStream := si;
  uu.OutputStream := so;
  uu.Method := uuMime;
  uu.Encode; // Decode
  result := so.ReadString(255); // Read Result
  result := copy(result, 1, pos(#13, result) - 1); // No CRLF
  si.free; // Free objects
  so.free;
  uu.free;
end;

{
The OnAboutToSend event on the NMHTTP should look like:
}

procedure TForm1.NMHTTP1AboutToSend(Sender: TObject);
begin
  if username <> '' then
    NMHTTP1.SendHeader.Insert(2, 'Proxy-authorization: ' +
      EncodeAuth(username, password));
end;

{
We are inserting the Proxy-authorization token
to the 3rd position as it is a valid position to
place it
}

Nincsenek megjegyzések:

Megjegyzés küldése