PHP - JWT get token wrong number of segments

Ale picture Ale · Feb 24, 2019 · Viewed 11.5k times · Source

I need consume a API using JWT, for this, I'm build a API client from PHP with using Guzzle and Firebase PHP-JWT

The documentation of API say: Prepare and post a JWT for authorization.

Endpoint URL:

https://api.example.com/auth

The JWT has three components, the header, the payload and the signature.

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 )

The code to get token is the follow:

<?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());
    }
    ...
}

If print $data I get

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

My problem: I do not know why this error is due and if I am sending the request in some incorrect way.

I'm a newbie consuming API resource with JWT and I guess I'm building the wrong way something. I have some values of static way only to test purpose.

Answer

Ale picture Ale · Feb 24, 2019

My mistake was in how I sent the token, since I had to send it in the body of the request in the following way:

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

With this I get the correct response from the API.