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.

1 Answer 1

4

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.

2
  • Can we send it as a bearer? May 30, 2020 at 19:39
  • 2
    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'
    – Alejandro
    May 31, 2020 at 17:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.