沃梦达 / 编程问答 / php问题 / 正文

Laravel 4:防止多个表单提交 - CSRF Token

Laravel 4: Prevent multiple form submissions - CSRF Token(Laravel 4:防止多个表单提交 - CSRF Token)

本文介绍了Laravel 4:防止多个表单提交 - CSRF Token的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题场景:

我正在使用 Laravel 4 创建一个博客.负责创建新博客文章的表单受到 CSRF 保护 (Laravel 文档:CSRF 保护).

I'm creating a blog with Laravel 4. The form that's responsible for the creation of new blog posts is secured by the build in CSRF protection (Laravel Docs: CSRF Protection).

到目前为止一切正常,但似乎 laravel 不会在每个请求上刷新 csrf 令牌.

Everything works fine so far, but it seems that laravel does not refresh the csrf token on every request.

出现的问题是,如果用户点击浏览器的后退按钮返回到提交的表单,输入的数据仍然存在并且用户能够重新提交"表单.这可能会为垃圾邮件发送者打开大门.

The problem that occurs is that if the user hits the back button of the browser to return to the submitted form, the entered data persists and the user is able to "re-submit" the form. This might create an open door for spammers.

这通常会被 CSRF 令牌阻止,因为它会在每次请求时刷新,但 Laravel 似乎不会那样做.

Usually this is prevented by the CSRF token, as it's being refreshed on every request, but Laravel doesn't seem to do it like that.

我使用 laravel 资源控制器"方法(Laravel 文档:资源控制器)处理表单和博客文章视图.此外,我在将提交的输入存储到数据库(MySQL)之前使用 Laravel 输入验证器.

I use the laravel "Resource Controller" approach (Laravel Docs: Resource Controllers) to handle the form and blog post views. Furthermore I use Laravels input validator before storing the submitted input in the database (MySQL).


于是产生了以下想法:

  1. 以某种方式强制 Laravel 4 在每次请求时自动重新生成 csrf

  1. somehow force Laravel 4 to regenerate the csrf automatically on every request

生成另一个令牌并手动将其包含到表单中

generate another token and include it into the form manually

在用户会话(php 或数据库)中保存表单提交的时间戳,并在时间基准上限制新表单提交

save a timestamp of form submition in the users session (php or database) and throttle new form submissions on a time base

我个人更喜欢第一个想法,但不幸的是,我无法找到一种方法来强制 laravel 表现出我想要的样子,而不破坏Illuminate"本身(我想保持原样"能够在没有麻烦hoff"的情况下更新 laravel ^^).

Personally I prefer the first idea, but unfortunately I couldn't find a way of forcing laravel to behave how I want it to be, without hacking the "Illuminate" itself (which I want to keep "as is" to be able to update laravel without "hasslehoff" ^^).

你会推荐什么?

你自己是如何处理这个问题的?

推荐答案

我实际上也遇到了这个问题,因为我提交了多个帖子.您有两种选择:

I actually ran into this issue as well for multiple posts submissions. You have two options here:

1) 提交后生成新令牌:

1) Generate a new token AFTER post submission:

Session::put('_token', sha1(microtime()))

2) 发帖后重定向到确认页面:

2) Redirect AFTER post to a confirmation page:

Redirect::route('form/success')->with("data", $myData)

我最终做了第二个.

在 Jason 的评论中,最好结合使用上述两种方法

In a comment via Jason, it may be best to use the combination of both methods outlined above

这篇关于Laravel 4:防止多个表单提交 - CSRF Token的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:Laravel 4:防止多个表单提交 - CSRF Token

基础教程推荐