问题描述
在 Laravel 5 中处理过期令牌的最佳方法是什么.
What is the best way to handle expired tokens in laravel 5.
我的意思是我有一个页面,它有一些执行 ajax 请求的链接.当页面加载时它们工作正常,但是当我等待一段时间时,我收到一个 TOKEN MISMATCH 错误.
I mean I have a page and it has some links which perform ajax requests. They work fine when the page is loaded but when I wait for sometime then I get a TOKEN MISMATCH error.
现在,我必须刷新页面才能使其再次工作.但是,我不想刷新页面.我想要一些方法来刷新令牌或其他一些解决方法来修复它.
Now, I have to refresh the page to make it work again. BUT, I don't want to refresh the page. I want some way to refresh the token or some other work around to make it fix.
希望你明白我的意思.
推荐答案
2021 年更新:
你好 Stackoverflow!似乎我们几年前发布的答案引发了一些争议.
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.
由于我们的专业知识有限,我们仍然相信我们的解决方案是可行的,但为了减少疑虑,请务必仔细阅读评论部分以及Ryan 因为他们在你做出决定之前不这么认为.谢谢.
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.
2015 年的原始答案
一个解决方法,就是每隔一定时间实际获取新令牌,否则你就违背了 csrf 令牌的目的:
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>
在 Laravel 路由中
In laravel routes
Route::get('refresh-csrf', function(){
return csrf_token();
});
如有任何语法错误,我深表歉意,很久没有使用 jquery,但我想你明白了
I apologize in case of any syntax errors, haven't used jquery for long time, but i guess you get the idea
这篇关于在 Laravel 中处理过期的令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!