微信小程序 --- JWT接口鉴权

1.通过 composer 下载插件

composer require firebase/php-jwt

2.

<?php
namespace app\business;
 
 
use Firebase\JWT\Key;
use think\Exception;
 
class Jwt
{
    public static function createJwt($userId = 'zq')
    {
        $key = md5('zq8876!@!'); //jwt的签发密钥,验证token的时候需要用到
        $time = time(); //签发时间
        $expire = $time + 14400; //过期时间
        $token = array(
            "user_id" => $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无效");
        }
    }
 
}

3.定义中间件

php think make:middleware Check
<?php
declare (strict_types = 1);
 
namespace app\middleware;
 
use app\business\Jwt;
use think\db\exception\DbEventException;
use think\Exception;
 
class CheckToken
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
//        取出token
        $token=$_SERVER["HTTP_TOKEN"];
//        验证token
        try {
            $user_id=Jwt::verifyJwt($token);
            $request->user_id=$user_id;
        }catch (Exception $exception){
            return fail("token异常");
        }
        return $next($request);
    }
}

4..登录成功颁发token

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

5.引用中间件

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

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

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

7.小程序其他需登录页面才可查看时 每次访问需携带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
            })
          }
        })
    },

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值