ThinkPHP6.0实例

通过composer安装

composer require lcobucci/jwt

在app/common/下创建一个trait目录

并且在trait目录下创建JWT.php文件

PHP中Traits的用法及示例

如:app/common/trait/JWT.php

JWT.php代码

<?php

namespace app\common\traits;


use Lcobucci\JWT\Builder;
use Lcobucci\JWT\Parser;
use Lcobucci\JWT\Signer\Hmac\Sha256;

trait JWT
{

    public static $signKey = 'www.liqingbo.cn'; //签名KEY

    /**
     * 生成json web token 字符串
     * @param int $userId 用户id
     * @return string $token
     */
    protected function generateJWT($userId)
    {
        $signer = new Sha256();

        return (string)(new Builder())->setIssuer('liqingbo')
            ->setIssuedAt(time())
            ->set('user_id', $userId)
            ->sign($signer, self::$signKey)
            ->getToken();
    }

    /**
     * 验证token是否有效
     * @param string $token token字符串aaa.bbb.ccc
     * @return bool
     */
    protected function verifyJWT($token)
    {
        $tokenObj = $this->parseJWT($token);
        $signer = new Sha256();
        return $tokenObj->verify($signer, self::$signKey);
    }

    /**
     * 将jwt字符串解析成Token对象
     * @param $token
     * @return \Lcobucci\JWT\Token
     */
    protected function parseJWT($token)
    {
        return (new Parser())->parse((string) $token); // Parses from a string
    }

    /**
     * 从jwt字符串中获取用户ID
     * @param string $token
     * @return mixed
     */
    protected function getUserIdFromJWT($token)
    {
        $tokenObj = $this->parseJWT($token);
        return $tokenObj->getClaim('user_id');
    }
}
通过上面两步:
  • 安装JWT
  • 通过traits公共调用代码

就可以开始调用了,这里建议放在中间件或者公共控制器里面

<?php

declare (strict_types = 1);

namespace app\api\controller;
use app\BaseController;

use app\common\traits\JWT; //通过命名空间引入
use think\facade\Request;

class CommonController extends BaseController
{
    use JWT; //还有这里,别忘记了

    public function checkAuth()
    {
        $header = Request::header();
        $token = $header['token']; //获取通过header传过来的token

        // 1.先从header取出token字符串
        if (!empty($token)) {
            $tokenString = (string)$token;
            if (empty($tokenString)) {
                exception("token值为空", 100001);
            }

            // 2.验证token是否合法
            if ($this->verifyJWT($tokenString)) {
                // 3.将token字符串转换成Token对象然后取出user_id
                $data = $this->getUserIdFromJWT($tokenString);

                // 单点登录
                // 4.在redis里查找token查找数据,如果查不到则返回token不存在
                //$token = Cache::store('redis')->get('user_id:' . $userId);

            } else {
                exception('非法token', 100001);
            }
        } else {
            exception('请求头缺少token参数', 100001);
        }

    }

}
Copyright © 李清波 2019 all right reserved,powered by Gitbook本书发布时间: 2020-04-24 16:20:58

results matching ""

    No results matching ""