Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
730 views
in Technique[技术] by (71.8m points)

php - Laravel 4: Prevent multiple form submissions - CSRF Token

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...