In Laravel 5, How to disable VerifycsrfToken middleware for specific route?

[亡魂溺海] 提交于 2019-11-27 23:28:29

CSRF is enabled by default on all Routes in Laravel 5, you can disable it for specific routes by modifying app/Http/Middleware/VerifyCsrfToken.php

//app/Http/Middleware/VerifyCsrfToken.php

//add an array of Routes to skip CSRF check
private $openRoutes = ['free/route', 'free/too'];

//modify this function
public function handle($request, Closure $next)
    {
        //add this condition 
    foreach($this->openRoutes as $route) {

      if ($request->is($route)) {
        return $next($request);
      }
    }

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

source

user3252599

In Laravel 5 this has chagned a bit. Now you can simply add the routes you want to exclude from csrftoken verification, in $except array of the class

'VerifyCsrfToken' (\app\Http\Middleware\VerifyCsrfToken.php):

class VerifyCsrfToken extends BaseVerifier
{
    protected $except = [
        // Place your URIs here
    ];
}

Examples:

1. If you are using a route group:

Route::group(array('prefix' => 'api/v2'), function()
{
    Route::post('users/valid','UsersController@valid');
});

Your $except array looks like:

protected $except = ['api/v2/users/valid'];

2. If you are using a simple route

Route::post('users/valid','UsersController@valid');

Your $except array looks like:

protected $except = ['users/valid'];

3. If you want to exclude all routes under main route (users in this case)

Your $except array looks like:

protected $except = ['users/*'];

see: http://laravel.com/docs/master/routing#csrf-excluding-uris

If you are using the version 5.2 then in: app/Http/Middleware/VerifyCsrfToken.php you can add the route to the attribute: protected $except: For example:

protected $except = [
'users/get_some_info',
];

The portion users would be your controller, "get_some_info" would be the action. After you perform this change, make sure you add the route in your routes.php.

Sunilspr7

Add your route to App\Http\Middleware\VerifyCsrfToken.php file:

/**
* The URIs that should be excluded from CSRF verification.
*
* @var array
*/
protected $except = [
'route-name-1', 'route-name-2'
];
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!