【问题标题】:Guzzle - Command & Services: Basic HTTP AuthGuzzle - 命令和服务:基本 HTTP 身份验证
【发布时间】:2016-11-16 12:44:20
【问题描述】:

我之前成功使用了guzzlehttp/guzzle v.6.* 包,其身份验证参数如下:

        $client = new GuzzleClient([
            'base_uri'  => $base_uri ,
            'auth'      => [ $username, $password ]
        ]);

这很好用。不过,我现在正在尝试使用 "guzzlehttp/guzzle-services": "0.5.*" 包来更轻松地使用 API 端点。

使用 guzzle-services 的 Github page 中的以下示例:

use GuzzleHttp\Client;
use GuzzleHttp\Command\Guzzle\GuzzleClient;
use GuzzleHttp\Command\Guzzle\Description;

$client = new Client();
$description = new Description([
    'baseUrl' => 'http://httpbin.org/',
    'operations' => [
        'testing' => [
            'httpMethod' => 'GET',
            'uri' => '/get/{foo}',
            'responseModel' => 'getResponse',
            'parameters' => [
                'foo' => [
                    'type' => 'string',
                    'location' => 'uri'
                ],
                'bar' => [
                    'type' => 'string',
                    'location' => 'query'
                ]
            ]
        ]
    ],
    'models' => [
        'getResponse' => [
            'type' => 'object',
            'additionalProperties' => [
                'location' => 'json'
            ]
        ]
    ]
]);

$guzzleClient = new GuzzleClient($client, $description);
$result = $guzzleClient->testing(['foo' => 'bar']);

使用"guzzlehttp/guzzle-services": "0.5.*" 包时,我应该如何以及在哪里添加身份验证参数?

我已经尝试了所有可能的方法,但无法让它发挥作用。

【问题讨论】:

    标签: php web-services rest guzzle guzzle6


    【解决方案1】:

    我已经成功地通过以下代码使用 Guzzle 6.2.2 和 Guzzle Services 1.0.0 和 Basic Auth:

    $config['auth'] = array('user', 'pass');
    $client = new Client($config);
    

    当然,您可能需要其他设置,但对于基本身份验证,仅需要此设置。检查GuzzleHttp\Client::applyOptions 类方法以查看 Guzzle 何时使用此设置。

    它与@revo 答案非常相似,但没有主“默认”数组。

    这些是我的 guzzle 安装包:

    "
    gimler/guzzle-description-loader     v0.0.2  Load guzzle service description from various file formats
    guzzlehttp/command                   1.0.0   Provides the foundation for building command-based web service clients
    guzzlehttp/guzzle                    6.2.2   Guzzle is a PHP HTTP client library
    guzzlehttp/guzzle-services           1.0.0   Provides an implementation of the Guzzle Command library that uses Guzzle service descriptions to describe web services, se...
    guzzlehttp/promises                  1.3.0   Guzzle promises library
    guzzlehttp/psr7                      1.3.1   PSR-7 message implementation
    "
    

    【讨论】:

      【解决方案2】:

      我怀疑Description 类是否提供了一种将身份验证信息合并到请求的方法。但是您可以在 Guzzle v5.x 中实例化新的 Client 时添加它们,如下所示:

      $client = new Client(['defaults' => ['auth' => ['user', 'pass']]]);
      

      【讨论】:

      • 我试过了,但至少在 guzzlehttp/guzzle v.6.* 包中不起作用。
      猜你喜欢
      • 2015-09-07
      • 2014-04-09
      • 2011-11-08
      • 2013-09-01
      • 2015-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-17
      相关资源
      最近更新 更多