PHP - JWT get token wrong number of segments
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.
Ale
IHE engineer: Consultant interoperable processes, developing standards for interoperability. Knowledge of DICOM, HL7, IHE. Knowledge of open source tools like PHP, HTML5, CSS, Javascript, Python, AngularJS, Node.js, Express between some code. Development projects management of digital medical images (RIS, PACS, HIS).
Updated on June 28, 2022Comments
-
Ale almost 2 years
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.
-
Wail Hayaly almost 4 yearsCan we send it as a bearer?
-
Ale almost 4 yearsGenerally 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'