Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JWT Decode try catch

Tags:

php

jwt

I am using JWT for authorization (REST API) in my tiny project. JWT looks to be a very suitable for my project.

Let's say I have this code:

$key = "secret";
$token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ"
$data = JWT::decode($token, $key, array('HS256'));

This code will return an array as on the official page of JWT.

But if I try to run the following codes:

$key = "secret";
$token = "abc.abc.abc"
$data = JWT::decode($token, $key, array('HS256'));

or

$key = "secret";
$token = "abc"
$data = JWT::decode($token, $key, array('HS256'));

PHP will issue an exception/error, how can I handle those exceptions/errors so the end-user will not see them (together with my secret key in the error).

I've tried to do the following:

try {
    $key = "secret";
    $token = "abc"
    $data = JWT::decode($token, $key, array('HS256'));
} catch (Exception $e) { // Also tried JwtException
    echo 'error';
}
like image 377
Coder Avatar asked Jan 05 '17 18:01

Coder


1 Answers

I come just to the same issue and the solution to catch this error is:

catch (\Exception $e) not catch (Exception $e)

so your code become:

try {
    $key = "secret";
    $token = "abc"
    $data = JWT::decode($token, $key, array('HS256'));
} catch (\Exception $e) { // Also tried JwtException
    echo 'error';
}

found here: https://github.com/firebase/php-jwt/issues/50

like image 173
Hamza Harbili Avatar answered Oct 13 '22 21:10

Hamza Harbili