Laravel enable csrf protection on api middleware

前端 未结 3 1606
情深已故
情深已故 2020-12-17 01:02

I\'m working on Laravel 5.4 and my routes are in the api middleware

I see that I need to transfer my routes to the web middleware, but I need them to be on the api m

相关标签:
3条回答
  • 2020-12-17 01:07

    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?

    0 讨论(0)
  • 2020-12-17 01:20

    Make sure your web middleware group contains the following line and just be sure verify the content with a clean laravel installation of the same version.

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

    And verify that the routes use the web middleware. You check that by running php artisan route:list and note the middleware column.

    0 讨论(0)
  • 2020-12-17 01:28

    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,
        ],
    ];
    
    0 讨论(0)
提交回复
热议问题