public static function createjwt($userid=null)
{
//t的签发密钥,验证token的时候需要用到
$key = md5(env('TOKEN.key',"pyg"));
//签发时间
$time = time();
//过期时间
$expire = $time + 14400;
$token = array(
"user_id" => $userid,
//签发组织
"iss" => env('TOKEN.iss',""),
//签发作者
"aud" => env('TOKEN.aud',""),
"iat" => $time,
"nbf" => $time,
"exp" => $expire
);
return json(JWTUtil::encode($token,$key));
}
public static function verifyjwt($jwt)
{
//查看token是否过期
if(!in_array($jwt,cache("delete_token"))){
throw new Exception('token过期',400);
}
//t的签发密钥,验证token的时候需要用到
$key = md5('pyg');
try{
$jwtAuth = json_encode(JWTUtil::decode($jwt,$key,array("HS256")));
$authInfo = json_decode($jwtAuth,true);
if (!$authInfo['user_id']){
//return json_encode(['code'=>400,'msg'=>'用户不存在','data'=>[]]);
throw new Exception('用户不存在',400);
}
//验签返回
return json($authInfo);
}catch (ExpiredException $e){
//return json(['code'=>501,'msg'=>'token已过期','data'=>[]]);
throw new Exception('token已过期',400);
}catch (\Exception $e){
//return json(['code'=>$e.getCode(),'msg'=>$e.getMessage(),'data'=>[]]);
throw new Exception($e->getMessage(),$e->getCode());
}
}
/**
* 从请求信息中获取token令牌
* @return false|string
*/
public static function getRequestToken()
{
if (empty($_SERVER['HTTP_AUTHORIZATION'])) {
return false;
}
$header = $_SERVER['HTTP_AUTHORIZATION'];
$method = 'bearer';
//去除token中可能存在的bearer标识
return trim(str_ireplace($method, '', $header));
}
//登录接口
public function login(Request $request)
{
//接收数据
$postDate = $request->all();
//调用表单验证的逻辑
try {
validate(User::class)->check($postDate);
} catch (ValidateException $e) {
// 验证失败 输出错误信息
return fail($e->getMessage());
}
//调用登录验证的逻辑/调用生成token的逻辑
try {
$loginDate= LoginBusiness::checklogin($postDate);
$token=LoginBusiness::setToken($loginDate['id']);
}catch (Exception $exception){
return fail($exception->getMessage());
}
//组装数据
$backDate = [
'token' => $token,
'user_id' => $loginDate['id'],
'username' => $loginDate['username'],
'nickname' => $loginDate['nickname'],
'email' => $loginDate['email']
];
return success($backDate, '200', 'success');
}
中间件
public function handle($request, \Closure $next)
{
//后置中间件
$response=$next($request);
//取出当前访问的路由
if(!in_array($request->pathinfo(),$this->url)){
//取出token
$token=\app\api\lib\JWT::getRequestToken();
try {
//校验token
$data=\app\api\lib\JWT::verifyjwt($token);
}catch (Exception $exception){
return fail($exception->getMessage());
}
}
return $response;
}
|