微信小程序 JWT登录颁发token

1.引入扩展包

composer require firebase/php-jwt

 $userId,
            "iss" => "http://www.najingquan.com/",//签发组织
            "aud" => "zhangqi", //签发作者
            "iat" => $time,
            "nbf" => $time,
            "exp" => $expire
        );
//        生成token
        $jwt = \Firebase\JWT\JWT::encode($token, $key,'HS256');
        return $jwt;
    }

    public static function verifyJwt($jwt = '')
    {
        $key = md5('zq8876!@!');
        try {
            $jwtAuth = json_encode(\Firebase\JWT\JWT::decode($jwt, new Key($key,'HS256')));
            $authInfo = json_decode($jwtAuth, true);

            $msg = [];
            if (!empty($authInfo['user_id'])) {
                $msg = [
                    'status' => 1001,
                    'msg' => 'Token验证通过'
                ];
                return $authInfo['user_id'];
            } else {
                throw new Exception("用户不存在");
            }
        }  catch (\Firebase\JWT\ExpiredException $e) {
            throw new Exception("token过期");

        } catch (\Exception $e) {
            throw new Exception("token无效");
        }
    }

}

2.定义中间件

php think make:middleware Check
user_id=$user_id;
        }catch (Exception $exception){
            return fail("token异常");
        }
        return $next($request);
    }
}

3.登录成功颁发token

$token=Jwt::createJwt($id);

4.引用中间件

Route::get('list','Hotels/list')->middleware(\app\middleware\CheckToken::class);

5.小程序登录前端获取token并缓存

success({data:{data}}){
   console.log(data)
   wx.setStorage({
      key:"token",
      data:data
     })

5.小程序其他需登录页面才可查看时 每次访问需携带token

 onLoad: function (options) {
        let that = this
        let token = wx.getStorageSync('token');
        wx.request({
          url: 'http://www.www.com/index.php/list',
          data:{
              pagesize:10
          },
          header:{
            token:token
          },
          success(e){
            that.setData({
                data:e.data.data.data,
                last_page:e.data.data.last_page
            })
          }
        })
    },

你可能感兴趣的:(微信小程序,小程序)