Fixing JWT Expiration Issues with PHP-JWT - 401 Status Not Returned

I encountered an issue where expired JWT tokens weren’t returning a 401 Unauthorized status in my PHP application. After debugging, I found the problem in my JWT middleware.

Issue

When sending expired tokens to the API:

  • The DecodeJwt() function failed

  • The middleware silently ignored this failure

  • No 401 status was returned

  • The request continued processing

Solution

I modified the middleware to properly handle JWT validation errors:

try {

$jwt = DecodeJwt($token);

// Process valid token...

} catch (\Throwable $e) {

// Handle expired/invalid token

$response = ResponseFactory()->createResponse();

$responseBody = [

"success" => false,

"error" => $e->getMessage(),

"status" => "unauthorized",

"timestamp" => date('Y-m-d H:i:s')

];

$response->getBody()->write(json_encode($responseBody));

return $response->withStatus(401)->withHeader('Content-Type', 'application/json');

}

This fixed the issue, and now expired tokens properly return 401 errors.

Has anyone else encountered this problem or found a more elegant solution?

You may update template from Tools → Update Template, re-generate ALL the script files, and try again.

Hi, I worked with the support team on the issue and there is now a new version of the template, which is working fine.

Philipp