You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel Lighthouse GraphQL Passport认证异常:带Token仍无法验证用户

问题分析与解决方案

我之前在Laravel + Lighthouse + Passport的项目里也碰到过一模一样的情况——明明请求头带了有效Token,auth()->check()却始终返回false。结合你的代码细节,核心问题和修复方案如下:

1. 明确指定API Guard(最可能的原因)

默认情况下,auth()助手函数使用的是config/auth.php里配置的默认Guard(通常是web),而你的GraphQL请求走的是api路由组,对应的Guard应该是passport驱动的api Guard。

修改你的AuthRestaurantAdmin中间件代码,把所有auth()调用换成auth('api'):

<?php
namespace App\Http\Middleware;

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

class AuthRestaurantAdmin
{
    public function handle($request, Closure $next)
    {
        // 明确使用api guard进行认证
        $user = auth('api')->user();
        
        if ($user && $user->hasRole(User::ROLE_RESTAURANT_ADMIN)) {
            if ($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');
    }
}

同时确认config/auth.php里的api Guard配置正确:

'guards' => [
    'api' => [
        'driver' => 'passport',
        'provider' => 'users',
    ],
],

2. 检查请求头格式是否正确

Passport的认证中间件要求Authorization头的格式必须是 Bearer {你的Token},如果你的请求头只传了Token字符串(没有Bearer 前缀),Passport无法识别,导致认证失败。

你可以在中间件里临时打印请求头确认:

dd($request->header('Authorization')); // 应该输出 "Bearer xxxxxx..."

3. 确认Lighthouse与Passport的集成配置

检查config/lighthouse.php里的中间件配置,确保已经包含Passport的认证中间件:

'middleware' => [
    \Laravel\Passport\Http\Middleware\CheckClientCredentials::class,
    // 如果你需要刷新Token的话可以加上下面这个
    // \Laravel\Passport\Http\Middleware\CreateFreshApiToken::class,
],

另外,确保你的GraphQL路由定义在routes/api.php中(而不是web.php),这样会自动应用api路由组的中间件:

// routes/api.php
Route::graphql();

4. 清除配置缓存

有时候修改配置后缓存会导致新配置不生效,运行以下命令清除缓存:

php artisan config:clear
php artisan cache:clear

如果上述步骤都试过还是有问题,可以尝试重新生成Passport密钥:

php artisan passport:install --force

内容的提问来源于stack exchange,提问作者Wai Yan Hein

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 10:07:58