PHP - JWT 获取令牌的段数错误

PHP - JWT get token wrong number of segments

我需要使用 JWT 使用 API,为此,我使用 Guzzle and Firebase PHP-JWT

从 PHP 构建了一个 API 客户端

API 的文档说:准备并post 一个用于授权的 JWT。

端点URL:

https://api.example.com/auth

JWT 具有三个组件,header、有效负载和签名。

Header: { "alg": "HS256", "typ": "JWT" }
Payload: { "clientId": "YOUR_CLIENT_ID","requestTime": "Y-m-d H:i:s" } (requestTime in GMT)
Signature: HMACSHA256( base64UrlEncode(header) + "." + base64UrlEncode(payload), YOUR_CLIENT_SECRET )

获取token的代码如下:

<?php

use \Firebase\JWT\JWT;

class Client 
{
    ...
    private function getAuthToken() 
    {
        $requestTime = date('Y-m-d H:i:s T', time());
        $payload = [
            'clientId' => 'A1b2C3d4E5',
            'requestTime' => $requestTime
        ];

        $key = '9z8Y7x6w5V4';
        $alg = 'HS256';
        $token = JWT::encode($payload, $key, $alg);

        $client = new \GuzzleHttp\Client;
        $headers = ['content_type' => 'application/x-www-form-urlencoded'];
        $response = $client->request('POST', 'https://api.example.com/auth', $headers, $token);
        $body = $response->getBody();
        $data = \json_decode($body->getContents());
    }
    ...
}

如果打印 $data 我得到

stdClass Object
    (
        [success] => false
        [data] => Wrong number of segments 
    )

我的问题: 我不知道为什么会出现此错误,以及我是否以某种不正确的方式发送请求。

我是一个使用 JWT 消耗 API 资源的新手,我想我正在以错误的方式构建某些东西。我有一些静态方法的值只是为了测试目的。

我的错误在于发送令牌的方式,因为我必须按以下方式在请求正文中发送令牌:

....
$client = new \GuzzleHttp\Client;
$headers = [
    'content_type' => 'application/x-www-form-urlencoded',
    'body' => $token
];
$response = $client->request('POST', 'https://api.example.com/auth', $headers);
....

有了这个,我从 API 得到了正确的回应。