Skip to content
Advertisement

PHP JWT:: **Decode** expired Token

I use a JWT (Json Web Token) which has a refresh token (GUID) in the payload. In general I use Firebase JWT to create/encode and decode the JWT.

I would like to decode an expired JWT in PHP and then use the refresh token from its payload to create a new JWT (as long the refresh token is still valid). If I decode the JWT with Firebase it throws an exception (expired) and doesn’t return the decoded token.

How can I decode safely an expired JWT and get access to it’s payload? Can I just catch the expired Exception or is this unsafe and it could also catch maybe other errors. And if I do so how do I get access to the payload? Thanks for you helps and inputs.

Advertisement

Answer

Here my solution:

  1. Try and Catch with decode of Firebase
  2. Catch the exception for expired token
  3. In this catch decode the token with base64 to get the refresh token

Only if the token is valid and expired it gets decoded with normal base64 (so no check of the signature). But the signature check is done before with the decode in step 1.

Here the pseudo code of it:

$jwt = getBearerToken();

try {

$decoded = JWT::decode($jwt, $key, array('HS256'));
$refresh_token=$decoded->data->refresh_token;

}

catch (Exception $e){

if($e->getMessage() == "Expired token"){
    list($header, $payload, $signature) = explode(".", $jwt);
    $payload = json_decode(base64_decode($payload));
    $refresh_token = $payload->data->refresh_token;

} else {

    // set response code
    http_response_code(401);

    // show error message
    echo json_encode(array(
        "message" => "Access denied.",
        "error" => $e->getMessage()
    ));
    die();
    }
}
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement