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

本地跨端口Vue SPA集成Laravel Sanctum遇401未授权问题求助

解决Laravel Sanctum + Vue SPA 401未授权问题

以下是针对性的排查和修复步骤:

1. 修正Laravel CORS配置

打开config/cors.php,确保以下配置正确:

return [
    'paths' => ['api/*', 'sanctum/csrf-cookie'],
    'allowed_origins' => ['http://localhost:5173'],
    'allowed_methods' => ['*'],
    'allowed_headers' => ['*'],
    'exposed_headers' => [],
    'max_age' => 0,
    'supports_credentials' => true, // 必须设为true,否则Cookie无法跨域传递
];

2. 完善Sanctum与Session域名配置

在.env文件中补充或修改:

APP_URL=http://localhost:8000
SANCTUM_STATEFUL_DOMAINS=localhost:5173
SESSION_DOMAIN=.localhost // 注意前面的点,确保跨端口共享Cookie

3. 规范Axios请求流程

  • 确保Axios全局配置正确:
    import axios from 'axios';
    
    axios.defaults.baseURL = 'http://localhost:8000/api';
    axios.defaults.withCredentials = true;
    axios.defaults.withXSRFToken = true;
    
  • 必须先获取CSRF令牌再发起登录/受保护请求:
    // 登录流程示例
    async function login(credentials) {
      // 先获取CSRF Cookie
      await axios.get('http://localhost:8000/sanctum/csrf-cookie');
      // 再发送登录请求
      const res = await axios.post('/login', credentials);
      return res.data;
    }
    

4. 确认路由中间件使用正确

受保护的API路由必须使用auth:sanctum中间件,而非web或普通auth:

// routes/api.php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

Route::middleware('auth:sanctum')->group(function () {
    Route::get('/user', function (Request $request) {
        return $request->user();
    });
    // 其他受保护路由
});

5. 浏览器端Cookie与请求头检查

  • 打开浏览器开发者工具(F12)→ Application → Cookies,确认存在laravel_session和XSRF-TOKEN两个Cookie,且Domain为.localhost、Path为/
  • 查看Network面板中受保护请求的请求头:
    • 确认X-XSRF-TOKEN头存在,且值与Cookie中的XSRF-TOKEN一致
    • 确认Origin头为http://localhost:5173

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 16:27:12