thinkphp5 基于JWT访问令牌token 刷新令牌token验证

common.php

use Firebase\JWT\JWT;
/**
 * 应用公共(函数)文件
 */


// +---------------------------------------------------------------------+
// | 系统相关函数
// +---------------------------------------------------------------------+

/**
 * 生成会员token
 * @param unknown $userId
 * @param unknown $expire
 * @return string
 */
function create_jwt_by_userid($userId,$expire){
    //jwt的签发密钥,验证token的时候需要用到
    $key = md5('*********');
    $time = time(); //签发时间
    $expire = $time + $expire; //过期时间
    $token = array(
        "user_id" => $userId,
        "iss" => "https://199508.com",//签发组织
        "aud" => "https://199508.com", //签发作者
        "iat" => $time,
        "nbf" => $time,
        "exp" => $expire
    );
    $jwt = JWT::encode($token, $key);
    return $jwt;
}

/**************************************************************************************/

namespace app\tollcollector\controller;
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization");
header('Access-Control-Allow-Methods: GET,POST,PUT,DELETE,OPTIONS,PATCH');

use think\Controller;
use Firebase\JWT\JWT;

/**
 * 公共控制器
 * @author 
 *
 */
class Common extends Controller
{   
    protected $userId = '';
    protected $usertoken = [];
    public function _initialize(){
        if(!$this->request->param('access_token') && $this->request->param('refresh_token')){
            $this->returnJson('100101','会员信息错误','','');
        }
        
        $access_token = $this->request->param('access_token');
        $refresh_token = $this->request->param('refresh_token');
        $access_token = $this->verifyJwt($access_token);
        if($access_token['code'] == 10000){
            $this->userId = $access_token['result'];
        }elseif($access_token['code'] == 10001){
            $this->returnJson('100101','会员信息错误','','');
        }elseif($access_token['code'] == 10002){
            $this->returnJson('100102','令牌失效','','');
        }elseif($access_token['code'] == 10003){
            //令牌过期
            //验证刷新令牌
            $refresh_token = $this->verifyJwt($refresh_token);
            if($refresh_token['code'] == 10000){
                $this->userId = $refresh_token['result'];
                //重新生成令牌
                $this->usertoken['access_token'] = create_jwt_by_userid($refresh_token['result'],3600*24);
                $this->usertoken['refresh_token'] = create_jwt_by_userid($refresh_token['result'],3600*24*7);
            }elseif($access_token['code'] == 10001){
                $this->returnJson('100101','会员信息错误','','');
            }elseif($access_token['code'] == 10002){
                $this->returnJson('100102','令牌失效','','');
            }elseif($access_token['code'] == 10003){
                $this->returnJson('100103','令牌过期','','');
            }
        }
    }
    
    /**
     * @author 
     * 校验会员token
     */
    protected function verifyJwt($jwt)
    {
        //jwt的签发密钥,验证token的时候需要用到
        $key = md5('*********');
        try {
            $jwtAuth = json_encode(JWT::decode($jwt, $key, array('HS256')));
            $authInfo = json_decode($jwtAuth, true);
            if (!empty($authInfo['user_id'])) {
                return array(
                    'code' => '10000',
                    'msg' => '令牌验证通过',
                    'result'=>$authInfo['user_id']
                );
            } else {
                return array(
                    'code' => '10001',
                    'msg' => '会员信息错误',
                    'result'=>''
                );
            }
        } catch (\Firebase\JWT\SignatureInvalidException $e) {
            return array(
                'code' => '10002',
                'msg' => '令牌失效',
                'result'=>''
            );
        } catch (\Firebase\JWT\ExpiredException $e) {
            return array(
                'code' => '10003',
                'msg' => '令牌过期',
                'result'=>''
            );
        } catch (\Exception $e) {
            return array(
                'code' => '10002',
                'msg' => '令牌验证失败',
                'result'=>''
            );
        }
    }
    
    protected function returnJson($code='100000',$msg='请求成功',$result='',$usertoken=''){
        exit(json_encode([
            'code' => $code,
            'msg' => $msg,
            'result'=>$result,
            'usertoken' =>$usertoken
        ]));
    }
}

/***************************************************************************/

namespace app\tollcollector\controller;
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization");
header('Access-Control-Allow-Methods: GET,POST,PUT,DELETE,OPTIONS,PATCH');

use think\Controller;

/**
 * 登录控制器
 * @author 
 *
 */
class Login extends Controller
{
    /**
     * 登录接口
     * username 账号 
     * password 密码 
     */
    public function login()
    {
        if ($this->request->isPost()) {
            $data = $this->request->param();
            if (empty($data['username']) || empty($data['password'])) {
                $this->returnJson('100001','账号或密码不能为空','','');
            }
            $snb_year = date('Y');
            $userInfo = db('***************')
            ->where('account', $data['username'])
            ->find();
            if (! $userInfo) {
                $this->returnJson('100002','账号输入错误','','');
            }
            if ($userInfo['password'] != md5($data['password'])) {
                $this->returnJson('100003','密码输入错误','','');
            }
            //access_token:请求接口的token
            //refresh_token:刷新access_token
            $usertoken['access_token'] = create_jwt_by_userid($userInfo['snb_id'],3600*24);
            $usertoken['refresh_token'] = create_jwt_by_userid($userInfo['snb_id'],3600*24*7);
            $this->returnJson('100000','登录成功','',$usertoken);
        } else {
            $this->returnJson('100005','登录失败','','');
        }       
    }
    
    protected function returnJson($code='100000',$msg='请求成功',$result='',$usertoken=''){
        exit(json_encode([
            'code' => $code,
            'msg' => $msg,
            'result'=>$result,
            'usertoken' =>$usertoken
        ]));
    }
}

/*********************************************************************/

namespace app\tollcollector\controller;

/**
 * 首页控制器
 * @author 
 *
 */
class Index extends Common
{
    /**
     * 信息接口
     */
    public function index(){
        $userInfo = db('**************')->where('id', $this->userId)->find();
        unset($userInfo['snb_password']);
        $this->returnJson('100000','请求成功',$userInfo,$this->usertoken);
    }
 
    
    
}

你可能感兴趣的:(php)