Share via


Função WinHttpQueryAuthSchemes (winhttp.h)

A função WinHttpQueryAuthSchemes retorna os esquemas de autorização compatíveis com o servidor.

Sintaxe

WINHTTPAPI BOOL WinHttpQueryAuthSchemes(
  [in]  HINTERNET hRequest,
  [out] LPDWORD   lpdwSupportedSchemes,
  [out] LPDWORD   lpdwFirstScheme,
  [out] LPDWORD   pdwAuthTarget
);

Parâmetros

[in] hRequest

Identificador HINTERNET válido retornado por WinHttpOpenRequest

[out] lpdwSupportedSchemes

Um inteiro sem sinal que especifica um sinalizador que contém os esquemas de autenticação com suporte. Esse parâmetro pode retornar um ou mais sinalizadores identificados na tabela a seguir.

Valor Significado
WINHTTP_AUTH_SCHEME_BASIC
Indica que a autenticação básica está disponível.
WINHTTP_AUTH_SCHEME_NTLM
Indica que a autenticação NTLM está disponível.
WINHTTP_AUTH_SCHEME_PASSPORT
Indica que a autenticação de passaporte está disponível.
WINHTTP_AUTH_SCHEME_DIGEST
Indica que a autenticação de resumo está disponível.
WINHTTP_AUTH_SCHEME_NEGOTIATE
Seleciona entre a autenticação NTLM e Kerberos.

[out] lpdwFirstScheme

Um inteiro sem sinal que especifica um sinalizador que contém o primeiro esquema de autenticação listado pelo servidor. Esse parâmetro pode retornar um ou mais sinalizadores identificados na tabela a seguir.

Valor Significado
WINHTTP_AUTH_SCHEME_BASIC
Indica que a autenticação básica é a primeira.
WINHTTP_AUTH_SCHEME_NTLM
Indica que a autenticação NTLM é a primeira.
WINHTTP_AUTH_SCHEME_PASSPORT
Indica que a autenticação de passaporte é a primeira.
WINHTTP_AUTH_SCHEME_DIGEST
Indica que a autenticação de resumo é a primeira.
WINHTTP_AUTH_SCHEME_NEGOTIATE
Seleciona entre a autenticação NTLM e Kerberos.

[out] pdwAuthTarget

Um inteiro sem sinal que especifica um sinalizador que contém o destino de autenticação. Esse parâmetro pode retornar um ou mais sinalizadores identificados na tabela a seguir.

Valor Significado
WINHTTP_AUTH_TARGET_SERVER
O destino de autenticação é um servidor. Indica que um código 401 status foi recebido.
WINHTTP_AUTH_TARGET_PROXY
O destino de autenticação é um proxy. Indica que um código 407 status foi recebido.

Valor retornado

Retorna TRUE se tiver êxito ou FALSE se não tiver êxito. Para obter informações de erro estendidas, chame GetLastError. A tabela a seguir identifica os códigos de erro retornados.

Código do Erro Descrição
ERROR_WINHTTP_INCORRECT_HANDLE_TYPE
O tipo de identificador fornecido está incorreto para esta operação.
ERROR_WINHTTP_INTERNAL_ERROR
Ocorreu um erro interno.
ERROR_NOT_ENOUGH_MEMORY
Não havia memória suficiente disponível para concluir a operação solicitada. (Código de erro do Windows)

Comentários

Mesmo quando WinHTTP é usado no modo assíncrono (ou seja, quando WINHTTP_FLAG_ASYNC é definido em WinHttpOpen), essa função opera de forma síncrona. O valor retornado indica êxito ou falha. Para obter informações de erro estendidas, chame GetLastError.

WinHttpQueryAuthSchemes não pode ser usado antes de chamar WinHttpQueryHeaders.

Nota Para Windows XP e Windows 2000, consulte a seção Requisitos de tempo de execução da página inicial do WinHttp.
 

Exemplos

O exemplo a seguir mostra como recuperar um documento especificado de um servidor HTTP quando a autenticação é necessária. O código status é recuperado da resposta para determinar se o servidor ou o proxy está solicitando a autenticação. Se um código de status 200 for encontrado, o documento estará disponível. Se um código de status de 401 ou 407 for encontrado, a autenticação será necessária para que o documento possa ser recuperado. Para qualquer outra status código, uma mensagem de erro é exibida.

#include <windows.h>
#include <winhttp.h>
#include <stdio.h>

#pragma comment(lib, "winhttp.lib")

DWORD ChooseAuthScheme( DWORD dwSupportedSchemes )
{
  //  It is the server's responsibility only to accept 
  //  authentication schemes that provide a sufficient level
  //  of security to protect the server's resources.
  //
  //  The client is also obligated only to use an authentication
  //  scheme that adequately protects its username and password.
  //
  //  Thus, this sample code does not use Basic authentication  
  //  because Basic authentication exposes the client's username 
  //  and password to anyone monitoring the connection.
  
  if( dwSupportedSchemes & WINHTTP_AUTH_SCHEME_NEGOTIATE )
    return WINHTTP_AUTH_SCHEME_NEGOTIATE;
  else if( dwSupportedSchemes & WINHTTP_AUTH_SCHEME_NTLM )
    return WINHTTP_AUTH_SCHEME_NTLM;
  else if( dwSupportedSchemes & WINHTTP_AUTH_SCHEME_PASSPORT )
    return WINHTTP_AUTH_SCHEME_PASSPORT;
  else if( dwSupportedSchemes & WINHTTP_AUTH_SCHEME_DIGEST )
    return WINHTTP_AUTH_SCHEME_DIGEST;
  else
    return 0;
}

struct SWinHttpSampleGet
{
  LPCWSTR szServer;
  LPCWSTR szPath;
  BOOL fUseSSL;
  LPCWSTR szServerUsername;
  LPCWSTR szServerPassword;
  LPCWSTR szProxyUsername;
  LPCWSTR szProxyPassword;
};

void WinHttpAuthSample( IN SWinHttpSampleGet *pGetRequest )
{
  DWORD dwStatusCode = 0;
  DWORD dwSupportedSchemes;
  DWORD dwFirstScheme;
  DWORD dwSelectedScheme;
  DWORD dwTarget;
  DWORD dwLastStatus = 0;
  DWORD dwSize = sizeof(DWORD);
  BOOL  bResults = FALSE;
  BOOL  bDone = FALSE;

  DWORD dwProxyAuthScheme = 0;
  HINTERNET  hSession = NULL, 
             hConnect = NULL,
             hRequest = NULL;

  // Use WinHttpOpen to obtain a session handle.
  hSession = WinHttpOpen( L"WinHTTP Example/1.0",  
                          WINHTTP_ACCESS_TYPE_DEFAULT_PROXY,
                          WINHTTP_NO_PROXY_NAME, 
                          WINHTTP_NO_PROXY_BYPASS, 0 );

  INTERNET_PORT nPort = ( pGetRequest->fUseSSL ) ? 
                        INTERNET_DEFAULT_HTTPS_PORT  :
                        INTERNET_DEFAULT_HTTP_PORT;

  // Specify an HTTP server.
  if( hSession )
    hConnect = WinHttpConnect( hSession, 
                               pGetRequest->szServer, 
                               nPort, 0 );

  // Create an HTTP request handle.
  if( hConnect )
    hRequest = WinHttpOpenRequest( hConnect, 
                                   L"GET", 
                                   pGetRequest->szPath,
                                   NULL, 
                                   WINHTTP_NO_REFERER, 
                                   WINHTTP_DEFAULT_ACCEPT_TYPES,
                                   ( pGetRequest->fUseSSL ) ? 
                                       WINHTTP_FLAG_SECURE : 0 );

  // Continue to send a request until status code is not 401 or 407.
  if( hRequest == NULL )
    bDone = TRUE;

  while( !bDone )
  {
    //  If a proxy authentication challenge was responded to, reset 
    //  those credentials before each SendRequest, because the proxy  
    //  may require re-authentication after responding to a 401 or to 
    //  a redirect. If you don't, you can get into a 407-401-407-401
    //  loop.
    if( dwProxyAuthScheme != 0 )
      bResults = WinHttpSetCredentials( hRequest, 
                                        WINHTTP_AUTH_TARGET_PROXY, 
                                        dwProxyAuthScheme, 
                                        pGetRequest->szProxyUsername,
                                        pGetRequest->szProxyPassword,
                                        NULL );
    // Send a request.
    bResults = WinHttpSendRequest( hRequest,
                                   WINHTTP_NO_ADDITIONAL_HEADERS,
                                   0,
                                   WINHTTP_NO_REQUEST_DATA,
                                   0, 
                                   0, 
                                   0 );

    // End the request.
    if( bResults )
      bResults = WinHttpReceiveResponse( hRequest, NULL );

    // Resend the request in case of 
    // ERROR_WINHTTP_RESEND_REQUEST error.
    if( !bResults && GetLastError( ) == ERROR_WINHTTP_RESEND_REQUEST)
        continue;

    // Check the status code.
    if( bResults ) 
      bResults = WinHttpQueryHeaders( hRequest, 
                                      WINHTTP_QUERY_STATUS_CODE | 
                                          WINHTTP_QUERY_FLAG_NUMBER,
                                      NULL, 
                                      &dwStatusCode, 
                                      &dwSize, 
                                      NULL );

    if( bResults )
    {
      switch( dwStatusCode )
      {
        case 200: 
          // The resource was successfully retrieved.
          // You can use WinHttpReadData to read the contents 
          // of the server's response.
          printf( "The resource was successfully retrieved.\n" );
          bDone = TRUE;
          break;

        case 401:
          // The server requires authentication.
          printf(
           "The server requires authentication. Sending credentials\n");

          // Obtain the supported and preferred schemes.
          bResults = WinHttpQueryAuthSchemes( hRequest, 
                                              &dwSupportedSchemes, 
                                              &dwFirstScheme, 
                                              &dwTarget );

          // Set the credentials before re-sending the request.
          if( bResults )
          {
            dwSelectedScheme = ChooseAuthScheme( dwSupportedSchemes );

            if( dwSelectedScheme == 0 )
              bDone = TRUE;
            else
              bResults = WinHttpSetCredentials( 
                                        hRequest, dwTarget, 
                                        dwSelectedScheme,
                                        pGetRequest->szServerUsername,
                                        pGetRequest->szServerPassword,
                                        NULL );
          }

          // If the same credentials are requested twice, abort the
          // request.  For simplicity, this sample does not check for
          // a repeated sequence of status codes.
          if( dwLastStatus == 401 )
            bDone = TRUE;

          break;

        case 407:
          // The proxy requires authentication.
          printf( 
           "The proxy requires authentication. Sending credentials\n");

          // Obtain the supported and preferred schemes.
          bResults = WinHttpQueryAuthSchemes( hRequest, 
                                              &dwSupportedSchemes, 
                                              &dwFirstScheme, 
                                              &dwTarget );

          // Set the credentials before re-sending the request.
          if( bResults )
            dwProxyAuthScheme = ChooseAuthScheme(dwSupportedSchemes);

          // If the same credentials are requested twice, abort the
          // request.  For simplicity, this sample does not check for
          // a repeated sequence of status codes.
          if( dwLastStatus == 407 )
            bDone = TRUE;
          break;

        default:
          // The status code does not indicate success.
          printf( "Error. Status code %d returned.\n", dwStatusCode );
          bDone = TRUE;
      }
    }

    // Keep track of the last status code.
    dwLastStatus = dwStatusCode;

    // If there are any errors, break out of the loop.
    if( !bResults ) 
        bDone = TRUE;
  }

  // Report any errors.
  if( !bResults )
  {
    DWORD dwLastError = GetLastError( );
    printf( "Error %d has occurred.\n", dwLastError );
  }

  // Close any open handles.
  if( hRequest ) WinHttpCloseHandle( hRequest );
  if( hConnect ) WinHttpCloseHandle( hConnect );
  if( hSession ) WinHttpCloseHandle( hSession );
}


Requisitos

   
Cliente mínimo com suporte Windows XP, Windows 2000 Professional com SP3 [somente aplicativos da área de trabalho]
Servidor mínimo com suporte Windows Server 2003, Windows 2000 Server com SP3 [somente aplicativos da área de trabalho]
Plataforma de Destino Windows
Cabeçalho winhttp.h
Biblioteca Winhttp.lib
DLL Winhttp.dll
Redistribuível WinHTTP 5.0 e Internet Explorer 5.01 ou posterior no Windows XP e Windows 2000.

Confira também

Sobre os Serviços HTTP do Microsoft Windows (WinHTTP)

Versões do WinHTTP

WinHttpSetCredentials