EastsideDev
EastsideDev

Reputation: 6639

PHP: calling an API protected using basic authentication

I have an API deployed on a server that's now protected using basic authentication.

I also have a script running on the SAME server that the APi running on, that needs to call the API.

script: test.php

<?php
$url = 'https://my_site.myapi/account/add/{"account_id":"1234555"}
$username = 'myname';
$password = 'mypassword';
$ch=curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_USERPWD, $username.":".$password);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,5);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
$data = curl_exec($ch);
curl_close($ch);

When I try calling test.php from a browser:

https://my_site.myapi/test.php

I am promoted for user name and password. I am not getting an error message. Any ideas?

VirtualHost Section

DocumentRoot /var/www/mysite/web/
<Directory />
    Options FollowSymLinks
    AllowOverride None
</Directory>

<Directory "/var/www/api_section_1">
    Options Indexes MultiViews FollowSymLinks
    AllowOverride All
    Order allow,deny
    Allow from all
    AuthType Basic
    AuthName "Restricted Access"
    AuthUserFile /usr/local/apache/passwd/passwords
</Directory>

Alias /winapi /var/www/another_section/
<Directory "/var/www/another_section">
    Options Indexes MultiViews FollowSymLinks
    AllowOverride None
    Order allow,deny
    Allow from all
    AuthType Basic
    AuthName "Restricted Access"
    AuthUserFile /usr/local/apache/passwd/passwords
</Directory>

Upvotes: 0

Views: 633

Answers (2)

dearlbry
dearlbry

Reputation: 3211

If you're getting prompted for a password, that's not coming from your curl call, but rather apache. My guess is that your https://my_site.myapi/test.php page is also mistakenly protected by the basic auth.

curl_exec() would return an error indicating that authentication was required, not prompt you for it.

Upvotes: 1

Fenton
Fenton

Reputation: 250922

Is your basic authentication expecting any encoding - for example the username and password token may need to be base64 encoded.

Another thing to check is that the details make it into the Authorization header - check the request headers to see if this is the case.

Upvotes: 0

Related Questions