Laravel 5.3 - 如何在没有 CSRF 的情况下将会话添加到`API`?

2021-12-18 00:00:00 php laravel-5.3

我正在尝试构建一个 api,出于某种原因,我需要会话.但是如果我包含 web 中间件,我会收到 CSRF 错误,如果我不包含,我就无法启动 session.

Im trying to build an api, and for some reason I need sessions. But if I include web middleware I get CSRF errors, and if I dont I cant have session started.

如何解决这个问题?

推荐答案

转到 app/Http/Kernel.php 并将您自己的名称(如sessions")添加到 $middlewareGroups.它应该包含IlluminateSessionMiddlewareStartSession::class,

go to app/Http/Kernel.php and add your own name like 'sessions' to the $middlewareGroups. It should contain IlluminateSessionMiddlewareStartSession::class,

为您想要的路线分配会话".

Assign 'sessions' to those routes you want.

protected $middlewareGroups = [
        'web' => [
            AppHttpMiddlewareEncryptCookies::class,
            IlluminateCookieMiddlewareAddQueuedCookiesToResponse::class,
            IlluminateSessionMiddlewareStartSession::class,
            IlluminateViewMiddlewareShareErrorsFromSession::class,
            AppHttpMiddlewareVerifyCsrfToken::class,
        ],

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

        'sessions' => [
            IlluminateSessionMiddlewareStartSession::class,
        ]
    ];

路由/api.php

Route::group(['middleware' => ['sessions']], function () {
    Route::resource(...);
});

相关文章