对 cURL 和 GuzzleHTTP 的相同请求。不同的反应

Same request on cURL and GuzzleHTTP. Different responses

我在 API 中与 GuzzleHTTP 战斗。我正在使用 Lumen 开发 API 以便与 HashiCorp Vault API 进行通信。为此,我安装了 GuzzleHTTP 来进行 API 调用。

例如,我正在尝试根据特定角色为数据库用户生成凭据。在命令行中,cURL 请求使用新用户的凭据响应我。使用 Guzzle 时不会给我任何与新创建的用户相关的信息。

我是 Guzzle 的新手,很高兴收到任何建议。

cURL 请求如下所示:

curl -X GET \
    --header "X-Vault-Token: $VAULT_TOKEN" \
    http://192.168.1.3:8200/v1/database/creds/my-role | json_pp

响应给了我想要的凭据:

{
   "request_id" : "3eacc89b57b-2e2e-af6f-849f-868bdbfd2dc5e1",
   "wrap_info" : null,
   "renewable" : true,
   "data" : {
      "username" : "randomgeneratedusername",
      "password" : "randomgeneratedpassword"
   },
   "auth" : null,
   "lease_duration" : 3600,
   "warnings" : null,
   "lease_id" : "database/creds/my-role/randomsecretname"
}

当我的 Guzzle 代码如下所示时:

class MySQLVaultAPI extends VaultAPI
{
    public function createUser() {
        $response = $this->getClient()->request('GET', $this->url.'/database/creds/my-role',
            ['headers' => $this->headers]);

    }
}

并且:

class VaultAPI
{
    protected string $url;
    protected Client $http;
    protected array $headers;

    public function __construct(Client $client)
    {
        $this->url = 'http://192.168.1.3:8200/v1';
        $this->http = $client;
        $this->headers = [
            'X-Vault-Token' => 'secrettoken',
            'Accept' => 'application/json',
        ];
    }
}

以及来自 GuzzleHTTP 的响应(我在 $response 对象上使用了 symfony dumper):

^ GuzzleHttp\Psr7\Response {#43 ▼
  -reasonPhrase: "OK"
  -statusCode: 200
  -headers: array:4 [▼
    "Cache-Control" => array:1 [▶]
    "Content-Type" => array:1 [▶]
    "Date" => array:1 [▶]
    "Content-Length" => array:1 [▶]
  ]
  -headerNames: array:4 [▼
    "cache-control" => "Cache-Control"
    "content-type" => "Content-Type"
    "date" => "Date"
    "content-length" => "Content-Length"
  ]
  -protocol: "1.1"
  -stream: GuzzleHttp\Psr7\Stream {#21 ▼
    -stream: stream resource @137 ▶}
    -size: null
    -seekable: true
    -readable: true
    -writable: true
    -uri: "php://temp"
    -customMetadata: []
  }
}

好的,

我找到答案了。所有内容都在GuzzleHttp\Psr7\Stream

所以我不得不在我的 VaultAPI 服务中添加其他方法

public function getFullBody(Stream $responseBody)
{
    $responseBody->seek(0);
    $output = json_decode(trim($responseBody->getContents()), true);
    if ($output === null) {
        throw new \Exception('Error parsing response JSON ('.json_last_error().')');
    }

    return $output;
}

然后在我的 MySQLVaultAPI 中调用它

public function createUser() {
    $response = $this->getClient()->request('GET', $this->url.'/database/creds/my-role',
        ['headers' => $this->headers]);
    return $this->getFullBody($response->getBody());
}