【发布时间】: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() . '}}';
}
}
});
【问题讨论】:
-
print_r($decoded);给了什么? -
另外,我假设您调用“POST”来生成 JWT 令牌,然后将其传递给“GET”,就像在 github.com/letsila/slim3-jwt-auth-example/blob/master/tests/… 的测试中一样。
-
您应该正确调试您的代码,因为给定的消息非常清楚您的问题
-
漂亮的
Caddy server内置了 jwt 令牌作为选项:caddyserver.com/docs/http.jwt 很容易设置
标签: php json jwt slim restful-authentication