账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    Laravel中$response->headers->set为什么无效果?
    34
    0

    准备开发小程序,先测试后台API,项目使用Laravl+jwt+dingo来开发,JWT想要实现无痛刷新token,测试过程中在网上找到这样的一个中间件

        public function handle($request, Closure $next)
        {
            // 检查此次请求中是否带有 token,如果没有则抛出异常。 
            $this->checkForToken($request);
    
           // 使用 try 包裹,以捕捉 token 过期所抛出的 TokenExpiredException  异常
            try {
                // 检测用户的登录状态,如果正常则通过
                if ($this->auth->parseToken()->authenticate()) {
                    return $next($request);
                }
                throw new UnauthorizedHttpException('jwt-auth', '未登录');
            } catch (TokenExpiredException $exception) {
              // 此处捕获到了 token 过期所抛出的 TokenExpiredException 异常,我们在这里需要做的是刷新该用户的 token 并将它添加到响应头中
                try {
                    // 刷新用户的 token
                    $token = $this->auth->refresh();
                   // 使用一次性登录以保证此次请求的成功
                    Auth::guard('api')->onceUsingId($this->auth->manager()->getPayloadFactory()->buildClaimsCollection()->toPlainArray()['sub']);
                } catch (JWTException $exception) {
                   // 如果捕获到此异常,即代表 refresh 也过期了,用户无法刷新令牌,需要重新登录。
                    throw new UnauthorizedHttpException('jwt-auth', $exception->getMessage());
                }
            }
            
            // 在响应头中返回新的 token
            return $this->setAuthenticationHeader($next($request), $token);
        }

    在postman中测试接口,每次请求完后响应header都没办法添加authorization
    $this->setAuthenticationHeader这个源码是:

        protected function setAuthenticationHeader($response, $token = null)
        {
            $token = $token ?: $this->auth->refresh();
            $response->headers->set('Authorization', 'Bearer '.$token);
    
            return $response;
        }

    $response->headers->set('Authorization', 'Bearer '.$token);这里无法添加,这是为什么?
    最后改用这样才可以:

            return $next($request)->withHeaders([
                    'Authorization'=> 'Bearer '.$token,
                ]);

    按理说dingo自带的方法应该不会有问题的,是我哪里出错了吗?

    0
    打赏
    收藏
    点击回答
        全部回答
    • 0
    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部