Back

Disabling the CSRF Middleware in Laravel 5


opilo posted 2 years ago

I noticed CSRF Middleware is applied to all POST and DELETE requests by default. Is there anyway to disable it and only apply it on selected routes?

Thanks

adaojunior replied 2 years ago

I removed 'Illuminate\Foundation\Http\Middleware\VerifyCsrfToken' in app/Http/Kernel.php.

	protected $middleware = [
		'Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode',
		'Illuminate\Cookie\Middleware\EncryptCookies',
		'Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse',
		'Illuminate\Session\Middleware\StartSession',
		'Illuminate\View\Middleware\ShareErrorsFromSession',
		'Illuminate\Foundation\Http\Middleware\VerifyCsrfToken',
	];

does anyone know if there's another way?

jimgwhit replied 2 years ago

Sorry to inject here, but you have marked as solution but there is still a question. I'd like to know the correct way also to turn it off.

opilo replied 2 years ago

jimgwhit said:

Sorry to inject here, but you have marked as solution but there is still a question. I'd like to know the correct way also to turn it off.

You are right,I reopened the topic.

AlexanderWright replied 2 years ago

I would edit your app/Http/Middleware/VerifyCsrfToken.php and change the following:

public function handle($request, Closure $next)
{
        // Add this:
        if($request->method() == 'POST')
        {
		return $next($request);
        }

	if ($request->method() == 'GET' || $this->tokensMatch($request))
	{
		return $next($request);
	}
	throw new TokenMismatchException;
}

Obviously you can add other conditions, like checking the origin, etc.

jimgwhit replied 2 years ago

I have no app/Http/Middleware/VerifyCsrfToken.php file, nor folder.

EdRands replied 2 years ago

The VerifyCsrfToken Middleware was absorbed into the actual framework a little while ago, so you won't find that file in any up-to-date install of Laravel 5.

igaster replied 2 years ago

CSRF is now a "middleware" registered globally in App\Http\Kernel.php. Removing it will default to no CSRF protection (Laravel4 behavior).

To enable it in a route:

Create a short-hand key in your app/Providers/RouteServiceProvider.php :

protected $middleware = [
  // ....
  'csrf'  => 'Illuminate\Foundation\Http\Middleware\VerifyCsrfToken',
];

You can now enable it to any Route:

$router->post('url', ['middleware' => 'csrf', function() {
 ... 
}]);

Not the most elegant solution IMO...

Offtopic:

Form POST should be CSRF checked. But what about AJAX calls, RESTful API requests etc??? I think Laravel should not be so opinionated...

nmabhinandan replied 2 years ago

igaster said: Form POST should be CSRF checked. But what about AJAX calls, RESTful API requests etc??? I think Laravel should not be so opinionated...

Exactly

Foxandxss replied 2 years ago

In my humble opinion, framework's opinions are not that bad if they can be changed easily.

Using Laravel + some frontend framework and JWT for authentication, there is no need of CSRF in any way but if you can disable it removing it from the middleware list, that is not bad at all.

I guess Laravel has some goal in mind, to provide some standards for the most common applications. If apart from that, it allows you to override those standards, fine for me.

levacic replied 2 years ago

Why do you think that you don't need to check AJAX/API calls for CSRF? In case of API, you might have a different authentication method (e.g. via headers), but AJAX calls are just as susceptible to CSRF as non-AJAX ones.

What we do in our apps is add a <meta name="csrf-token" content="{{{ Session::token() }}}"> in our <head> in all pages, and we've abstracted AJAX calls with a custom function that always appends the token to all calls automatically. It's just a little bit of upfront work, with no extra work later on, but all of our AJAX endpoints are also protected against CSRF.

(We actually use RESTful API endpoints for AJAX, with authentication allowed either through the session, or via headers for non-browser-based API clients, and skip the CSRF check for non-AJAX calls, but this is beyond the scope of this answer.)

israelshirk replied 2 years ago

This thread is a little old but ranked high on Google; so apologies for the late response - it's for posterity :)

The proper way to neuter the default behavior of using the App\Http\Middleware\VerifyCsrfToken middleware from your Laravel 5 application would be to nix it from App/Http/Kernel.php. Before:

	protected $middleware = [
		'Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode',
		'Illuminate\Cookie\Middleware\EncryptCookies',
		'Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse',
		'Illuminate\Session\Middleware\StartSession',
		'Illuminate\View\Middleware\ShareErrorsFromSession',
		'App\Http\Middleware\VerifyCsrfToken',
	];

After:

	protected $middleware = [
		'Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode',
		'Illuminate\Cookie\Middleware\EncryptCookies',
		'Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse',
		'Illuminate\Session\Middleware\StartSession',
		'Illuminate\View\Middleware\ShareErrorsFromSession',
	];

Or, assuming you're doing things only by REST, you can get rid of all of the involved middleware overhead, which you'd probably end up substituting a custom authentication/authorization middleware for later:

	protected $middleware = [
	];

In any kind of hybrid API/end-user application any of this would be bad form, yada, yada, yada. You can enable/disable on a per-route basis similar to @igaster's comment above.

jnewing replied 2 years ago

Another simple option is what I did when I needed to allow post requests to an RESTful API was create my own middleware that extends VerifyCsrfToken, then add in your own exclusion function. After just replace the one in App/Http/Kernal.php with your own. I like this as I wanted to keep CSRF ON as I think it's just a must for security.

In this example I called mine VerifyCsrf

File: App\Http\Middleware\VerifyCsrf.php

<?php namespace App\Http\Middleware;

class VerifyCsrf extends \Illuminate\Foundation\Http\Middleware\VerifyCsrfToken
{
    /**
     * Routes we want to exclude.
     *
     * @var array
     */
    protected $routes = [
            'api/some/route',
            'another/route/here',
            'yup/more/routes',
    ];

     /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     *
     * @throws \Illuminate\Session\TokenMismatchException
     */
    public function handle($request, \Closure $next)
    {
        if ($this->isReading($request) 
            || $this->excludedRoutes($request) 
            || $this->tokensMatch($request))
        {
            return $this->addCookieToResponse($request, $next($request));
        }

        throw new \TokenMismatchException;
    }

    /**
     * This will return a bool value based on route checking.

     * @param  Request $request
     * @return boolean
     */
    protected function excludedRoutes($request)
    {
        foreach($this->routes as $route)
            if ($request->is($route))
                return true;

            return false;
    }

}

Then I swapped it out in App\Http\Kernel.php

<?php namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{

	/**
	 * The application's global HTTP middleware stack.
	 *
	 * @var array
	 */
	protected $middleware = [
		'Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode',
		'Illuminate\Cookie\Middleware\EncryptCookies',
		'Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse',
		'Illuminate\Session\Middleware\StartSession',
		'Illuminate\View\Middleware\ShareErrorsFromSession',
		// 'App\Http\Middleware\VerifyCsrfToken',
                'App\Http\Middleware\VerifyCsrf',
	];

	/**
	 * The application's route middleware.
	 *
	 * @var array
	 */
	protected $routeMiddleware = [
		'auth' => 'App\Http\Middleware\Authenticate',
		'auth.basic' => 'Illuminate\Auth\Middleware\AuthenticateWithBasicAuth',
		'guest' => 'App\Http\Middleware\RedirectIfAuthenticated',
	];

}

msalom28 replied 2 years ago

jnewing said:

Another simple option is what I did when I needed to allow post requests to an RESTful API was create my own middleware that extends VerifyCsrfToken, then add in your own exclusion function. After just replace the one in App/Http/Kernal.php with your own. I like this as I wanted to keep CSRF ON as I think it's just a must for security.

In this example I called mine VerifyCsrf

File: App\Http\Middleware\VerifyCsrf.php

<?php namespace App\Http\Middleware;

class VerifyCsrf extends \Illuminate\Foundation\Http\Middleware\VerifyCsrfToken
{
   /**
    * Routes we want to exclude.
    *
    * @var array
    */
   protected $routes = [
           'api/some/route',
           'another/route/here',
           'yup/more/routes',
   ];

    /**
    * Handle an incoming request.
    *
    * @param  \Illuminate\Http\Request  $request
    * @param  \Closure  $next
    * @return mixed
    *
    * @throws \Illuminate\Session\TokenMismatchException
    */
   public function handle($request, \Closure $next)
   {
       if ($this->isReading($request) 
           || $this->excludedRoutes($request) 
           || $this->tokensMatch($request))
       {
           return $this->addCookieToResponse($request, $next($request));
       }

       throw new \TokenMismatchException;
   }

   /**
    * This will return a bool value based on route checking.

    * @param  Request $request
    * @return boolean
    */
   protected function excludedRoutes($request)
   {
       foreach($this->routes as $route)
           if ($request->is($route))
               return true;

           return false;
   }

}

Then I swapped it out in App\Http\Kernel.php

<?php namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{

  /**
   * The application's global HTTP middleware stack.
   *
   * @var array
   */
  protected $middleware = [
  	'Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode',
  	'Illuminate\Cookie\Middleware\EncryptCookies',
  	'Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse',
  	'Illuminate\Session\Middleware\StartSession',
  	'Illuminate\View\Middleware\ShareErrorsFromSession',
  	// 'App\Http\Middleware\VerifyCsrfToken',
               'App\Http\Middleware\VerifyCsrf',
  ];

  /**
   * The application's route middleware.
   *
   * @var array
   */
  protected $routeMiddleware = [
  	'auth' => 'App\Http\Middleware\Authenticate',
  	'auth.basic' => 'Illuminate\Auth\Middleware\AuthenticateWithBasicAuth',
  	'guest' => 'App\Http\Middleware\RedirectIfAuthenticated',
  ];

}

Great solution. Thanks!

filipeaclima replied 2 years ago

@levacic

I'm also developing a RESTfull API using Laravel and disabling CSRF protection just seemed a really bad idea to me, but whenever a client tried to reach an endpoint (route) that expects POST, PUT or DELETE a TokenMismatchException was thrown by the application.

What I ended up doing, was to override the tokensMatch function of Illuminate\Foundation\Http\Middleware\VerifyCsrfToken To achieve this I added the following on App\Http\Middleware\VerifyCsrfToken (yes, our infamous middleware!), since it's already extending the class we want to override:

/**
 * Determine if the session and input CSRF tokens match.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return bool
 */
protected function tokensMatch($request)
{
	$token = $request->input('_token') ?: $request->session()->getToken();

	if ( ! $token && $header = $request->header('X-XSRF-TOKEN'))
	{
		$token = $this->encrypter->decrypt($header);
	}

	return StringUtils::equals($request->session()->token(), $token);
}

Don't forget to also add:

use Symfony\Component\Security\Core\Util\StringUtils;

Summing up, what I did was fetch the _token on the session instead of the default Laravel's behaviour of fetching it on the input.

Just my 2 cents, hope it helps!

vineetgarg90 replied 2 years ago

Checkout this tutorial on how to disable CSRF on specific routes in Laravel 5

http://www.techigniter.in/tutorials/disable-csrf-check-on-specific-routes-in-laravel-5/

MarkGavalda replied 2 years ago

That seems like an elegant solution vineetgarg90, thanks for sharing.

jasonhoule replied 2 years ago

The way I did this was to alter the \App\Http\Middleware\VerifyCsrfToken class to check the Auth config file for paths where I do not want to have the csrf validation.

public function handle($request, Closure $next)
{
        if(in_array($request->path(), Config::get('auth.no_csrf'))) {
            return parent::addCookieToResponse($request, $next($request));
        }
        return parent::handle($request, $next);
}

and in \Config\Auth.php I added

'no_csrf' => array('nocsrf/path/1', 'no/csrf/path/2'),

I hope this helps someone.

sambindoff replied 2 years ago

Very nice @jasonhoule really tidy way of doing things in L5, thanks!

dnamotoring replied 2 years ago

jasonhoule said:

The way I did this was to alter the \App\Http\Middleware\VerifyCsrfToken class to check the Auth config file for paths where I do not want to have the csrf validation.

public function handle($request, Closure $next)
{
       if(in_array($request->path(), Config::get('auth.no_csrf'))) {
           return parent::addCookieToResponse($request, $next($request));
       }
       return parent::handle($request, $next);
}

and in \Config\Auth.php I added

   'no_csrf' => array('nocsrf/path/1', 'no/csrf/path/2'),

I hope this helps someone.

Wow thanks a lot! I was stuck for so long and realized I had to disable CSRF on some routes and your solution was the most straight forward.

By the way I had to add:

use Config;

At the top of VerifyCsrfToken.php or it gave me an error of it not found.

lu32 replied 2 years ago

pretty clever

jnewing said:

Another simple option is what I did when I needed to allow post requests to an RESTful API was create my own middleware that extends VerifyCsrfToken, then add in your own exclusion function. After just replace the one in App/Http/Kernal.php with your own. I like this as I wanted to keep CSRF ON as I think it's just a must for security.

In this example I called mine VerifyCsrf

File: App\Http\Middleware\VerifyCsrf.php

<?php namespace App\Http\Middleware;

class VerifyCsrf extends \Illuminate\Foundation\Http\Middleware\VerifyCsrfToken
{
   /**
    * Routes we want to exclude.
    *
    * @var array
    */
   protected $routes = [
           'api/some/route',
           'another/route/here',
           'yup/more/routes',
   ];

    /**
    * Handle an incoming request.
    *
    * @param  \Illuminate\Http\Request  $request
    * @param  \Closure  $next
    * @return mixed
    *
    * @throws \Illuminate\Session\TokenMismatchException
    */
   public function handle($request, \Closure $next)
   {
       if ($this->isReading($request) 
           || $this->excludedRoutes($request) 
           || $this->tokensMatch($request))
       {
           return $this->addCookieToResponse($request, $next($request));
       }

       throw new \TokenMismatchException;
   }

   /**
    * This will return a bool value based on route checking.

    * @param  Request $request
    * @return boolean
    */
   protected function excludedRoutes($request)
   {
       foreach($this->routes as $route)
           if ($request->is($route))
               return true;

           return false;
   }

}

Then I swapped it out in App\Http\Kernel.php

<?php namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{

  /**
   * The application's global HTTP middleware stack.
   *
   * @var array
   */
  protected $middleware = [
  	'Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode',
  	'Illuminate\Cookie\Middleware\EncryptCookies',
  	'Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse',
  	'Illuminate\Session\Middleware\StartSession',
  	'Illuminate\View\Middleware\ShareErrorsFromSession',
  	// 'App\Http\Middleware\VerifyCsrfToken',
               'App\Http\Middleware\VerifyCsrf',
  ];

  /**
   * The application's route middleware.
   *
   * @var array
   */
  protected $routeMiddleware = [
  	'auth' => 'App\Http\Middleware\Authenticate',
  	'auth.basic' => 'Illuminate\Auth\Middleware\AuthenticateWithBasicAuth',
  	'guest' => 'App\Http\Middleware\RedirectIfAuthenticated',
  ];

}

eduardostuart replied 2 years ago

Another solution:

<?php namespace App\Http\Middleware;

use Closure;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier;

class VerifyCsrfToken extends BaseVerifier {

	protected $excludeRoutes = [
		'api*'
	];

	/**
	 * Handle an incoming request.
	 *
	 * @param  \Illuminate\Http\Request  $request
	 * @param  \Closure  $next
	 * @return mixed
	 */
	public function handle($request, Closure $next)
	{
		foreach( $this->excludeRoutes as $route )
		{
			if( $request->is( $route ) ) return $next($request);
		}

		return parent::handle($request, $next);
	}

}
ricardoaat replied 2 years ago

eduardostuart said:

Another solution:

<?php namespace App\Http\Middleware;

use Closure;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier;

class VerifyCsrfToken extends BaseVerifier {

  protected $excludeRoutes = [
  	'api*'
  ];

  /**
   * Handle an incoming request.
   *
   * @param  \Illuminate\Http\Request  $request
   * @param  \Closure  $next
   * @return mixed
   */
  public function handle($request, Closure $next)
  {
  	foreach( $this->excludeRoutes as $route )
  	{
  		if( $request->is( $route ) ) return $next($request);
  	}

  	return parent::handle($request, $next);
  }

}

this did the trick, Thank you.

HolgerW1 replied 2 years ago

Another possible solution (not ideal though):

<?php namespace App\Http\Middleware;

use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier;
use Route;
use Closure;

class VerifyCsrfToken extends BaseVerifier {

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $route = Route::getRoutes()->match($request);
        $routeAction = $route->getAction();
        if (isset($routeAction['nocsrf']) && $routeAction['nocsrf']) {
            return $next($request);
        }
        return parent::handle($request, $next);
    }

}

In your routes.php you may then disable the CSRF check for specific routes via

    Route::any('test', [
        'as' => 'external.test',
        'uses' => 'TestController@test',
        'nocsrf' => true,
    ]);

The solution is not ideal since we manually do the route matching which is done again after all global middlewares have finished (sendRequestThroughRouter). So we produce a little bit of an overhead there.

The advantage of this solution is that you can disable the CSRF check inside your routes.php and you don't need to change anyhting if your route name / URL ever changes. I.e. it is way easier to refactor / maintain your routes.

joetito1 replied 2 years ago

If you want to disable CSRF for every route, you can modify the Middleware/VerifyCsrfToken.php classes $except array to be like this:

protected $except = [
        '*',
];

This seems to be the cleanest way without modifying Laravel classes.

levacic replied 2 years ago

HolgerW1 said:

Another possible solution (not ideal though):

<?php namespace App\Http\Middleware;

use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier;
use Route;
use Closure;

class VerifyCsrfToken extends BaseVerifier {

   /**
    * Handle an incoming request.
    *
    * @param  \Illuminate\Http\Request  $request
    * @param  \Closure  $next
    * @return mixed
    */
   public function handle($request, Closure $next)
   {
       $route = Route::getRoutes()->match($request);
       $routeAction = $route->getAction();
       if (isset($routeAction['nocsrf']) && $routeAction['nocsrf']) {
           return $next($request);
       }
       return parent::handle($request, $next);
   }

}

In your routes.php you may then disable the CSRF check for specific routes via

   Route::any('test', [
       'as' => 'external.test',
       'uses' => 'TestController@test',
       'nocsrf' => true,
   ]);

The solution is not ideal since we manually do the route matching which is done again after all global middlewares have finished (sendRequestThroughRouter). Plus the match method does actually more than we really need (binding, ...).

The advantage of this solution is that you can disable the CSRF check inside your routes.php and you don't need to change anyhting if your route name / URL ever changes. I.e. it is way easier to refactor / maintain your routes.

You can in fact use Route::current() to get the currently matched route.

HolgerW1 replied 2 years ago

levacic said: You can in fact use Route::current() to get the currently matched route.

You unfortunately can't use Route::current() for global middlewares since the request to route matching is done after all global middlewares have finished. And the CSRF verifier is a global middleware for all routes by default.

This would work for route specific middlewares though since they run after the route matching.

levacic replied 2 years ago

HolgerW1 said:

You unfortunately can't use Route::current() for global middlewares since the request to route matching is done after all global middlewares have finished. And the CSRF verifier is a global middleware for all routes by default.

This would work for route specific middlewares though since they run after the route matching.

Oops! You are, of course, correct about that.

I'm new to L5 so I haven't yet had the time to dig into the framework and see how everything gets executed - but is there any specific reason why middleware runs before the route is matched? Is that so as to allow changing the request itself while it's on its way in? Even so, I'm not sure I would ever want to change the URL the user is trying to access, so this doesn't make much sense to me, though I'm likely overlooking something - it just seems like it would be possible to match the route before we run the middleware.

Thanks!

HolgerW1 replied 2 years ago

levacic said:

Oops! You are, of course, correct about that.

I'm new to L5 so I haven't yet had the time to dig into the framework and see how everything gets executed - but is there any specific reason why middleware runs before the route is matched? Is that so as to allow changing the request itself while it's on its way in? Even so, I'm not sure I would ever want to change the URL the user is trying to access, so this doesn't make much sense to me, though I'm likely overlooking something - it just seems like it would be possible to match the route before we run the middleware.

Thanks!

I honestly don't know the actual reason behind this design, you should ask Graham Campbell or Taylor Otwell.

Here's the code in Kernel.php responsible for this behavior:

    return (new Pipeline($this->app))
                    ->send($request)
                    ->through($shouldSkipMiddleware ? [] : $this->middleware)
                    ->then($this->dispatchToRouter());

As you can see dispatchToRouter is called after the global middlewares have finished (through command).

Imho it would be helpful if the request to route matching would be done before the global middlewares are being executed and thus if the middlewares would have access to the route data. But I doubt Graham or Taylor will change this since it would mean some fundamental restructuring of that specific code.

HolgerW1 replied 2 years ago

Btw. here's the 'official' answer to that from Taylor Otwell: https://github.com/laravel/framework/pull/9708

BenjaminListwon replied 1 year ago

Riffing off what folks have done so far, I did the following.

In a new config file (so I don't run into upgrade collisions) located at config/custom.php I created this:

return [

    /*
    |--------------------------------------------------------------------------
    | CSRF Exemptions
    |--------------------------------------------------------------------------
    |
    | Routes we do not check for CSRF. Note: Should use other means of 
    | authenticating the origin, etc.
    |
    */

    'csrf_exempt_routes' => array(
    	'api/*',
    ),
	
];

Note that you can use specific routes like foo/bar or the wildcard foo/* to match. Not sure if it allows more complex regex. Also, do not include a leading /.

Then, in app/Http/Middleware/VerifyCsrfToken.php I set the $except variable to the values specified in the config like so:

use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier;
use Illuminate\Contracts\Encryption\Encrypter;
use Config;


class VerifyCsrfToken extends BaseVerifier
{
    /**
     * The URIs that should be excluded from CSRF verification.
     *
     * @var array
     */
    protected $except = [];
	
	
    /**
     * Create a new middleware instance. We set our exceptions in a 
     * config file.
     *
     * @param  \Illuminate\Contracts\Encryption\Encrypter  $encrypter
     * @return void
     */
    public function __construct(Encrypter $encrypter)
    {
        parent::__construct($encrypter);
        $this->except = Config::get('custom.csrf_exempt_routes');
    }		
}

Hope this method helps someone.

Extra Credit

I plan to subclass Route eventually so I can pass a parameter into the route definition like:

public function __construct($methods, $uri, $action, $options)

...

$options = array('disable_csrf' => true);
Route::get('/foo/', function () { ... }, $options);

...

That way, there is no need to duplicate route specs in the config, which is a tad error prone.

basementjack replied 1 year ago

Not sure if this is new to 5.1: http://laravel.com/docs/5.1/routing#csrf-excluding-uris

muhammadshakeel replied 1 year ago

You can exclude URIs from CSRF by simply adding them to the $except property of the VerifyCsrfToken middleware:

<?php

namespace App\Http\Middleware;

use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier;

class VerifyCsrfToken extends BaseVerifier
{
    /**
     * The URIs that should be excluded from CSRF verification.
     *
     * @var array
     */
    protected $except = [
        'api/*',
    ];
}

Documentation: http://laravel.com/docs/5.1/routing#csrf-protection

Terrymol replied 1 year ago

hi AlexanderWright, you save my time

SeunMatt replied 6 months ago

In laravel 5.3 To exclude a path from csrf middleware check open app\Http\Middleware\VerifyCsrfToken.php file and add the path to the $except array. like this

protected $except = [ // "api/" //every route starting with /api/ should be ignored for csrf check ];

note the use of wildcard in the route definition

AndySchaafTHP replied 6 months ago

What about using the $except array and wildcards?

 protected $except = [
    'mandrill/*',
    'pusher/*',
];

That's worked without having to redefine the VerifyCSRFToken middleware for me.

mylonasg88 replied 6 months ago

Laravel 4.2

filters.php

Route::filter('csrf', function () {
    if(Config::get('auth.no_csrf')){
        return;
    }

    if (Session::token() !== Input::get('_token')) {
        throw new Illuminate\Session\TokenMismatchException('CSRF token not provided', 401);
    }
});

routes.php

Route::group(['after' => 'no-cache', 'prefix' => 'api/v1'], function () {
    // Disable CSRF protection
    Config::set('auth.no_csrf', true);

    Route::post('/test/search', ['auth.no_csrf' => 'val','uses' => 'Controllers\Api\SearchController@postSearch']);
});

Sign in to participate in this thread!



We'd like to thank these amazing companies for supporting us