php - 如何向 GuzzleHTTP 请求对象添加身份验证以进行异步处理

标签 php authentication guzzle

我正在创建多个以下 GuzzleHttp\Psr7\Requests:

use GuzzleHttp\Psr7\Request;

$myRequest = new Request(
    'GET',
    $someUri
);

并将它们保存在一个数组中:$guzzleRequests

然后我创建一个池来同时执行所有请求:

    use GuzzleHttp\Pool;

    $testPool = new Pool($testClient = new \GuzzleHttp\Client(), $guzzlePromises,
    [
        'fulfilled' => function ($response, $index) {
            // this is delivered each successful response
            var_dump($response);
        },
        'rejected' => function ($reason, $index) {
            // this is delivered each failed request
            var_dump($reason);
        }
    ]);
    // Initiate the transfers and create a promise
    $promise = $testPool->promise();

    // Force the pool of requests to complete.
    $promise->wait();

(取自文档:“并发请求”下的 http://guzzle.readthedocs.org/en/latest/quickstart.html)

这适用于不需要身份验证并返回 200 OK 状态的 URI 请求。

如何向请求添加身份验证,以便池可以同时针对受基本 HTTP 授权保护的 API 运行多个请求?

*编辑1:

回应pinkal vansia : 我按照你的建议添加了标题:

$headers = [
    'Authorization: Basic '. base64_encode($this->username.':'.$this->password),
];
$myRequest = new Request(
    'GET',
    $url,
    $headers
);`

并转储 header :

array (size=2)
    'Host' => 
    array (size=1)
        0 => string '<myHost>' (length=27)
0 => 
    array (size=1)
        0 => string 'Authorization: Basic <veryLongAuthenticationString>' (length=<stringLength>)`

响应仍然产生未授权:

private 'reasonPhrase' => string 'Unauthorized' (length=12)
private 'statusCode' => int 401

* 最终编辑:

我终于让它运行起来了。事实证明,pinkal vansia已经很接近了。

确切的形式是最后一个问题。 Michael Downling's评论让我走上了正确的轨道。

Authorization header 是可行的方式,它需要是键 => 值映射。

最后的样子是这样的:

$url = $myUrl.'?'.http_build_query($this->queryArray);

// ------------ Specify Authorization => key to make it work!!!
$headers = [
    'Authorization' => 'Basic '. base64_encode($this->username.':'.$this->password)
];
// -----------------------------------------------------------

$myRequest = new Request(
    'GET',
    $url,
    $headers
);

return $myRequest;

最佳答案

您可以在请求中添加基本身份验证 header ,如下所示

$headers = [
    'Authorization: Basic '. base64_encode($this->username.':'.$this->password)
];

$myRequest = new Request(
    'GET',
    $url,
    $headers
);

希望对您有所帮助。

更新

正如@worps 指出的那样,header 需要是一个key => value 对。所以最终的解决方案如下所示,

$headers = [
    'Authorization' => 'Basic '. base64_encode($this->username.':'.$this->password)
];

$myRequest = new Request(
    'GET',
     $url,
     $headers
);

关于php - 如何向 GuzzleHTTP 请求对象添加身份验证以进行异步处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31052003/

相关文章:

facebook - Session.ReauthorizeRequest 的替代品是什么?

php - guzzle ver 6 发布方法不起作用

php - 如何使用 PHP Curl 或 Guzzle 客户端使用动态用户代理 header

php - Guzzle 返回 500 错误

php - SQL查询有问题......在PHP中(非常简单的代码)

php - C++ 相当于 PHP 的 pack()

php - 在 Javascript 中存储大型 Cookie...如何

表示文件路径的 PHP 多维数组

api - REST API 身份验证 - 这足够吗?

asp.net-core - 如何修改.Aspnetcore.Identity.Application Cookie名称?