2

我正在制作一个处理API

所以我试图调用API使用cURL,问题是api将处理执行此curl调用的服务器cookie而不是使用应用程序的客户端cookie...

例如:客户端已经登录到api,但是当我检查客户端是否通过curl调用登录时,api响应你没有被授权

那么如何API与客户端 cookie 进行交易或将客户端的 cookie 传递给API

4

2 回答 2

1

您需要使用 cookiefile,如下所示:

        # Set the cookiefile name, which will allow us to store the cookie and present it later for all requests that require it...
        $cookiefile = tempnam("/tmp", "cookies");
        $agent     = "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)";

        # Set the user name and password values
        $user      = $argv[1];
        $password      = $argv[2];

        # The API url, to do the login
        $url = "https://some_site.com/login.php?WID=$user&PW=$password";

        # Initialise CURL
        $ch = curl_init();

        # Set all the various options
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_userAGENT, $agent);
        curl_setopt($ch, CURLOPT_POST, 0); // set POST method
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_COOKIEFILE, $cookiefile);
        curl_setopt($ch, CURLOPT_COOKIEJAR, $cookiefile);
        curl_setopt($ch, CURLOPT_userPWD, $user.":".$password);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);

        # Execute the first CURL request to perform the login...
        $results = curl_exec($ch);

        # Setup our next request...
        $job_id_number      = $argv[3];
        $url = "https://some_site.com/request.php?task=add&taskID=$job_id_number";

        # We do not have to initialise CURL again, however we do need to adjust our URL option for the second request...
        curl_setopt($ch, CURLOPT_URL, $url);

        #Remember to use the same cookiefile as above  
        curl_setopt($ch, CURLOPT_COOKIEFILE, $cookiefile);
        curl_setopt($ch, CURLOPT_COOKIEJAR, $cookiefile);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);

        # Execute the second CURL call  to perform the action (using the cookie we retrieved from earlier)
        $results = curl_exec($ch);

        echo "$results";
于 2013-03-15T16:59:20.447 回答
0

您应该检查 API 的文档。也许文档描述了一种授权客户端的方法。

这样它就行不通了,因为 cookie 是在客户端(在浏览器中)设置的,而不是在您的服务器上。因此,当您进行 cURl 调用时,cookie 数据不会包含在请求中。通过 Javascript 的 API 调用可以工作,因为这是客户端发送的请求(带有所需的 cookie)

于 2013-03-15T17:00:25.530 回答