CSRF filter on all post requests except one?

Published 3 years ago by bytefury

i have this defined in routes file. Route::when('*','csrf',['post']);

Now, how can i disable csrf on a particular post route?

Best Answer (As Selected By bytefury)
bashy

Not sure if there's an ->except() for a Route::when() but you could try this. What about making a new one to filter out certain? Or of course add it onto the original csrf filter.

Route::filter('csrf2', function()
{
    if ( ! Request::is('payment-return/*'))
    {
        if (Session::token() !== Input::get('_token'))
        {
            throw new Illuminate\Session\TokenMismatchException;
        }
    }
});

Route::when('*', 'csrf2', ['post']);
pmall
pmall
3 years ago (546,495 XP)

You have to find a pattern that match every routes except this particular route. Anyway, why do you want to disable csrf protection on one route ?

bytefury

i am trying to get values from a payment gateway which sends a confirmation after the payment is complete. but the problem is that it sends a post request on a specified link .

bashy
bashy
3 years ago (997,030 XP)

Not sure if there's an ->except() for a Route::when() but you could try this. What about making a new one to filter out certain? Or of course add it onto the original csrf filter.

Route::filter('csrf2', function()
{
    if ( ! Request::is('payment-return/*'))
    {
        if (Session::token() !== Input::get('_token'))
        {
            throw new Illuminate\Session\TokenMismatchException;
        }
    }
});

Route::when('*', 'csrf2', ['post']);
tag
tag
3 years ago (51,090 XP)

Laravel's Router has a whenRegex() method so you can conditionally match certain patterns without having to create a separate filter:

https://github.com/laravel/framework/blob/4.2/src/Illuminate/Routing/Router.php#L1182

Please sign in or create an account to participate in this conversation.