Laravel 5.3 - How to add Sessions to `API` without CSRF?

这一生的挚爱 提交于 2019-12-17 21:18:01

问题


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.

How to solve this?


回答1:


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

Assign 'sessions' to those routes you want.

protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
        ],

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

        'sessions' => [
            \Illuminate\Session\Middleware\StartSession::class,
        ]
    ];

routes/api.php

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


来源:https://stackoverflow.com/questions/39605289/laravel-5-3-how-to-add-sessions-to-api-without-csrf

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!