【问题标题】:PHP Slim decoding JWT tokenPHP Slim 解码 JWT 令牌
【发布时间】:2018-08-14 17:39:06
【问题描述】:

我是 PHP 新手,使用 jwt 授权令牌开发 RESTful 服务。我关注了this GitHub example 并且在一定程度上理解了代码,但我在这条线上遇到了错误$stmt->bindParam("user_id", $decoded->context->user->user_id);

注意:C:\xampp\htdocs\slim2\src\routes.php 中数组到字符串的转换上线。

请帮我解决这个问题,我不明白 context->user->user_id 是从哪里来的。完整代码如下

// The route to get a secured data.
$app->get('/restricted', function (Request $request, Response $response) {

$jwt = $request->getHeaders();

$key = "testsecretekey";

try {
    $decoded = JWT::decode($jwt['HTTP_AUTHORIZATION'][0], $key, array('HS256'));
} catch (UnexpectedValueException $e) {
    echo $e->getMessage();
}

if (isset($decoded)) {
    $sql = "SELECT * FROM tokens WHERE user_id = :user_id";

    try {
        $db = $this->db;
        $stmt = $db->prepare($sql);
        $stmt->bindParam("user_id", $decoded->context->user->user_id);
        $stmt->execute();
        $user_from_db = $stmt->fetchObject();
        $db = null;

        if (isset($user_from_db->user_id)) {
            echo json_encode([
                "response" => "This is your secure resource !"
            ]);
        }
    } catch (PDOException $e) {
        echo '{"error":{"text":' . $e->getMessage() . '}}';
    }
  }
});

【问题讨论】:

标签: php json jwt slim restful-authentication


【解决方案1】:

您只需将令牌发送到 JWT:decode。将您的代码更改为:

$jwt = str_replace('Bearer ', '', $jwt['HTTP_AUTHORIZATION'][0]);
$decoded = JWT::decode($jwt, $key, ['HS256']);

【讨论】:

    猜你喜欢
    • 2020-07-25
    • 2020-12-01
    • 2021-12-30
    • 2018-10-05
    • 2019-05-19
    • 2020-05-23
    • 2016-11-15
    • 2021-06-30
    相关资源
    最近更新 更多