我是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() . '}}';
}
}
});
答案 0 :(得分:0)
您只需要将令牌发送到JWT:decode。将您的代码更改为:
$jwt = str_replace('Bearer ', '', $jwt['HTTP_AUTHORIZATION'][0]);
$decoded = JWT::decode($jwt, $key, ['HS256']);