西安网站制作公司排,廉江网站建设,北京网站设计公司yy成都柚米科技15,网站建设的目标定义学习php中使用composer下载安装firebase/php-jwt 以及调用方法 1、安装firebase/php-jwt2、封装jwt类 1、安装firebase/php-jwt
composer require firebase/php-jwt安装好以后出现以下文件: 2、封装jwt类
根据所使用的php框架#xff0c;在指定目录创建 Token.php
?ph… 学习php中使用composer下载安装firebase/php-jwt 以及调用方法 1、安装firebase/php-jwt2、封装jwt类 1、安装firebase/php-jwt
composer require firebase/php-jwt安装好以后出现以下文件: 2、封装jwt类
根据所使用的php框架在指定目录创建 Token.php
?php
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
class Token
{const SECRET hello;//密钥//创建tokenstatic public function create_token($uid 1){$payload [iss pyg, //签发人(官方字段:非必需)exp time() 3600, //过期时间(官方字段:非必需)aud admin, //接收人(官方字段:非必需)nbf time(), //生效时间(官方字段:非必需)iat time(), //签发时间(官方字段:非必需)admin_id $uid, //自定义字段(用户id)];$token JWT::encode($payload, self::SECRET, HS256);return $token;}//验证tokenstatic public function verify_token($token){try {// $decoded JWT::decode($jwt, new Key($key, HS256));$Result JWT::decode($token, new Key(self::SECRET, HS256));return true;} catch(\Firebase\JWT\SignatureInvalidException $e) { //签名不正确echo $e-getMessage();}catch(\Firebase\JWT\BeforeValidException $e) { // 签名在某个时间点之后才能用echo $e-getMessage();}catch(\Firebase\JWT\ExpiredException $e) { // token过期echo $e-getMessage();}catch(Exception $e) { //其他错误echo $e-getMessage();}}
}封装好以后 下面是登录控制器
public function loginCheck(){$req request()-param();// halt($req);// 接收工号和密码$uname trim(input(uname));$password trim(input(password));// halt($password);// 工号和密码不能为空if (empty($uname) || empty($password)) {// return 账号或密码不能为空;return json_encode([error 账号或密码不能为空]);}// halt($uname);// 进行账号验证$data Up::get([uname$uname]);// halt($data);if (!$data) {return json_encode([error 工号不存在请验证后输入]);}// halt($password);// 进行密码验证if ($password ! $data[password]) {// return ;return json_encode([error 工号和密码不匹配]);}// 如果工号和密码匹配则登录成功这才是重要的 上面代码是验证输入是否有误 并不重要 生成token$token Token::create_token($data[admin_id]);// dump($token);// return $token;return json_encode([token $token]);// session(Uname,$uname);// $this-success(登录成功,index/index);}最后进入其他页面验证token是否正确 我放到了Base控制器 每个页面都验证
?php
namespace app\index\controller;
use think\Controller;
use Token;class Base extends Controller
{public function _initialize(){$this-verifyToken();}public function verifyToken(){// $token input(token);$token eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJweWciLCJleHAiOjE2NzUxNDk3NzgsImF1ZCI6ImFkbWluIiwibmJmIjoxNjc1MTQ2MTc4LCJpYXQiOjE2NzUxNDYxNzgsImFkbWluX2lkIjoxfQ.bGz-MZwPDkixQQGnQ9iFpX-mZiOohJehuf114rc9zQA;$res Token::verify_token($token);halt($res);//这里可以来判断 是否跳到登录页面}
}token我直接写上去了 ,只为演示用,项目里是从客户端获取的来比对