【问题标题】:PHP - JWT get token wrong number of segmentsPHP - JWT 获取令牌错误的段数
【发布时间】:2019-07-18 06:45:49
【问题描述】:

我需要使用 JWT 使用 API,为此,我使用 GuzzleFirebase PHP-JWT 从 PHP 构建 API 客户端

API 的文档说:准备并发布 JWT 以进行授权。

端点网址:

https://api.example.com/auth

JWT 包含三个组件,标头、有效负载和签名。

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 资源的新手,我想我正在构建错误的方法。我有一些静态方式的值仅用于测试目的。

【问题讨论】:

    标签: php firebase jwt guzzle6


    【解决方案1】:

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

    ....
    $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 得到了正确的响应。

    【讨论】:

    • 我们可以作为不记名发送吗?
    • 通常是的,但出于某种原因,在这个 API 中,他们专门实现了它,以便在标题中指示键 'body' 内的令牌而不是 'Authorization'
    猜你喜欢
    • 2018-03-16
    • 1970-01-01
    • 2018-03-04
    • 2021-05-14
    • 2016-04-30
    • 2021-10-20
    • 2021-01-29
    • 2021-01-07
    • 1970-01-01
    相关资源
    最近更新 更多