JWT解码尝试捕获 [英] JWT Decode try catch

查看:297
本文介绍了JWT解码尝试捕获的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的小型项目中使用JWT进行授权(REST API). JWT看起来非常适合我的项目.

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

假设我有以下代码:

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

此代码将返回JWT官方页面上的数组.

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'));

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

PHP将发出一个异常/错误,我该如何处理这些异常/错误,以便最终用户看不到它们(连同我在错误中的秘密密钥).

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).

我尝试执行以下操作:

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

推荐答案

我遇到了同样的问题,解决此错误的解决方案是:

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

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

因此您的代码变为:

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

在这里找到: https://github.com/firebase/php-jwt/issues /50

这篇关于JWT解码尝试捕获的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆