How specifically does Laravel build and check a CSRF token?

坚强是说给别人听的谎言 提交于 2019-12-03 04:50:01

Laravel just facilitates that for you by keeping the token stored in session, but the code is actually yours (to change as you wish). Take a look at filters.php you should see:

Route::filter('csrf', function()
{
    if (Session::token() != Input::get('_token'))
    {
        throw new Illuminate\Session\TokenMismatchException;
    }
});

It tells us that if you have a route:

Route::post('myform', ['before' => 'csrf', 'uses' => 'MyController@update']);

And the user session expires, it will raise an exception, but you can do the work yourself, keep your own token stored wherever you think is better, and instead of throwing that exception, redirect your user to the login page:

Route::filter('csrf', function()
{
    if (MySession::token() != MyCSRFToken::get())
    {
        return Redirect::to('login');
    }
});

And, yes, you can create your own csrf_token(), you just have to load it before Laravel does. If you look at the helpers.php file in Laravel source code, you`ll see that it only creates that function if it doesn't already exists:

if ( ! function_exists('csrf_token'))
{
    function csrf_token()
    {
       ...
    }
}

Since this has become a popular question, I decided to post my specific solution that has been working quite nicely...

Most likely you will have a header.php or some partial view that you use at the top of all your pages, make sure this is in it in the <head> section:

<meta name="_token" content="<?=csrf_token(); ?>" />  

In your filters.php:

Route::filter('csrf', function() 
{
   if (Request::ajax()) {
        if(Session::token() != Request::header('X-CSRF-Token')){
            throw new Illuminate\Session\TokenMismatchException;
        } 
    }
});

And in your routes.php

Route::group(array('before' => 'csrf'), function(){

    // All routes go in here, public and private

});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!