如何调用JWT有效负载数据

时间:2019-03-25 09:34:35

标签: php slim slim-3

在这里,我用我的帖子登录名让用户登录到系统,然后返回一个JWT,其中包含初始化时间,到期时间和ID。

$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);  
}

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

$payload = [
    "iat" => time(),
    "exp" => time() + 36000,
    "id" => $input['id']
];

$token = JWT::encode($payload, $settings['jwt']['secret'],"HS256");

$_SESSION['user_id'] = $input['id'];

return $this->response->withJson($input, 200)
                      ->withHeader('Content-type', 'application/json;charset=utf-8', 200)
                      ->withAddedHeader('Authorization', $token);

});

$app->put('/address/{id}', function ($request, $response, $args) {

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

if(!empty($_SESSION['user_id'])) {
    $input = $request->getParsedBody();
    $sql = "UPDATE address SET s_pNumber =:s_pNumber, s_address =:s_address, s_address2 =:s_address2 , s_pCode =:s_pCode, s_city =:s_city,
             s_state =:s_state, s_country =:s_country WHERE id =:id";

    $sth = $this->db->prepare($sql);
    $sth->bindParam("id", $args['id']);
    $sth->bindParam("s_pNumber", $input['s_pNumber']);
    $sth->bindParam("s_address", $input['s_address']);
    $sth->bindParam("s_address2", $input['s_address2']);
    $sth->bindParam("s_pCode", $input['s_pCode']);
    $sth->bindParam("s_city", $input['s_city']);
    $sth->bindParam("s_state", $input['s_state']);
    $sth->bindParam("s_country", $input['s_country']);
    $input['id'] = $args['id'];
    $sth->execute();
    session_destroy();

    return  $this->response->withJson($input, 200);
}

// if(empty($_SESSION['user_id'])) {
//     return $response->withJson(['error' => true, 'message' => 'Login please'], 403);
// }

});

我的问题是如何根据用户已经在其中登录的有效负载中的ID来编辑用户数据?我如何解码有效负载并使我的mysql看起来像“ WHERE(payload.id)”而不是“ WHERE id =:id'谢谢

0 个答案:

没有答案