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 return to a page they have previously left open, only to find ajax requests don't work. The ajax requests don't work because the session has timed out (and the token no longer validates?). If these users were "logged in" users, then I could simply redirect them back to the login page. Since they are public users, then the user is forced to refresh the page to get it back working (awkward).

还是我错了?CSRF令牌是否仍会得到Laravel的验证(即使在会话超时后,页面仍将通过令牌发送……但Laravel将如何处理它?).一个最佳的解决方案是让令牌部分基于时间戳,这样我们就可以在会话时间限制之外给出令牌的到期限制.我可以让我的CSRF token 持续2天(因此只有离开2天的用户才会返回死页).

最后,这就引出了我的问题:Where is the specific code in the Laravel framework that handles this?我目前正试图找到它.此外,是否有一个简单的替代我可以做,或者我留下来创建我自己的版本的csrf_token();输出到我的网页,然后我需要创建我自己的路由过滤器来配合它.

推荐答案

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

它告诉我们,如果你有一条路由:

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

而且,是的,你可以创建自己的csrf_token()个,你只需要在Laravel之前加载它.如果你看看帮手们.在Laravel源代码中的php文件中,您将看到它仅在不存在的情况下创建该函数:

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

Laravel相关问答推荐

到查询构建器的MySQL查询

Laravel 联合和分页

如何在控制器中获取所需参数?

如何仅将日期列解析为月和日?

从 Laravel 中的值开始主键

基于值laravel提交表单后如何返回特定页面

如何获得每种类型的总和

Laravel 连接表

Eloquent: hasNot 带参数

Laravel 保存一对多关系

Laravel:`loadMissing` 函数的目的是什么?

Laravel 监听器监听多个事件

你如何在自定义 Laravel Nova 工具中使用确认对话?

中间件中的 Laravel 依赖注入

导航栏品牌中的 Laravel 动态页面标题

如何从 laravel 中的现有数据库创建迁移

调整行数以形成:: Textarea Laravel 5

Laravel 中的 isDirty() 是什么意思?

Laravel binding绑定的用途和目的是什么?

如何访问 Laravel 集合中的第 n 个项目?