How specifically does Laravel build and check a CSRF token?

后端 未结 2 1333
耶瑟儿~
耶瑟儿~ 2021-02-12 13:38

I\'m using Laravel\'s CSRF protection on my public site. However since Laravel uses a session to maintain this, I\'m worried that a user might walk away from their computer and

2条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-12 14:34

    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()
        {
           ...
        }
    }
    

提交回复
热议问题