在LARLAVEL 5中处理过期令牌的最佳方式是什么?

我的意思是我有一个页面,它有一些执行ajax请求的链接.加载页面时,它们工作正常,但当我等待某个时间时,会出现令牌不匹配错误.

现在,我必须刷新页面才能使其再次工作.但是,我不想刷新页面.我想要一些方法来刷新令牌或其他解决方法来修复它.

我希望你明白我的意思.

推荐答案

Update 2021:

Hello Stackoverflow! It seems that the answer we've posted a few years ago has sparked some controversy.

To sum it up, the approach we've posted does solve the technical aspect of the problem. However, from web security standpoint it seems to be debatable.

With our limited expertise, we still believe our solution is viable, but to reduce doubt please make sure to go through the comments section as well as the answer posted by Ryan since they think otherwise before you make your decision. Thanks.

Original Answer From 2015

a work around for it, is to actually get the new token every certain time, otherwise you are defeating the purpose of the csrf token:

<html>
    <head>
        <meta name="csrf_token" content="{{ csrf_token() }}">
    </head>
    <body>
        <script type="text/javascript">
            var csrfToken = $('[name="csrf_token"]').attr('content');
            
            setInterval(refreshToken, 3600000); // 1 hour 
            
            function refreshToken(){
                $.get('refresh-csrf').done(function(data){
                    csrfToken = data; // the new token
                });
            }

            setInterval(refreshToken, 3600000); // 1 hour 

        </script>
    </body>
</html>

在幼体路由中

Route::get('refresh-csrf', function(){
    return csrf_token();
});

I apologize in case of any syntax errors, haven't used jquery for long time, but i guess you get the idea

Laravel相关问答推荐

在Laravel Livewire中,如果一个输入基于另一个唯一的字段是唯一的,如何判断验证?

laravel如何在Blade 模板中将元素添加到数组

Laravel - 出于某种原因,max 打破了我的查询

如何在 Laravel 中填充以后执行的条件

Laravel Eloquent,仅 Select 存在关系的行

Laravel 5表单请求验证返回禁止错误

刚安装 Lumen 并得到 NotFoundHttpException

Laravel transformer vs resource

如何修复无效请求(不支持的 SSL 请求)

Laravel 5 - 没有重叠的任务计划不起作用

需要 Vagrant 环境或目标机器

Laravel Blade 没有额外的空格?

在 laravel 5.2 中禁用特定路由的 Web 中间件

Laravel 5 文件下载:stream() 或 download()

使用 ModelNotFoundException

在 Laravel 中将 Public 添加到assets资源路径

Eloquent - 更新集合中的所有模型

禁用Eager的关系

Laravel 5 Carbon 全局语言环境

Laravel 4 控制器模板/Blade - 正确的方法?