Slim 3:如何从请求标头访问用户信息

时间:2018-09-01 19:27:43

标签: slim

我正在使用Slim 3.1,并且能够正确进行身份验证,即能够生成令牌并将其用于其他POST请求。现在,我想解析请求标头以提取用户信息,以便可以识别出哪个用户发送了请求。 这是我获取令牌的代码。

$app->post('/login/token', function (Request $request, Response $response, 
array $args) {

$input = $request->getParsedBody();
$now = new DateTime();
$future = new DateTime("+10 minutes");
$server = $request->getServerParams();
$jti = (new Base62)->encode(random_bytes(16));
$payload = [
    "iat" => $now->getTimeStamp(),
    "exp" => $future->getTimeStamp(),
    "jti" => $jti,
    "sub" => $input['username']
];

$sql = "SELECT * FROM user WHERE User_Name= :username";

$sth = $this->db->prepare($sql);
$sth->bindParam("username", $input['username']);

$sth->execute();
$user = $sth->fetchObject();

// verify email address.
if(!$user) {
    return $this->response->withJson(['error' => true, 'message' => 'These credentials do not match our records.']);  
}

// verify password.
if (!password_verify($input['password'],$user->User_Password)) {
    return $this->response->withJson(['error' => true, 'message' => 'These credentials do not match our records.']);  
}

$settings = $this->get('settings'); // get settings array.

//$token = JWT::encode(['User_ID' => $user->User_ID, 'username' => $user->User_Name], $settings['jwt']['secret'], "HS256");
$token = JWT::encode($payload, $settings['jwt']['secret'], "HS256");
return $this->response->withJson(['token' => $token, 'ACL' => $user->User_ACL]);

});

这将返回我在以下POST请求中发送的令牌

$app->group('/api', function(\Slim\App $app) {
$app->post('/createuser', function (Request $request, Response $response, 
array $args) {

$headerValueArray = $request->getHeader('HTTP_AUTHORIZATION');

return $this->response->withJson(['success' => true,  $token]);
});

});

上面的POST请求给出以下输出

{     “成功”:是的,     “0”:[ “承载eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE1MzU4Mjk0OTUsImV4cCI6MTUzNTgzNjY5NSwianRpIjoiMWc5ZFM3dUNLbzl1blRQZzBmYjU2diIsInN1YiI6InN5c2FkbWluIn0.vo3FBPhBkhfA2y7AG-afmjfeEhygIYY7lIaaVNX5i5k”]     }

我需要解析此令牌以提取用户信息,以查看其是否是执行此操作的有效用户。换句话说,如何解码上述令牌。
任何帮助将不胜感激!

0 个答案:

没有答案