| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120 | <?phpnamespace app\common\controller;use Firebase\JWT\JWT;use Firebase\JWT\Key;use app\BaseController;use app\common\util\Result;use EasyWeChatComposer\EasyWeChat;use app\common\exception\CatchException;class JwtBaseController extends BaseController{    protected $failException = true;    /**     * $key jwt HS256 key     *     * @var string     */    protected $key;    /**     * $table 当前使用的表     *     * @var mixed     */    protected $table;    /**     * $model 当前使用的模型     *     * @var \think\Model     */    protected $model;    /**     * $wechat 微信小程序api实例     *     * @var \EasyWeChat\MiniProgram\Application     */    private static $_wechat;    /**     * 设置jwt密钥     *     * @param mixed $key     *      * @return void     */    protected function setKey($key) {        $this->key = $key;    }    /**     * 验证token     *     * @return void     */    public function valid()    {        // 允许 Authorization 头部通过 cors        $jwt = $this->request->header('Authorization');        if (empty($jwt)) {            throw new CatchException("未授权用户", 600);        }        $jwt = str_replace('Bearer ', '', $jwt);        // try decode        $this->decodeJwt($jwt);        return Result::rest(true);    }    /**     * 默认参数     *     * @return mixed     */    protected function params($validator = null, $name = '')    {        $params = $this->request->param($name, null, 'trim');        // 尝试校验        if (!is_null($validator)) {            $this->validate($params, $validator);        }        return $params;    }    protected function only(array $names)    {        return $this->request->only($names);    }    /**     * encodeJwt     *     * @param array|\stdClass $payload     *     * @return string     */    protected function encodeJwt($payload)    {        return JWT::encode($payload, $this->key, 'HS256');    }    /**     * decodeJwt     *     * @param string $jwt     *     * @return \stdClass     */    protected function decodeJwt($jwt)    {        return JWT::decode($jwt, new Key($this->key, 'HS256'));    }}
 |