简体   繁体   中英

PHP CURL => Rest API (GET) = HTTP_CODE 401

The following script returns "HTTP/1.1 401 Unauthorized" by requesting, but i am not sure why. I know, the request goes to a https, but i "denied" the option "CURLOPT_SSL_VERIFYPEER".. and i think, that's not the problem at all, is it?

<?php
error_reporting(E_ALL); 
ini_set('display_errors', 1);

$html_brand = "https://example.com/api/test";
$ch = curl_init();

$options = array(
    CURLOPT_URL            => $html_brand,
    CURLOPT_RETURNTRANSFER => TRUE,
    CURLOPT_HEADER         => TRUE,
    CURLOPT_FOLLOWLOCATION => TRUE,
    CURLOPT_CONNECTTIMEOUT => 120,
    CURLOPT_TIMEOUT        => 120,
    CURLOPT_SSL_VERIFYPEER => FALSE,
    CURLOPT_CUSTOMREQUEST  => "GET",
    CURLOPT_HTTPAUTH       => CURLAUTH_DIGEST,
    CURLOPT_USERPWD        => "user:pass",
    CURLOPT_HTTPHEADER     => array(
            'Content-Type: application/json; charset=utf-8'
        )
);
curl_setopt_array( $ch, $options );
$response = curl_exec($ch); 
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

if ( $httpCode != 200 ){
    echo "Return code is {$httpCode} \n"
        .curl_error($ch);
    echo "<pre>";
    print_r($response);
} else {
    echo "<pre>".htmlspecialchars($response)."</pre>";
}

curl_close($ch);

I think, there is just one more option for the curl missing..

Response:

HTTP/1.1 401 Unauthorized Server: nginx Date: Tue, 19 May 2015 18:52:26 GMT Content-Type: application/json Transfer-Encoding: chunked Connection: keep-alive Keep-Alive: timeout=5 Www-Authenticate: Digest realm="REST-API", domain="/", nonce="", opaque="", algorithm="MD5", qop="auth" Cache-Control: nocache, private Vary: Accept-Encoding

HTTP/1.1 400 Bad Request Server: nginx Date: Tue, 19 May 2015 18:52:26 GMT Content-Type: application/json Transfer-Encoding: chunked Connection: keep-alive Keep-Alive: timeout=5 Cache-Control: nocache, private Vary: Accept-Encoding

May it's kind of stupid, but is it something about the auth algorithm - md5? The password is in plain-text and not encrypted by md5.

EDIT: It seems, that it's not about MD5 - got same response after coding password to md5.

ONE MORE Edit: Okay, same client works pretty well on HTTP Layer (and another INSTANCE!) instead HTTPS.. So something is broken on HTTPS?

I had the same problem, in my case server had a 301 redirect to url with double slash. In browser's address bar it was invisble, when I checked server response to my browser I realized that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM