首页 > 解决方案 > Laravel Lighthouse GraphQL:即使令牌存在请求标头,护照身份验证也不起作用

问题描述

我正在做一个 Laravel 项目。我正在使用 Lighthouse 库构建 GraphQL API。我正在将此库用于 Passport 身份验证,https://github.com/joselfonseca/lighthouse-graphql-passport-auth。我可以使用该库中的端点并生成身份验证访问令牌。我事先安装并配置了 Passport。问题是,当我使用端点/查询受保护的突变时,它不起作用。即使令牌存在于标头中,它也总是返回 false 以检查用户是否已登录。

我有以下架构声明。

extend type Mutation @middleware(checks: ["api", "auth.restaurant-admin"]) {
    updateUserProfile(input: UpdateUserProfileInput): User! @updateUserProfileValidation
}

如您所见,它实际上是受“api”和“auth.restaurant-admin”中间件保护的突变。

以下是我的 auth.restaurant-admin 中间件实现。

<?php

namespace App\Http\Middleware;

use App\Models\User;
use Closure;
use Illuminate\Http\Response;

class AuthRestaurantAdmin
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (auth()->check() and auth()->user()->hasRole(User::ROLE_RESTAURANT_ADMIN)) {

            if (auth()->user()->restaurant) {
                return $next($request);
            } else {
                return abort(Response::HTTP_FORBIDDEN, 'There is no restaurant assigned to the user');
            }
        }

        return abort(Response::HTTP_FORBIDDEN, 'You are not authorised to access this part of the application');
    }
}

auth()->check()即使标头中存在有效的访问令牌,该方法也始终返回 false。我在 GraphQL 操场上按如下方式传递令牌。

[![enter code here][1]][1]

当我像这样从标头中检索令牌时,$request->header('Authorization'),我可以看到预期值。但是 auth()->check() 只是不起作用。我的代码有什么问题和缺失?我该如何解决?

标签: laravelgraphqllaravel-passportlighthouselaravel-lighthouse

解决方案


推荐阅读