2

I am using restful controllers. I need to run some filters like auth and custom permissions on them. So I put them in a route group and set filters on that group. In addition I also want to run csrf filter but only on post requests. How to do this in the route group?

Added code for clarification

Route::group(array('before' => 'auth|allowed|csrf'), function() {
    Route::controller('controller', 'SomeController');
    Route::controller('othercontroller', 'OtherController');
});

I want the csrf only on post routes. I really don't want to add a filter on every controller (there are quite a few);

4

4 回答 4

10

在使用资源丰富的路由时,您可以从控制器执行此操作。

public function __construct() {
  $this->beforeFilter('csrf', array('on' => 'post'));
}
于 2013-09-19T16:31:20.877 回答
2

您可以创建一个运行标准 CSRF 过滤器的自定义过滤器,但仅限于这样的 POST 请求......

Route::filter('csrfIfPost', function($route, $request) {
    if ($request->getMethod() == 'POST') 
        return $route->callFilter('csrf', $request);
});

然后在任何你想使用它的地方,只需使用过滤器“csrfIfPost”而不是“csrf”。

于 2013-12-02T20:12:11.977 回答
1

好的。我想我解决了。我检查了请求是否已发布。不知道这是否是不好的做法。我将 filter.php 中的 csrf 过滤器更改为

Route::filter('csrf', function()
{
    if (Request::getMethod() == 'POST' && Session::token() != Input::get('_token'))
    {
        throw new Illuminate\Session\TokenMismatchException;
    }
});
于 2013-09-20T18:24:00.763 回答
1

您可以在组内拥有组:

Route::group(array('before' => 'session'), function()
{
    Route::get('/login', array('as'=>'login', 'uses'=>'LogonController@form'));

    Route::group(array('before' => 'csrf'), function()
    {
        Route::post('/login', array('as'=>'login.post', 'before' => 'csrf', 'uses'=>'LogonController@login'));

        Route::group(array('before' => 'permissions'), function()
        {
            Route::post('/store/checkout/new/shipping/address', array('as'=>'store.checkout.shipping.address.new',  'uses'=>'StoreController@newShippingAddress'));
        }
    }
}
于 2013-09-19T16:30:39.407 回答