30

I was wondering what CURLOPT_USERPWD is actually doing to the url, header or data of a request. Is it INSTEAD OF the Authorization: Basic <base64 of user:pass> or does it work along side this?

Is it modifying the url to this?:

username:password@someurl.com

I saw some code like this so I am wondering, as it seems if I request that url in a NodeJS equivalent request it is not working with just an Authorization header (I have a theory the server is broken and ignoring the Auth header and using the username:password in the url):

    curl_setopt($ch, CURLOPT_URL, $url); 

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 

    $encodedAuth = base64_encode(self::$pfAdapterUser.":".self::$pfAdapterPasswd);

    curl_setopt($ch, CURLOPT_HTTPHEADER, array("Authentication : Basic ".$encodedAuth));
    curl_setopt($ch, CURLOPT_USERPWD, self::$pfAdapterUser.":".self::$pfAdapterPasswd);
    curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLINFO_HEADER_OUT, true);

Thanks

Dominic
  • 62,658
  • 20
  • 139
  • 163

1 Answers1

48

Is it modifying the url to this?:

username:password@someurl.com

No, the url still the same. You can check with

curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);

This

$encodedAuth = base64_encode(self::$pfAdapterUser.":".self::$pfAdapterPasswd);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Authorization: Basic ".$encodedAuth));

And this

curl_setopt($ch, CURLOPT_USERPWD, self::$pfAdapterUser.":".self::$pfAdapterPasswd);

are doing the same thing so there's no need to use them together (although it won't break), use one and it will work fine.

Community
  • 1
  • 1
hlscalon
  • 7,304
  • 4
  • 33
  • 40
  • 1
    If you also include curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY); then the behavior is different. When this is combined with the USERPWD, cURL will first make a request without the Authorizaion header to see how the server responds and then selects the best authentication method. – Juha Palomäki May 16 '17 at 12:44
  • 1
    I think it's worth noting that CURLOPT_USERPWD sends the header as "Authorization: Basic" without the space after Authorization. This seems to matter, as I've used your code and it failed on certain services. Depending on how the server reads the headers, the extra space may cause things to break. – Robert Noack Jan 28 '19 at 17:51
  • 1
    @RobertNoack fixed. That whitespace wasn't intended, tks – hlscalon Jan 28 '19 at 18:51
  • 1
    Right but what does the request actually look like when it's sent? What is it 'sent' as? – Oliver Dixon Dec 12 '19 at 20:04
  • 4
    @OliverDixon Its turning the username and password to its base64 form and prepending "Authorization: Basic" infront so basically it's sending it as `Authorization: Basic ` – Uriahs Victor Jun 12 '21 at 01:49