Search code examples
laravelposthttp-postcsrf

laravel: can not accept post request without csrf


I have added into the exceptions:

    protected $except = [
        'pay/finish'
    ];

But still I am getting MethodNotAllowedException

Route is defined in web.php

Route::post('/pay/finish', ['as' => 'pay.finish', 'uses' => 'PaymentController@finish']);

The post request comes from another domain.


Solution

  • You don't normally get a MethodNotAllowedException from an invalid CSRF token. I normally get a 419 response from CSRF issues.

    However, assuming the CSRF token is the problem you could move your route from web.php to api.php. Be aware this adds the prefix api/ to the URL.

    The middleware that checks the CSRF token is applied in your Kernel to all routes in web.php but not to those is api.php

    You could verify whether the CSRF check is really the problem by looking in your App\Http\Kernel file and commenting out \App\Http\Middleware\VerifyCsrfToken::class from:

    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,
            \Laravel\Passport\Http\Middleware\CreateFreshApiToken::class,
        ],
    
        'api' => [
            'throttle:60,1',
            'bindings',
        ],
    ];
    

    If your route then works it is CSRF and you can move the route to the API routes file and hit it at api/pay/finish with the api prefix.

    If not then I suggest you look at what's calling your route and check the correct http method is being called. Is it definitely sending a POST request? Do you have the _method input specified in your form that Laravel checks for POST requests to mutate them to PUT or PATCH for its edit routes?