本地跨端口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
相关产品推荐
相关产品推荐

