老莫的笔记本  
  
查看: 1208|回复: 0

TP5.0 中如何使用jwt

[复制链接]

662

主题

878

帖子

5145

积分

超级版主

Rank: 8Rank: 8

积分
5145
发表于 2018-12-24 11:02:37 | 显示全部楼层 |阅读模式
login.php    在这个操作时,签发jwt;并且携带基础信息
  1. <?php
  2. namespace app\index\controller;
  3. use think\Request;
  4. use think\Db;  
  5. use app\index\model\Admins;
  6. // 引入jwt
  7. use \Firebase\JWT\JWT;
  8. class Login
  9. {
  10.    
  11.     public function index()
  12.     {
  13.         return '<style type="text/css">*{ padding: 0; margin: 0; } .think_default_text{ padding: 4px 48px;} a{color:#2E5CD5;cursor: pointer;text-decoration: none} a:hover{text-decoration:underline; } body{ background: #fff; font-family: "Century Gothic","Microsoft yahei"; color: #333;font-size:18px} h1{ font-size: 100px; font-weight: normal; margin-bottom: 12px; } p{ line-height: 1.6em; font-size: 42px }</style><div style="padding: 24px 48px;"> <h1>:)</h1><p> ThinkPHP V5<br/><span style="font-size:30px">十年磨一剑 - 为API开发设计的高性能框架</span></p><span style="font-size:22px;">[ V5.0 版本由 <a href="http://www.qiniu.com" target="qiniu">七牛云</a> 独家赞助发布 ]</span></div><script type="text/javascript" src="https://tajs.qq.com/stats?sId=9347272" charset="UTF-8"></script><script type="text/javascript" src="https://e.topthink.com/Public/static/client.js"></script><think id="ad_bd568ce7058a1091"></think>    }
  14.     public function mv()
  15.     {
  16.         return '我进来了    }
  17.     // 执行登录
  18.     public function dologin(Request $request)
  19.     {
  20.         if (Request::instance()->isOptions()){
  21.             die;
  22.         }
  23.         // 非空验证
  24.         if(!$request->param('username')){
  25.             downjson($code=1,$msg='用户名不能为空');
  26.         }
  27.         if(!$request->param('password')){
  28.             downjson($code=1,$msg='密码不能为空');
  29.         }
  30.         if(!$request->param('vercode')){
  31.             downjson($code=1,$msg='验证码不能为空');
  32.         }
  33.         $ip = Request::instance()->ip();
  34.         // 只根据用户名拿数据
  35.         $where = function ($query) use($request){
  36.             $query->where([
  37.                     'username' =>['=',$request->param('username')],
  38.                 ]);
  39.         };
  40.         //在这有个坑点 返回值 只能是数组、字符串、不能反回一个对象
  41.         $lmb = Admins::get($where);
  42.         
  43.         //登录用户验证
  44.         if(!$lmb){
  45.             downjson(1,'登录失败,该用户不存在');
  46.         }
  47.         // 登录用户密码验证
  48.         if( MD5($request->param('password')) !== $lmb->getData()['password'] ){
  49.             downjson(1,'登录失败,密码错误');
  50.         }
  51.         // 判断该用户是否被禁用
  52.         if($lmb->getData()['status']!==1){
  53.             downjson(1,'该用户已被管理员禁用');
  54.         }
  55.         // 在这生成jwt并且返回给前端
  56.         $result=array(  
  57.             'code'=> 0
  58.             ,'msg'=> "登录成功"
  59.             ,'data'=> array(
  60.               "access_token" => $this->lssue($lmb['id'],$lmb['truename'],$ip)
  61.             )  
  62.         );  
  63.         exit( json_encode($result, JSON_UNESCAPED_UNICODE) );
  64.     }
  65.     // 用户信息 通过解析access_token 获得
  66.     public function userInfo(Request $request)
  67.     {
  68.         // 判断是不是option请求
  69.         if (Request::instance()->isOptions()){
  70.             die;
  71.         }
  72.         $key = 'laomo'; //key要和签发的时候一样
  73.         $info = Request::instance()->header(); //直接在这里放'access_token' 居然接收不到值
  74.         if(isset($info['access_token'])){
  75.             $jwt = $info['access_token'];
  76.         }else{
  77.             $jwt = input('access_token');
  78.         }
  79.         if(empty($jwt)){
  80.             downjson($code=161,$msg='请登录',$info['access_token']);
  81.         }
  82.         try {
  83.             JWT::$leeway = 60;//当前时间减去60,把时间留点余地
  84.             $decoded = JWT::decode($jwt, $key, ['HS256']); //HS256方式,这里要和签发的时候对应
  85.             $arr = (array)$decoded;
  86.             downjson($code=0,$msg='成功','',$data=$arr['data']);
  87.         } catch(\Firebase\JWT\SignatureInvalidException $e) {  //签名不正确
  88.             // return $e->getMessage();
  89.             downjson($code=161,$msg=$e->getMessage());
  90.         }catch(\Firebase\JWT\BeforeValidException $e) {  // 签名在某个时间点之后才能用
  91.             // return $e->getMessage();
  92.             downjson($code=161,$msg=$e->getMessage());
  93.         }catch(\Firebase\JWT\ExpiredException $e) {  // token过期
  94.             downjson($code=162,$msg=$e->getMessage());
  95.         }catch(Exception $e) {  //其他错误
  96.             downjson($code=162,$msg=$e->getMessage());
  97.         }
  98.     }
  99.    //签发Token
  100.         public function lssue($id,$username,$ip)
  101.         {
  102.                 $key = 'laomo'; //key
  103.                 $time = time(); //当前时间
  104.                        $token = [
  105.                 'iss' => '', //签发者 可选
  106.                    'aud' => $ip, //接收该JWT的一方,可选
  107.                    'iat' => $time, //签发时间
  108.                    'nbf' => $time , //(Not Before):某个时间点后才能访问,比如设置time+30,表示当前时间30秒后才能使用
  109.                    'exp' => $time+7200, //过期时间,这里设置2个小时
  110.                     'data' => [ //自定义信息,不要定义敏感信息
  111.                              'userid' => $id,
  112.                                'username' => $username
  113.             ]
  114.         ];
  115.         return JWT::encode($token, $key); //输出Token
  116.         }
  117.       
  118. }
复制代码

基类 Base.php  验证jwt 获取对应信息;
  1. <?php
  2. namespace app\index\controller;
  3. use think\Controller;
  4. use think\Request;
  5. use \Firebase\JWT\JWT; //导入JWT
  6. use think\auth\Auth;
  7. class Base extends Controller
  8. {
  9.     public $useinfo = array(); //存储用户信息
  10.     // 登录验证
  11.     public function _initialize()
  12.     {
  13.         // 判断是不是option请求
  14.         if (Request::instance()->isOptions()){
  15.             die;
  16.         }
  17.         $key = 'laomo'; //key要和签发的时候一样
  18.         $info = Request::instance()->header(); //直接在这里放'access_token' 居然接收不到值
  19.         if(isset($info['access_token'])){
  20.             $jwt = $info['access_token'];
  21.         }else{
  22.             $jwt = input('access_token');
  23.         }
  24.       
  25.         if(empty($jwt)){
  26.             downjson($code=161,$msg='请登录');
  27.         }
  28.         try {
  29.             JWT::$leeway = 60;//当前时间减去60,把时间留点余地
  30.             $decoded = JWT::decode($jwt, $key, ['HS256']); //HS256方式,这里要和签发的时候对应
  31.             $arr = (array)$decoded;
  32.             $this->useinfo = $arr['data']; //提出存储在jwt的用户信息
  33.         } catch(\Firebase\JWT\SignatureInvalidException $e) {  //签名不正确
  34.             downjson($code=161,$msg=$e->getMessage());
  35.         }catch(\Firebase\JWT\BeforeValidException $e) {  // 签名在某个时间点之后才能用
  36.             downjson($code=161,$msg=$e->getMessage());
  37.         }catch(\Firebase\JWT\ExpiredException $e) {  // token过期
  38.             downjson($code=162,'登陆超时');
  39.         }catch(Exception $e) {  //其他错误
  40.             downjson($code=162,$msg=$e->getMessage());
  41.         }
  42.     }
  43.    
  44. }
复制代码


回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

快速回复 返回顶部 返回列表