PHP - JWT get token wrong number of segments
The error message Wrong number of segments indicates that your API endpoint is failing to parse the incoming request body as a valid JWT string. This is almost certainly an issue with how you are constructing the HTTP request payload, not with the JWT library itself or the signature generation logic.
In standard OAuth2 and JWT flows, authentication tokens must be transmitted in specific ways depending on the endpoint configuration. The error arises because you are passing the raw token string as a URL parameter (or part of the URL) rather than including it in the HTTP request body where the API expects it.
Examining the Request Construction
Looking closely at your Guzzle implementation, there is a critical distinction between how you define headers and how you pass data to the server. You are currently executing this line:
$response = $client->request('POST', 'https://api.example.com/auth', $headers, $token);
Here, $token is being interpreted as an optional URL query parameter or a fragment identifier, depending on Guzzle's internal logic for that specific overload. More importantly, you are defining the header 'content_type' => 'application/x-www-form-urlencoded'. This tells the API to expect form data in the body (e.g., key=value&key2=value2), not a raw JSON string or a raw JWT string.
However, most modern APIs expecting a JWT in the request body expect either:
- A specific header like
Authorization: Bearer <token>with an empty or JSON body. - A raw JSON payload where the token is a field (e.g.,
{"token": "<your_token>"}) with content typeapplication/json. - Form-encoded data where the token is a specific field (e.g.,
grant_type=jwt&token=<your_token>) if usingapplication/x-www-form-urlencoded.
The error "Wrong number of segments" specifically happens on the server side when it attempts to split your input by dots (.) to extract the header, payload, and signature. If the API receives a form-encoded string or an empty body instead of the raw JWT string, that split fails immediately.
Correcting the Guzzle Implementation
To fix this, you need to ensure the raw token string reaches the server exactly as generated by JWT::encode(). You should not be passing $token as the fourth argument to request() in a way that treats it as a query parameter. Instead, construct the body explicitly.
If the API documentation implies the token is sent via POST body without specifying a JSON wrapper, you likely need to set the content type to application/json and pass the token as a string value, or if it expects form data, ensure the field name matches what the backend requires.
Here is a corrected approach assuming the standard pattern of sending a raw token in the body:
$token = JWT::encode($payload, $key, $alg);
$client = new \GuzzleHttp\Client();
// Explicitly define the headers and the body
$options = [
'headers' => [
'Content-Type' => 'application/json',
// If the API expects a Bearer header instead of body token:
// 'Authorization' => 'Bearer ' . $token
],
'body' => json_encode([
'token' => $token,
'clientId' => 'A1b2C3d4E5'
// Only include clientId if the API expects it in the body, not as a JWT claim
])
];
try {
$response = $client->request('POST', 'https://api.example.com/auth', $options);
$body = (string) $response->getBody();
// Verify the response before decoding to prevent crashes on empty bodies
if ($body === '') {
throw new \Exception("Empty response body received.");
}
$data = json_decode($body, true);
if (!isset($data['success']) || !$data['success']) {
// Log the raw data to debug further
error_log("API Error: " . print_r($data, true));
}
} catch (\GuzzleHttp\Exception\ConnectException $e) {
// Handle connection errors specifically
throw new \Exception("Could not connect to API.");
}
Debugging the JWT Claims
There is a secondary logical issue in your payload generation. You are including clientId inside the JWT payload claims:
$payload = [
'clientId' => 'A1b2C3d4E5',
'requestTime' => $requestTime
];
While valid within a JWT structure, many APIs expect the clientId to be sent as an independent parameter in the request body or headers rather than encoded inside the token. If the API documentation states "Prepare and post a JWT for authorization," it usually means the token is the credential. Sending clientId twice (once in the claim, once implied by the endpoint context) can sometimes confuse stateless validators if they are expecting a strict schema.
Additionally, ensure your $requestTime format matches exactly what the API expects. The documentation specifies "Y-m-d H:i:s" in GMT. Your code uses date('Y-m-d H:i:s T', time()). Note that T is not a valid PHP date format character for timezones; it will likely append a literal 'T' to your timestamp (e.g., 2023-10-27 10:00:00T), which breaks the requestTime claim validation on the server side. You should use date('Y-m-d H:i:s', time()) and ensure your server's timezone settings are aligned with GMT if you haven't set a specific offset.
Summary of Fixes
- Stop passing
$tokenas an argument torequest(): Use the explicit options array with abodykey. - Adjust Content-Type: Switch from
application/x-www-form-urlencodedtoapplication/jsonunless the API explicitly requires form data, and ensure the token is sent as a JSON field or part of the raw body string. - Fix the Date Format: Remove the invalid
Tfrom your date string to prevent timestamp validation errors. - Verify Payload Scope: Double-check if
clientIdbelongs in the JWT claim or should be separate request data.
By aligning the HTTP request structure with what the server expectsâa raw, valid JWT string in the body or headersâand correcting the timestamp format, the "Wrong number of segments" error will resolve itself.