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

Laravel 9 Passport API中间件中auth()->user()返回null问题

Laravel 9 Passport自定义管理员中间件auth()->user()返回null的解决方法

常见原因及修复方案

1. 路由未配置auth:api中间件

Passport的token认证依赖auth:api中间件处理请求中的身份凭证,若仅给路由添加admin中间件,跳过认证流程,auth()->user()必然返回null。

修复方式:
给需要管理员权限的路由同时添加auth:api和admin中间件,且auth:api必须放在前面:

Route::get('/admin/dashboard', [AdminController::class, 'dashboard'])
    ->middleware(['auth:api', 'admin']);

2. 中间件未指定API Guard

Laravel默认认证守卫是web,而Passport使用的是api守卫,直接调用Auth::user()会读取web守卫的用户(不存在),导致返回null。

修复方式:
在中间件中明确指定使用api守卫:

use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Response;

public function handle(Request $request, Closure $next)
{
    $user = Auth::guard('api')->user();
    
    if ($user && $user->is_admin == 1) {
        return $next($request);
    }
    
    return response()->json(['message' => 'Not Allowed'], Response::HTTP_FORBIDDEN);
}

3. 中间件执行顺序问题

若路由中admin中间件在auth:api之前执行,会导致认证未完成就触发管理员检查。只需确保路由中auth:api先于admin中间件即可,无需修改Kernel的全局优先级(除非有特殊全局需求)。

内容的提问来源于stack exchange,提问作者Thamer Alluqmani

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 19:36:20