Reputation: 1019
I'm creating my first API, which will need to be accessed by a partner from their server using cURL. So in creating it, I am using server #1 to create a test connection script, and server #2 to host the API. On Server #1 I have:
<?php
$url = "http://example.net/api/";
$data['api_key'] = "AFsASfafasasf";
$data['api_secret'] = "faskakfokfl3a";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
$result = curl_exec($ch);
curl_close($ch);
echo $result;
?>
And on Server #2, the API file, I have this (just to test the connection):
<?php
echo "Testing API...";
echo $_POST['api_key'];
echo $_POST['api_secret'];
?>
Problem is, when I run the test script on Server #1, I get this:
"Authorization Required
This server could not verify that you are authorized to access the document requested. Either you supplied the wrong credentials (e.g., bad password), or your browser doesn't understand how to supply the credentials required.
Additionally, a 401 Authorization Required error was encountered while trying to use an ErrorDocument to handle the request."
This is definitely connected to cURL because Server #1 will work with any other basic PHP script.
All the examples I've seen online don't seem to require authorization...so is it something in the CURLOPT fields I need to set, or is there something in .htaccess or somewhere else I'm missing?
Thanks!
Upvotes: 1
Views: 4975
Reputation: 1118
I was getting the same error when I tried running a cURL command on the same server that I was running my API.
I finally worked out that the virtual host settings in httpd.conf were set up for a single gateway IP, and not 127.0.0.1.
So, presuming apache, I think it's likely that Server #2 is calling Server #1 in a way that conflicts with the apache settings on #1.
Check the /etc/hosts file on Server #2 to work out whether it's calling Server #1 directly by its internal IP, or just sending outside the LAN by default.
Check the httpd.conf settings on Server #1, specifically which IP addresses NameVirtualHost and VirtualHost are configured for when resolving the domain. They need to be configured to allow the IP address that Server #2 is calling from.
Upvotes: 0
Reputation: 1385
401 error comes when server requires some kind of authentication to access the web page and in most cases it is basic authentication.
Can you please confirm whether basic authentication is configured on your Server #1? If Server #1 requires basic authentication, then browser will ask it first time and then it will store credentials and pass it with every subsequent request.
if Basic Authentication is configured, then following will pass credentials using cURL
curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
Upvotes: 4