我有一个生成JWT的函数:
function getToken($user, $expTime){
$jwt = \Firebase\JWT\JWT::encode([
'iss' => request()->getBaseUrl(),
'sub' => "{$user['id']}",
'exp' => $expTime,
'iat' => time(),
'nbf' => time(),
'is_admin' => $user['role_id'] == 1
], getenv("SECRET_KEY"), 'HS256');
return $jwt;
}
此函数返回以下令牌:
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJcL2FwaSIsInN1YiI6InVzNWIzY2M4YmRlMDc4MSIsImV4cCI6NTUxMDY1ODkyNDAwMCwiaWF0IjoxNTMwNzM4NTkwLCJuYmYiOjE1MzA3Mzg1OTAsImlzX2FkbWluIjpmYWxzZX0.3bMaxCaMprURZEDurnckZWSoDRp7ePMxZXDW0B6q6fk
当我使用此令牌发出请求时,我得到了:
{
"status": "error",
"message": "Signature verification failed"
}
要使其正常工作,我转到https://jwt.io/,添加密钥并通过传递密码进行验证。
然后我得到此令牌:
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiIvYXBpIiwic3ViIjoidXM1YjNjYzhiZGUwNzgxIiwiZXhwIjo1NTEwNjU4OTI0MDAwLCJpYXQiOjE1MzA3Mzg1OTAsIm5iZiI6MTUzMDczODU5MCwiaXNfYWRtaW4iOmZhbHNlfQ.heF_L9LrFp7Hht2dbVtOMx_gdUtmPKzrMgxW1_jdWLo
这很好用。但是如何使用php代码进行验证,以便我可以将其发送给用户?
响应代码:
function loginUser($email, $password) {
try {
// Connecting to databas
$db = new db();
$db = $db->connect();
$user = findUserByEmail($email, $db);
if(empty($user)){
echo 'User not found';
exit;
}
if(!password_verify($password, $user['password'])) {
echo 'Password does not match';
exit;
}
$expTime = time() * 3600;
$jwt = getToken($user, $expTime);
// Close databse
$db = null;
} catch(PDOException $e){
echo $e->getMessage();
}
return $jwt;
}
答案 0 :(得分:0)
好吧,最后我通过稍微更改生成令牌的函数来使其工作:
function getToken($user, $expTime){
$key = "secretkey";
$token = array(
'iss' => request()->getBaseUrl(),
'sub' => "{$user['id']}",
'exp' => $expTime,
'iat' => time(),
'nbf' => time(),
'is_admin' => $user['role_id'] == 1
);
return JWT::encode($token, $key);
}
答案 1 :(得分:0)
如果您是由于Google搜索“签名验证失败”而登陆此页面,则需要考虑的一件事。我收到此错误的原因是,在“授权人”标题中的“承载者”和我的令牌之间有两个空格。
错误:
Authorization:Bearer eyJraWQiOiJDT2N...
正确:
Authorization:Bearer eyJraWQiOiJDT2N...