这是在Laravel中设置CSRF保护的更好方法


Which is the better way to setup CSRF protection in Laravel?

将它添加到 BaseController.php:

public function __construct() {
    // Run the 'csrf' filter on all post, put, patch and delete requests.
    $this->beforeFilter('csrf', ['on' => ['post', 'put', 'patch', 'delete']]);
}

或将其添加到路由.php:

Route::when('*', 'csrf', array('post', 'put', 'patch', 'delete'));

哪个是更好的方法,为什么?

两者将具有相同的效果,但Router::when方法似乎更优惠。

在没有适当的parent::__construct()调用的情况下,很容易扩展错误的控制器或过载BaseController::__construct()。在这两种情况下都不会发生错误。如果这是偶然发生的,您将有一个无声的安全漏洞:

class FooController extends App'BaseController
{
    public function __construct()
    {
         $this->initializeSomething() 
         // somebody forgot to call parent::__construct()
    }
    public function action()
    {
         // no CSRF protection here!
    }
}

使用路由器似乎不太容易出错,以后没有简单的方法可以意外覆盖过滤器。

Route::when('*', 'csrf', array('post', 'put', 'patch', 'delete'));