无法使用基本授权和cURL登录服务器.(用户/通行证+证书)


Cannot login to server with Basic Authorization and cURL. (User/pass + certificate)

我正试图从我自己的应用程序访问服务器及其数据。要登录,我需要一个用户名和密码加上一个证书,我有。我的问题是,我显然发送了错误的信息,因为我一直得到401。我应该能够,在这个页面上,得到一些HAL+JSON数据从这个服务器登录后。它从上一页张贴了一个字段,并应提交给服务器以获取数据。

下面是我的代码:
$username = 'foo';
$password = 'bar';
$auth_token = $username . '-' . $password;
$url = 'https://data.service.com'.$_POST['url'].'?callback=?';
$ch = curl_init($url); 
/* Upon receiving the right certificate 
*  I should have a cookie with this information. 
*/
$data_string = array('cert_url' => 'https://data.service.com/cert/2364o872ogfglsgw8ogiblsjy');    
/* That hash at the end corresponds to the Public Key ID 
*  in the certificate. No idea how to retrieve this, 
*  or if I need to do it to login
*/
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);      
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
curl_setopt($ch, CURLOPT_HEADER, true);     
curl_setopt($ch, CURLOPT_HTTPHEADER, array(   
      'Accept: application/javascript',
      'Access-Control-Allow-Origin: *',                                                                       
      'Content-Type: application/javascript',
      "Authorization: Basic " . base64_encode($username.":".$password)
   ));  
curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);  
curl_setopt($ch, CURLOPT_FAILONERROR, true);  
curl_setopt($ch, CURLOPT_UNRESTRICTED_AUTH, true);    
curl_setopt($ch, CURLOPT_VERBOSE, true);                                                                                                            
$result = curl_exec($ch);  
if(curl_exec($ch) === false){
      echo 'Curl error: ' . curl_error($ch);
      print_r(error_get_last());
} else {
      echo 'Operation completed without any errors';
curl_close($ch);
$response = json_decode($result, true); ?>

看看http://www.php.net/manual/ru/function.curl-setopt.php#98164

尽量不要使用

"Authorization: Basic " . base64_encode($username.":".$password)

或者让curl选择一个验证方法,试试

curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY); 

如果curl不喜欢远程服务器上的ssl证书,可以这样做:

curl_setopt( $ch , CURLOPT_SSL_VERIFYPEER , false ); 
curl_setopt( $ch , CURLOPT_SSL_VERIFYHOST , false );

注:你确定CURLOPT_RETURNTRANSFER在你的情况下应该是假的吗?

相关文章: