Laravel enables csrf protection on api middleware

I am working on Laravel 5.4 and my routes are in middleware api

I see that I need to transfer my routes to the middleware, but I need them to be on the api middleware since I am creating a RESTful api, any suggestions on how I could use csrf with the middleware api?

+4
source share
3 answers

CSRF protection prevents attacks using a previously authenticated user (usually setting state using a session) https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF) .

The sedative API does not have the state https://en.wikipedia.org/wiki/Representational_state_transfer , so there is no session to attack. Thus, in a robust API, CSRF protection is to authenticate the user on every request, if you only authenticate the user on the first request and use the session for the next requests that you do not restfull API, and must use network middleware.

Edit: How are you going to get the CSRF token for the client if you do not have any state?

+3

, . Laravel . Kernel.php App\Http. protected $middlewareGroups 28 , , Csrf api:

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,
    ],

    'api' => [
        'throttle:60,1',
        'bindings',
        \App\Http\Middleware\VerifyCsrfToken::class,
    ],
];
+2

, , larvel .

\App\Http\Middleware\VerifyCsrfToken::class,

, - . , php artisan route:list .

0

Source: https://habr.com/ru/post/1677272/


All Articles