PHP - JWT get token wrong number of segments
Asked Answered
P

1

7

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.

Pace answered 24/2, 2019 at 20:55 Comment(0)
P
5

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.

Pace answered 24/2, 2019 at 21:27 Comment(2)
Can we send it as a bearer?Dint
Generally yes, but for some reason in this API they specifically implemented it so that the token inside the key 'body' was indicated in the headers instead of 'Authorization'Pace

© 2022 - 2024 — McMap. All rights reserved.