Laravel 4: Prevent multiple form submissions - CSRF Token

旧城冷巷雨未停 提交于 2019-12-18 03:01:26

问题


Problem scenario:

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).

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.

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.

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).


So the following ideas came up:

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

  2. generate another token and include it into the form manually

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

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" ^^).

What would you recommend?

How did you handle the problem yourself?


回答1:


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

1) Generate a new token AFTER post submission:

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

2) Redirect AFTER post to a confirmation page:

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

I ended up doing the second.

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



来源:https://stackoverflow.com/questions/17239586/laravel-4-prevent-multiple-form-submissions-csrf-token

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!