Laravel enable csrf protection on api middleware

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

A restful API do not have state https://en.wikipedia.org/wiki/Representational_state_transfer, so there is no session to attack. So in a restful API the CSRF protection is to authenticate the user on each request, if you are only authenticating the user on the first request and use session for the following requests you are not making a restfull API and should use the web middleware.

Edit: How are you going to get the CSRF token to the client if you don't have any state?


you can use any middleware as well as your custom middleware in any route group. Laravel makes it very easy for us. Just open the Kernel.php file in App\Http namespace. Find protected $middlewareGroups probable on line 28 and the change the code like below to allow the enable Csrf protection in api routes:

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

Tags:

Php

Csrf

Laravel