三种方法实现jwt
方法一:
1.引入php-jwt包
composer require firebase/php-jwt
2.env
[TOKEN] KEY = yyp iss = http://admin.week3.com/ aud = zwx
3.htaccess
RewriteCond %{HTTP:Authorization} ^(.+)$ RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
4.代码
控制器文件:app\api\controller\Jwt.php
<?phpnamespace app\api\lib;
use app\BaseController;
use Firebase\JWT\ExpiredException;
use Firebase\JWT\JWT as JWTUtil;
use think\facade\Request;class Jwt
{/*** 根据json web token设置的规则生成token* @return \think\response\Json*/public function createjwt($userid=null){//jwt的签发密钥,验证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 $jwt = JWTUtil::encode($token,$key);}/*** 验证token* @return \think\response\Json*/public function verifyjwt($jwt){//jwt的签发密钥,验证token的时候需要用到$key = md5(env('TOKEN.KEY','pyg'));try{$jwtAuth = json_encode(JWTUtil::decode($jwt,$key,array("HS256")));$authInfo = json_decode($jwtAuth,true);if (!$authInfo['user_id']){return json(['code'=>400,'msg'=>'用户不存在','data'=>'']);}//验证成功返回return json($authInfo);}catch (ExpiredException $e){return json(['code'=>500,'msg'=>'token已经过期','data'=>'']);}catch (\Exception $e){return json(['code'=>$e->getCode(),'msg'=>$e->getMessage(),'data'=>[]]);}}//从请求信息中获取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));}}
路由:app\api\route\api.php
<?php
use think\facade\Route;
Route::rule("jwt","jwt/createjwt","get");
Route::rule("verifyjwt","jwt/verifyjwt","post");
1
2
3
4
方法二:
# 安装
composer require lcobucci/jwt 3.3
/*** Created by PhpStorm.* Author: Shadow* Date: 2021/12/19* Time: 5:35 下午* description: Token.php*/namespace app\adminapi\extend\tools\jwt;use Lcobucci\JWT\Signer\Hmac\Sha256;
use Lcobucci\JWT\Builder;
use Lcobucci\JWT\Parser;
use Lcobucci\JWT\ValidationData;class Token
{private static $_config = ['audience' => 'http://www.pyg.com',//接收人'id' => '3f2g57a92aa',//token的唯一标识,这里只是一个简单示例'sign' => 'pinyougou',//签名密钥'issuer' => 'http://adminapi.pyg.com',//签发人'expire' => 3600*24 //有效期];//生成tokenpublic static function getToken($user_id){//签名对象$signer = new Sha256();//获取当前时间戳$time = time();//设置签发人、接收人、唯一标识、签发时间、立即生效、过期时间、用户id、签名$token = (new Builder())->issuedBy(self::$_config['issuer'])->canOnlyBeUsedBy(self::$_config['audience'])->identifiedBy(self::$_config['id'], true)->issuedAt($time)->canOnlyBeUsedAfter($time-1)->expiresAt($time + self::$_config['expire'])->with('user_id', $user_id)->sign($signer, self::$_config['sign'])->getToken();return (string)$token;}//从请求信息中获取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));}//从token中获取用户id (包含token的校验)public static function getUserId($token = null){$user_id = null;$token = empty($token)?self::getRequestToken():$token;if (!empty($token)) {//为了注销token 加以下if判断代码$delete_token = cache('delete_token') ?: [];if(in_array($token, $delete_token)){//token已被删除(注销)return $user_id;}$token = (new Parser())->parse((string) $token);//验证token$data = new ValidationData();$data->setIssuer(self::$_config['issuer']);//验证的签发人$data->setAudience(self::$_config['audience']);//验证的接收人$data->setId(self::$_config['id']);//验证token标识if (!$token->validate($data)) {//token验证失败return $user_id;}//验证签名$signer = new Sha256();if (!$token->verify($signer, self::$_config['sign'])) {//签名验证失败return $user_id;}//从token中获取用户id$user_id = $token->getClaim('user_id');}return $user_id;}
}
方法三:
JWT-AUTH · tp6-jwtauth · 看云 (kancloud.cn)