lumen request 获取 header 头参数 token
$token = $request->bearerToken();
以下是校验 token 合法性的一个方法,可以用在中间件中使用:
/**
* 验证 token 合法性
* @param Request $request
* @param $err
* @return bool
* @throws \Exception
*/
public static function checkToken(Request $request, &$err)
{
$token = $request->bearerToken();
if (!$token) {
$err = 'token not found';
return false;
}
$user = [];
//检查redis里边是否存在用户token
if (Redis::exists(Constant::REDIS_TOKEN_PREFIX . $token)) {
$userJson = Redis::get(Constant::REDIS_TOKEN_PREFIX . $token);
if (!$userJson) {
$err = 'data error';
return false;
}
$user = JsonHelper::decode($userJson);
} else {
//不存在,就请求GRpc获取
$client = new GRpcClient();
$params['session_id'] = $token;
$ret = $client->setCmd(GRpcCmd::CHECK_LOGIN)->send($params);
if (!is_array($ret)) {
$err = 'token error:' . $client->getMsg();
return false;
}
//获取到之后就存到redis
$user['id'] = $ret['user_id'];//用户ID
$user['phone'] = $ret['phone'];//手机号
$user['channel'] = $ret['register_channel'];//注册渠道
$user['gold'] = $ret['gold'];//金币
Redis::setex(Constant::REDIS_TOKEN_PREFIX . $token, 7200, JsonHelper::encode($user));
}
return true;
}