6

Using InternetSetOption to set the username and password when connecting to a REST service. I notice that WinInet does not send the Authorization header when I call HttpSentRequest even though I called InternetSetOption first. Seems ridiculous that you have to get a response from the server with a WWW-Authenication header first. That creates an entire extra request to the server on every request.

Is there a WinInet call to force the Authorization header on the first call or do I have to add it manually?

Lamloumi Afif
  • 8,941
  • 26
  • 98
  • 191
bpeikes
  • 3,495
  • 9
  • 42
  • 80
  • Have you tried adding the Authentication header directly? – kiewic Oct 06 '13 at 00:15
  • 1
    I ended up adding the Authentication header directly, but it seems like a kludge. Why wouldn't WinInet allow you to specify the Authentication scheme if you already know it? – bpeikes Oct 07 '13 at 20:47
  • I came here looking for an answer to the same puzzle, except I specified the credentials in InternetConnect, not with InternetSetOption. Neither one works as expected. – Enno Aug 20 '23 at 16:12

2 Answers2

1

After some deliberation and research, I think the answer is no. To set an Authorization header, WinInet needs to know what authentication method it should use, not just what username and password. The standard way to determine an authentication scheme is to send an unauthenticated request and read the WWW-Authenticate header.

If you know that your request needs Basic Authentication, you can set the Authorization: header yourself, using HttpAddRequestHeaders:

   HttpAddRequestHeaders(hRequest, TEXT("Authentication: Basic dXNlcjpwYXNzd29yZA=="), -1, HTTP_ADDREQ_FLAG_REPLACE);

Calculate the base64-encoding of your own "user:password" string using CryptBinaryToString.

Enno
  • 1,736
  • 17
  • 32
0

Call the function InternetSetOptionW before HttpSendRequestW. For example:

InternetSetOptionW( hRequest, INTERNET_OPTION_USERNAME, (void*) pwszAuthUserName, wcslen( pwszAuthUserName ) + 1 );
InternetSetOptionW( hRequest, INTERNET_OPTION_PASSWORD, (void*) pwszAuthPassword, wcslen( pwszAuthPassword ) + 1 );
HttpSendRequestW( hRequest, 0, -1, 0, 0 );
  • 1
    The OP says he's already using InternetSetOption, though he's not showing his code. I've tried the same, and still have the same problem: HttpSendRequest sends an initial request without authentication, shortly after followed by an authenticated request. – Enno Aug 20 '23 at 16:11