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

本地环境下Laravel Sanctum保护路由返回401错误求助

Laravel Sanctum 跨域认证问题

已经在Stack Overflow查阅多篇相关帖子,但未找到问题解决方案。用户登录后访问/files路由应返回HTTP 200状态码,目前无法实现。我的Laravel API地址为https://localhost:8090,React前端地址为https://localhost:3000,二者同属顶级域名localhost,符合Sanctum的域名要求。/sanctum/csrf-cookie和/login接口均可成功请求,返回204状态码且已正确设置Cookie。

开发者控制台中的Cookie视图
网络标签页
响应头
请求头


前端JS代码

import axios from 'axios';
 
const apiClient = axios.create({
    baseURL: 'https://localhost:8090',
    withCredentials: true,
});

export const login = (email, password) => {
    apiClient.get('/sanctum/csrf-cookie').then(() => {
        apiClient.post('/login', {
            email,
            password
        }).then(response => {
            apiClient.get('api/files').then(response => {
                console.log(response);
            })
        })
    });
};

环境变量配置

APP_URL=https://localhost:8090
SESSION_DRIVER=file # 也试过cookie驱动
CLIENT_ORIGIN=https://localhost:3000
SESSION_SECURE_COOKIE=true # 也试过false
SESSION_DOMAIN=localhost
SANCTUM_STATEFUL_DOMAINS=localhost:3000 # 这里试过多种组合

cors.php 配置

<?php

return [
    'paths' => ['api/*', 'sanctum/csrf-cookie', 'login'],
    'allowed_methods' => ['*'],
    'allowed_origins' => [env('CLIENT_ORIGIN')],
    'allowed_origins_patterns' => [],
    'allowed_headers' => ['*'],
    'exposed_headers' => ['Content-Disposition'],
    'max_age' => 0,
    'supports_credentials' => true,
];

登录路由(web.php)

Route::group([
    'middleware' => 'web',
], function () {
    Route::post('/login', [AuthenticationController::class, 'login']);
});

受保护路由(api.php)

Route::group([
    'middleware' => 'auth:sanctum',
], function () {
    Route::get('/files', 'FileController@all');
});

Kernel.php 中间件配置

protected $middleware = [
        \Illuminate\Http\Middleware\HandleCors::class,
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
        \Mz\Http\Middleware\TrimStrings::class,
        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
    ];

    /**
     * The application's route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [
        'api' => [
            \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
            'throttle:60,1',
            'bindings',
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        ],
        'web' => [
            \Mz\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \Mz\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],
    ];

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 00:30:33