How specifically does Laravel build and check a CSRF token?

后端 未结 2 1336
耶瑟儿~
耶瑟儿~ 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:36

    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 section:

      
    

    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
    
    });
    

提交回复
热议问题