Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 234
Raheel Hasan Avatar asked Sep 20 '16 23:09

Raheel Hasan


People also ask

Does laravel API need CSRF token?

Laravel automatically generates a CSRF "token" for each active user session managed by the application. This token is used to verify that the authenticated user is the person actually making the requests to the application.

Can we use session in API laravel?

Laravel Passport is a token-based authentication package, it does not use sessions!


1 Answers

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(...);
});
like image 131
jakub wrona Avatar answered Nov 05 '22 15:11

jakub wrona