1.引入php-jwt包
composer require firebase/php-jwt
控制器文件:app\api\lib
<?php
namespace app\api\lib;
use Firebase\JWT\ExpiredException;
use Firebase\JWT\JWT as JWTUtil;
use think\Exception;
use think\response\Json;
class JWT
{
//生产token
public static function createjwt($userid = null): Json
{
$key = md5(env('TOKEN.KEY', "pyg")); //jwt的签发密钥,验证token的时候需要用到
$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));
}
// 验证token
public static function verifyjwt($jwt)
{
if (in_array($jwt, cache("delete_token"))) {
throw new Exception("token过期", 400);
}
$key = md5(env('TOKEN.KEY', "pyg")); //jwt的签发密钥,验证token的时候需要用到
try {
$jwtAuth = json_encode(JWTUtil::decode($jwt, $key, array("HS256")));
$authInfo = json_decode($jwtAuth, true);
if (!$authInfo['user_id']) {
throw new Exception("用户不存在", 400);
}
return json($authInfo);
} catch (ExpiredException $e) {
throw new Exception("token过期", 400);
} catch (\Exception $e) {
throw new Exception($e->getMessage(), $e->getCode());
}
}
//从请求信息中获取token令牌
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));
}
}
3.在env 目录里加入如下代码:
[TOKEN]
KEY= pyg
iss = http://admin.tp.com
aud= pyg
4.生成token值
public static function setToken($userid){
try {
$token = JWT::createjwt($userid)->getData();
}catch (Exception $exception){
throw new Exception("token生成失效",500);
}
return $token;
}
5.效果如图所示
图1.生成token