Ir al contenido


Foto

[MULTILENGUAJE] Autentificarnos en un proxy


  • Por favor identifícate para responder
4 respuestas en este tema

#1 escafandra

escafandra

    Advanced Member

  • Administrador
  • 4.107 mensajes
  • LocationMadrid - España

Escrito 21 mayo 2010 - 04:45

Para conseguir autentificar nuestro programa en un proxy, podemos dejar que el usuario lo haga a mano y automatizar el proceso y hacerlo transparente. Esto puede ahorrar los molestos diálogos que piden el usuario y contraseña.

La función que publico nos autentifica en un proxy dando una URL que tenga que salir por él, un nombre de usuario y una contraseña. El código origunal lo escribí en C++ pero lo muestro también migrado a delphi:

Versión C++:


cpp
  1. #pragma link "$(BCB)\\lib\\PSDK\\Wininet.lib"
  2.  
  3.  
  4. //---------------------------------------------------------------------------
  5. void Authenticate(char* _URL, char* Username, char* Password)
  6. {
  7.   HINTERNET hInet,  hConnect, hRequest;
  8.   DWORD dwStatus, dwStatusSize = sizeof(DWORD);
  9.  
  10.   char *URL = strnewdup(_URL);
  11.   if(!strnicmp(URL, "http://", 7)) URL += 7;
  12.   char *C = strchr(URL, '//'); if(C) *C = 0;
  13.  
  14.   hInet = InternetOpen("agent", INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
  15.   hConnect = InternetConnect(hInet, URL,
  16.                               INTERNET_INVALID_PORT_NUMBER,
  17.                               NULL, NULL, INTERNET_SERVICE_HTTP, 0,0);
  18.  
  19.   hRequest = HttpOpenRequest(hConnect, "GET", "",
  20.                               NULL, NULL, NULL, INTERNET_FLAG_KEEP_CONNECTION, 0);
  21.  
  22.   for(int n=0; n<2; n++){
  23.       HttpSendRequest(hRequest, NULL, 0, NULL, 0);
  24.       HttpQueryInfo(hRequest, HTTP_QUERY_FLAG_NUMBER | HTTP_QUERY_STATUS_CODE,
  25.                     &dwStatus, &dwStatusSize, NULL);
  26.  
  27.       // Se requiere autentificación en el Proxy o en el servidor
  28.       if(dwStatus == HTTP_STATUS_PROXY_AUTH_REQ || dwStatus == HTTP_STATUS_DENIED){
  29.         // Introducimos UserName
  30.         InternetSetOption(hRequest, INTERNET_OPTION_PROXY_USERNAME, (void*)Username, lstrlen(Username)+1);
  31.         // Introducimos el Password
  32.         InternetSetOption(hRequest, INTERNET_OPTION_PROXY_PASSWORD, (void*)Password, lstrlen(Password)+1);
  33.       }
  34.   }
  35.   delete URL;
  36.   InternetCloseHandle(hInet);
  37.   InternetCloseHandle(hConnect);
  38.   InternetCloseHandle(hRequest);
  39. }


Ejemplo de uso:

cpp
  1. Authenticate(Edit1->Text.c_str(), "User", "Password");
  2. CppWebBrowser1->Navigate(WideString(Edit1->Text).c_bstr());


La versión delphi es similar en su funcionamiento y uso:

delphi
  1. uses  Wininet;
  2.  
  3. procedure Authenticate(URL, UserName, PassWord: String);
  4. var
  5.   hInet, hConnect, hRequest: HINTERNET;
  6.   dwStatus, StatusSize, i: DWORD;
  7. begin
  8.   StatusSize:= sizeof(dwStatus);
  9.   URL:= StrLower(PCHAR(URL));
  10.   i:= Pos('http://', URL); if i>0 then URL:= Copy(URL, 8, Length(URL)-7);
  11.   i:= Pos('/', URL);      if i>0 then SetLength(URL, i-1);
  12.  
  13.   hInet:= InternetOpen('agent', INTERNET_OPEN_TYPE_PRECONFIG, nil, nil, 0);
  14.   hConnect:= InternetConnect(hInet, PCHAR(URL),
  15.                               INTERNET_INVALID_PORT_NUMBER, nil, nil,
  16.                               INTERNET_SERVICE_HTTP, 0,0);
  17.  
  18.   hRequest:= HttpOpenRequest(hConnect, 'GET', '',
  19.                               nil, nil, nil, INTERNET_FLAG_KEEP_CONNECTION, 0);
  20.  
  21.   for i:=0 to 1 do
  22.   begin
  23.       HttpSendRequest(hRequest, nil, 0, nil, 0);
  24.       HttpQueryInfo(hRequest, HTTP_QUERY_FLAG_NUMBER or
  25.                     HTTP_QUERY_STATUS_CODE, @dwStatus, StatusSize, PCardinal(0)^);
  26.       // Se requiere autentificación en el Proxy o en el servidor
  27.       if (dwStatus = HTTP_STATUS_PROXY_AUTH_REQ) or (dwStatus = HTTP_STATUS_DENIED) then
  28.       begin
  29.         // Introducimos UserName
  30.         InternetSetOption(hRequest, INTERNET_OPTION_PROXY_USERNAME, PCHAR(UserName), Length(UserName) + 1);
  31.  
  32.         // Introducimos el Password
  33.         InternetSetOption(hRequest, INTERNET_OPTION_PROXY_PASSWORD, PCHAR(PassWord), Length(PassWord) + 1);
  34.       end;
  35.   end;
  36.   InternetCloseHandle(hInet);
  37.   InternetCloseHandle(hConnect);
  38.   InternetCloseHandle(hRequest);
  39. end;


Ejemplo de uso:

delphi
  1. Authenticate(PCHAR(Edit1.Text), 'User', 'Password');
  2. WebBrowser1.Navigate(WideString(Edit1.Text));


Espero que sea de utilidad.


Saludos.

PD: Actualizo para admitir direcciones IP
  • 0

#2 egostar

egostar

    missing my father, I love my mother.

  • Administrador
  • 14.448 mensajes
  • LocationMéxico

Escrito 21 mayo 2010 - 04:53

Excelente código para evitarnos el tener que autenticarnos manualmente, solo hay que utilizar la unidad WinInet en Delphi. Gracias escafandra, siempre con utilidades muy interesantes. (y)

Salud OS
  • 0

#3 escafandra

escafandra

    Advanced Member

  • Administrador
  • 4.107 mensajes
  • LocationMadrid - España

Escrito 22 mayo 2010 - 01:06

solo hay que utilizar la unidad WinInet en Delphi.


Y en C/C++ debemos suministrar la ruta de librerías $(BCB)\Lib\PSDK\ para que se pueda enlazar Wininet.lib

Saludos.
  • 0

#4 escafandra

escafandra

    Advanced Member

  • Administrador
  • 4.107 mensajes
  • LocationMadrid - España

Escrito 07 septiembre 2011 - 03:41

Con motivo de una revisión de este hilo, actualiza el código expuesto arriba.

Saludos.


  • 0

#5 escafandra

escafandra

    Advanced Member

  • Administrador
  • 4.107 mensajes
  • LocationMadrid - España

Escrito 21 marzo 2012 - 09:23

Por coherencia con el truco Pedir autentificación en un proxy  Actualizo el código para que admita direcciones IP.


Saludos.


  • 0




IP.Board spam blocked by CleanTalk.