使用 JavaScript 使用 API 时禁用 Laravel CSRF 保护 /api 路由

Disable Laravel CSRF Protection for /api routes when consuming API with JavaScript

我有一个 Laravel 后端和 React 前端。对于开发,React 在 localhost:3000 上运行,在 localhost:8080 上运行 Laravel,所以我不得不允许 Cors。

我已经成功设置了 Passport,并且能够 Consume my API with JavaScript

但是在每个请求中,我都必须包含 X-CSRF-TOKEN 以访问受保护的 API 路由,这是有效的,但为了开发,我想为 [=44] 禁用 CSRF-Protection =].

我已经尝试将 /api 路由添加到 VerifyCsrfToken 中的 except 数组并从 Kernel.php 中删除了中间件,但这似乎并没有改变事实上我仍然需要发送 CSRF-Token。

我正在使用 Laravel 5.8 并使用 JavaScript 提取来发出请求。

VerifyCsrfToken:

protected $except = [
    '/api/*'
];```

我在内核中注释掉了VerifyCsrfToken:

protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        // \Illuminate\Session\Middleware\AuthenticateSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        // \App\Http\Middleware\VerifyCsrfToken::class,
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
        \Laravel\Passport\Http\Middleware\CreateFreshApiToken::class,
    ],

    'api' => [
        'throttle:60,1',
        'bindings',
    ],
];

示例API路线:

Route::get('test', function() {
    return response()->json(['success' => 'Hello!']);
})->middleware('auth:api');

我如何尝试访问 API:

const checkStatus = (response) => {
    console.log(response);
    if (response.ok) {
        return response;
    } else {
        const error = new Error(response.statusText);
        error.response = response;
        throw error;
    }
}

const parseJSON = res => res.text();

const Fetcher = {
    get: (ressource) => {
        return fetch(CONSTANTS.API_URL + ressource, {
            method: 'GET',
            mode: 'cors',
            headers: {
                'Accept': 'application/json',
                'X-Requested-With': 'XMLHttpRequest',
                //'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
            },
            credentials: 'include'
        })
            .then(checkStatus)
            .then(parseJSON)
    },
    post: (ressource, data) => {
        return fetch(CONSTANTS.API_URL + ressource, {
            method: 'POST',
            mode: 'cors',
            headers: {
                'Accept': 'application/json',
                'X-Requested-With': 'XMLHttpRequest',
                //'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
            },
            credentials: 'include',
            body: data
        })
            .then(checkStatus)
            .then(parseJSON)
    }
}

尝试隔离问题。
删除路由中的 auth:api 个中间件:

Route::get('api/test', function() {
    return response()->json(['success' => 'Hello!']);
});

注意 url 是 "api/test" 而不仅仅是 "test" 因为你定义了 $except 数组是这样的:

protected $except = [
    '/api/*'
];

在不传递 CSRF 令牌的情况下进行调用。

已编辑

来自 laravel 关于 auth:api 中间件的文档:

Laravel includes an authentication guard that will automatically validate API tokens on incoming requests. You only need to specify the auth:api middleware on any route that requires a valid access token:

这意味着你必须将API令牌传递给auth:api中间件下的路由,否则你会得到401错误。

在路线文件夹下处理 api.php 而非 web.php

中的 api 路线