简体   繁体   English

PHP Slim解码JWT令牌

[英]PHP Slim decoding JWT token

I am new to PHP and developing restful services using jwt authorization token. 我是PHP的新手,正在使用jwt授权令牌开发宁静的服务。 I have followed this GitHub example and have understood code to some extent but I am stuck on error on this line $stmt->bindParam("user_id", $decoded->context->user->user_id); 我已经遵循了这个GitHub示例,并且在一定程度上理解了代码,但是我在此行上$stmt->bindParam("user_id", $decoded->context->user->user_id);了错误: $stmt->bindParam("user_id", $decoded->context->user->user_id); saying

Notice: Array to string conversion in C:\\xampp\\htdocs\\slim2\\src\\routes.php on line. 注意:在线将C:\\ xampp \\ htdocs \\ slim2 \\ src \\ routes.php中的数组转换为字符串。

please help me solving this problem, I cant understand what is context->user->user_id where these are coming from. 请帮助我解决这个问题,我无法理解它们的来源是context-> user-> user_id。 The full code is given below 完整的代码如下

// 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() . '}}';
    }
  }
});

You only have to send the token to JWT:decode. 您只需将令牌发送到JWT:decode。 Change your code to: 将您的代码更改为:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM