dongye4192 2013-09-06 19:13
浏览 39
已采纳

使用PHP POST到Web服务的摘要式身份验证的客户端部分

I'm trying to POST to a Web Service (not RESTful) and get response through PHP. However, that web service requires Digest Authentication.

I've been searching online and found most of the discussions and articles are about the other way around (Requesting Digest Authentications to users), instead of responding it, using PHP.

I'm able to generate the Digest response using the code this thread provide:HTTP Digest authenticating in PHP, but the problem is to sending it along with(or not?) the POST data.

Here's the code I'm using:

$domain = "https://api.example.com";
$uri = "/ws.asmx/do";

// get headers
$response1_array = get_headers($web_service_url);
// get request part of digest auth
$response1 = $response1_array[5];
// get things behind "WWW-Authenticate:"
$response1 = substr($response1, 18);

// response() is a invented function to calculate the response according to the RFC2617
$response2 = response($response1, "username", "password", "GET", $uri);

// manually add some headers for POST, and fill out the parts that the calculation function missed
// for auth
$header =  
        "Host: api.example.com
" .
        "Content-Type: application/x-www-form-urlencoded
" .
        "Authorization: " . $response2 . ", nc=\"00000001\", opaque=\"0000000000000000\"" . "
Content-Length: 0

";

// echo the response from server
echo do_post_request($web_service_url, "", $header);

function do_post_request($url, $data, $optional_headers = null)
{
  $params = array('http' => array(
              'method' => 'POST',
              'content' => $data
            ));
  if ($optional_headers !== null) {
    $params['http']['header'] = $optional_headers;
  }
  $ctx = stream_context_create($params);

  $fp = fopen($url, 'rb', false, $ctx);

  if (!$fp) {
    throw new Exception("Problem with $url");
  }
  $response = stream_get_contents($fp);
  if ($response === false) {
    throw new Exception("Problem reading data from $url");
  }
  return $response;
}

In the response:

$response1(from web service):
    Digest realm="example.com", nonce="OS82LzIwMTMgMTI6MDI6NDYgUE0", opaque="0000000000000000", stale=false, algorithm=MD5, qop="auth"

$response2(I calculated given the server response):
    Digest username="username", realm="example.com", nonce="OS82LzIwMTMgMTI6MDI6NDYgUE0", uri="/ws.asmx/do", cnonce="1378494106", nc="1", response="0f96788854cf2098ba22c6121529d7de", qop="auth"

the final (2nd) response from server:
    Warning: fopen(https://api.example.com/ws.asmx/do): failed to open stream: HTTP request failed! HTTP/1.1 500 Internal Server Error in ...

I don't understand why server responded 500 error in this case. Is there anything wrong in the code? Or has anyone met this problem before and solved it and can help me with a solution?

Regards,

Mylo

  • 写回答

1条回答 默认 最新

  • dongxie3701 2013-11-09 01:22
    关注

    Eventually solved it with cURL after 2 days' fumbling. I guess this is the first time a piece of ready-made PHP code for digest auth is posted, hopefully it can help someone who are in the same ditch as I was in.

    Code:

    <?php
    
    error_reporting(E_ALL); 
    ini_set( 'display_errors','1');
    
    $url = "https://api.example.com/ws.asmx/do";
    $username = "username";
    $password = "pwd";
    $post_data = array(
            'fieldname1' => 'value1',
            'fieldname2' => 'value2'
      );
    
    $options = array(
            CURLOPT_URL            => $url,
            CURLOPT_HEADER         => true,    
            CURLOPT_VERBOSE        => true,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_SSL_VERIFYPEER => false,    // for https
            CURLOPT_USERPWD        => $username . ":" . $password,
            CURLOPT_HTTPAUTH       => CURLAUTH_DIGEST,
            CURLOPT_POST           => true,
            CURLOPT_POSTFIELDS     => http_build_query($post_data) 
    );
    
    $ch = curl_init();
    
    curl_setopt_array( $ch, $options );
    
    try {
      $raw_response  = curl_exec( $ch );
    
      // validate CURL status
      if(curl_errno($ch))
          throw new Exception(curl_error($ch), 500);
    
      // validate HTTP status code (user/password credential issues)
      $status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
      if ($status_code != 200)
          throw new Exception("Response with Status Code [" . $status_code . "].", 500);
    
    } catch(Exception $ex) {
        if ($ch != null) curl_close($ch);
        throw new Exception($ex);
    }
    
    if ($ch != null) curl_close($ch);
    
    echo "raw response: " . $raw_response; 
    
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)