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

Vue前端通过Axios调用Laravel API获取登录用户失败求助

解决Laravel API中Auth::check()始终返回false的问题

1. 修正API路由的认证中间件组

Laravel的api.php路由默认使用api中间件组,该组默认采用token类认证机制,而web路由依赖的session认证逻辑并未包含在内。根据你的前后端分离场景,分两种情况处理:

同域场景复用Session认证

修改app/Http/Kernel.php中的api中间件组,添加会话相关中间件:

protected $middlewareGroups = [
    'api' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\Session\Middleware\AuthenticateSession::class,
        'throttle:api',
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
    ],
];

同时前端Axios需开启携带凭证:

axios.defaults.withCredentials = true;

后端config/cors.php中设置supports_credentials为true。

跨域场景使用Sanctum SPA认证(推荐)

  1. 安装Sanctum:composer require laravel/sanctum
  2. 发布迁移文件:php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
  3. 执行迁移:php artisan migrate
  4. 修改app/Http/Kernel.php的api中间件组:
    'api' => [
        \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
        'throttle:api',
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
    ],
    
  5. 前端Axios开启withCredentials: true,登录前先获取CSRF令牌:
    axios.get('/sanctum/csrf-cookie').then(() => {
        axios.post('/login', { email: 'xxx', password: 'xxx' });
    });
    

2. 明确路由的认证守卫

确保fetchLoggedUser路由指定正确的认证守卫,比如你用web guard(普通登录逻辑)的话,路由需显式声明:

Route::get('/fetch-logged-user', [\App\Http\Controllers\Api\ApartmentController::class, 'fetchLoggedUser'])->middleware('auth:web');

3. 控制器中指定认证守卫检查

在API控制器的对应方法里,明确使用web guard校验登录状态:

use Illuminate\Support\Facades\Auth;

public function fetchLoggedUser()
{
    if (Auth::guard('web')->check()) {
        return response()->json(Auth::guard('web')->user());
    }
    return response()->json(['message' => 'User not authenticated'], 401);
}

4. 检查CORS与会话配置

  • 确认config/cors.php中supports_credentials为true,且allowed_origins包含你的前端域名
  • 检查.env文件:SESSION_DRIVER设为file或database,SESSION_DOMAIN匹配前后端共用的根域名(如.yourdomain.com)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 08:30:56