Laravel 路由和 CSRF 保护

Laravel routing and CSRF protection

如果我的 routes.php 文件中有这行代码:

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

我还需要这样做吗?

Route::group(array('before' => 'csrf'), function() {
    Route::post('/search', array(
        'as' => 'search-post',
        'uses' => 'SearchController@postSearch'
    ));
});

或者只是这样做可以吗?

Route::post('/search', array(
    'as' => 'search-post',
    'uses' => 'SearchController@postSearch'
));

是;你应该只有 Route::post('/search', [...]);.

是安全的

Route::when 过滤器(内部称为 模式过滤器 )在 before 过滤器之前被调用。只要正常使用路由就可以了。

相关源代码如下:

public function callRouteBefore($route, $request)
{
    $response = $this->callPatternFilters($route, $request);

    return $response ?: $this->callAttachedBefores($route, $request);
}

正如您首先看到的,将调用模式过滤器。如果他们 return 任何响应,它将从这里 return 编辑,否则将调用过滤器之前的 "normal"。