【发布时间】:2019-08-16 13:27:15
【问题描述】:
这里我有一些用于登录的纤细 PHP 代码和一个检查它是否解码存储在标头中的 JWT 的函数。
$app->post('/login', function ($request, $response) {
$input = $request->getParsedBody();
$settings = $this->get('settings'); // get settings array.
$sql = "SELECT id, password FROM users WHERE id= :id";
$sth = $this->db->prepare($sql);
$sth->bindParam("id", $input['id']);
$sth->execute();
$user = $sth->fetchObject();
// verify user id
if(!$user) {
return $this->response->withJson(['error' => true, 'message' => 'NO ID '], 404)->withHeader('Content-type', 'application/json;charset=utf-8', 404);
}
// Compare the input password and the password from database for a validation
if (strcmp($input['password'],$user->password)) {
return $this->response->withJson(['error' => true, 'message' => 'These credentials do not match our records.'], 404)->withHeader('Content-type', 'application/json;charset=utf-8', 404);
}
$payload = array(
"iat" => time(),
"exp" => time() + 36000,
// "id" => $input['id']
"context" => [
"user" => [
"id" => $input['id']
]
]
);
try {
$token = JWT::encode($payload, $settings['jwt']['secret'],"HS256"); // $token store the token of the user
} catch (Exception $e) {
echo json_encode($e);
}
return $this->response->withJson($payload,200)
->withHeader('Content-type', 'application/json;charset=utf-8', 200)
->withAddedHeader('Authorization', $token);
});
$app->get('/get', function ($request, $response) {
$jwt = $request->getHeader("Authorization");
$settings = $this->get('settings');
$token = JWT::decode($jwt, $settings['jwt']['secret'], "HS256"); // $token store the token of the user
if ($token) {
return $this->response->withJson($token, 200)
->withHeader('Content-type', 'application/json;charset=utf-8', 200);
}
return $this->response->withJson($token,401)
->withHeader('Content-type', 'application/json;charset=utf-8', 401);
});
但是当我尝试运行http://localhost:8080/get 时,它会返回一个错误
传递给 Firebase\JWT\JWT::decode() 的参数 3 必须是数组类型。
为什么会发生,我该如何解决?
【问题讨论】:
-
警告!
strcmp($input['password'],$user->password)表明您没有正确散列密码。在处理密码时,您应该始终使用password_hash 和password_verify()。 从不将它们存储为纯文本或使用任何自建的散列算法。 -
是的,我知道,我不是为了生产。稍后将实施安全性。谢谢
-
print_r($settings);显示什么?尝试调试它 -
包含密钥的是我的 jwt 设置,请参阅我的新评论