使用Curl i对服务器进行身份验证,将会话cookie写入文件(cookie)并在下次请求时使用它。
curl --basic --digest --user restuser:restpassword --cookie-jar cookies --insecure https://xxx.example.dom/api/authentication
从cookies文件中复制session_id cookie值并使用它:
curl --cookie session_id=910f5e79aaf44dd8dc3c26e79e6d08bb22a86674 --insecure https://xxx.example.dom/api/configuration
我想用Guzzle 6.1.1实现这一点。它通过基本身份验证获取会话cookie,但不将其传递给下一个请求。
use GuzzleHttp\Client;
use GuzzleHttp\Cookie\SessionCookieJar;
$jar = new \GuzzleHttp\Cookie\SessionCookieJar('session_id', true);
$client = new GuzzleHttp\Client([
'base_uri' => REST_URL,
'cookies' => $jar,
'debug' => true
]);
// authenticate
$res = $client->request('GET', 'authentication', [
'verify' => false,
'auth' => [REST_USER, REST_PASS]
]);
// send authenticated request
$res = $client->request('GET', 'configuration', [
'verify' => false
]);
根据我对文档的理解,通过设置持久会话cookie并在创建客户端时使用它,Guzzle应该在下一个请求中自动发送它我错了吗?
感谢。
注意:这是调试输出。
HTTP/1.1 200 OK
X-Frame-Options: SAMEORIGIN
Content-Length: 129
Content-Language: en
Server: REST
Allow: DELETE, GET, HEAD, POST, PUT
Date: Sun, 07 Feb 2016 03:53:02 GMT
Content-Type: application/json
Set-Cookie: session_id=488df4282feb714f3fd2e36a1bb02ea06f923eb8; expires=Sun, 07 Feb 2016 04:13:02 GMT; httponly; Path=/; secure
* Connection #0 to host xxx.example.dom left intact
200Array{
"_meta": {
"href": "/api/authentication",
"next": "/api",
"transaction": "/api/transaction"
}
}
* Found bundle for host xxx.example.dom: 0x100c18510
* Re-using existing connection! (#0) with host xxx.example.dom
* Connected to xxx.example.dom (192.168.68.100) port 443 (#0)
> GET /api/configuration HTTP/1.1
User-Agent: GuzzleHttp/6.1.1 curl/7.41.0 PHP/5.6.7
Host: xxx.example.dom
HTTP/1.1 401 Unauthorized
X-Frame-Options: SAMEORIGIN
Content-Length: 284
Content-Language: en
Server: REST
Allow: DELETE, GET, HEAD, POST, PUT
Date: Sun, 07 Feb 2016 03:53:02 GMT
Content-Type: application/json
Set-Cookie: session_id=d1c231b1a093a1d9a9041597b3d708d32203e3f0; expires=Sun, 07 Feb 2016 04:13:02 GMT; httponly; Path=/; secure
* Connection #0 to host xxx.example.dom left intact
<b>Fatal error</b>: Uncaught exception 'GuzzleHttp\Exception\ClientException' with message 'Client error: `GET https://xxx.example.dom/api/configuration` resulted in a `401 Unauthorized` response: