0

I am having a couple of issues with NTLM authentication using WinHTTP. Whilst monitoring the traffic in wireshark I can see the request being made, yet the client never sends the authentication headers necessarry so every time the server responds with a 401 authentication required message.

I am not behind any proxy server with direct IP connectivity to the host so that shouldn't be an issue.

Here is my code: and help would be most appreciated.

hSession = WinHttpOpen(L"Connection/1.0",
    WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0);

hConnect = WinHttpConnect(hSession, L"connect", INTERNET_DEFAULT_HTTP_PORT, 0);
hRequest = WinHttpOpenRequest(hConnect, L"GET", url, NULL, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, NULL);


WinHttpSetOption (hRequest, WINHTTP_OPTION_AUTOLOGON_POLICY, 0, 0);

int i = 0;

while(!bDone)
{
    i++;
    WinHttpSetCredentials(hRequest, WINHTTP_AUTH_TARGET_SERVER, WINHTTP_AUTH_SCHEME_NTLM, NULL, NULL, NULL);

    //Send the 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);

    if( bResults ) 
        bResults = WinHttpQueryHeaders(hRequest, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER, NULL, &dwStatusCode, &dwSize, NULL );


    if(bResults)
    {
        switch(dwStatusCode)
        {
            case 401:
                //Requres auth
                newFile << "401 Auth Required\n";
                WinHttpSetCredentials(hRequest, WINHTTP_AUTH_TARGET_SERVER, WINHTTP_AUTH_SCHEME_NTLM, NULL, NULL, NULL);
                break;

            default:
                newFile << dwStatusCode << " unknown\n";
                break;
        }
    }


    if(i >= 30)
        bDone = TRUE;
}
Roman R.
  • 68,205
  • 6
  • 94
  • 158
  • Your second `WinHttpSetCredentials` is immediately overwritten with another API call at the top of the loop body. – Roman R. Sep 29 '13 at 13:12
  • @Roman, MS recommends it that way, although it doesn't make any sense. Anyway, what you suggest is not a solution. –  Oct 01 '13 at 03:25
  • One WinHttpSetCredentials call is for a proxy and the other is for a server. It is if you have to authenticate to a server behind a proxy which you also have to authenticate to. I think in your case where you aren't concerning about proxies, it shouldn't be necessary to call WinHttpSetCredentials until after you get a 401. – Nathan Moinvaziri Oct 01 '13 at 04:34
  • Also, I don't actually see you passing in a username and password to WinHttpSetCredentials. – Nathan Moinvaziri Oct 01 '13 at 04:38

0 Answers0