views:

31

answers:

1

Using CakePHP 1.3, I have a (working) form that has dynamically created form fields (via Javascript). Everything works great, multiple models are saved via saveAll(), and it's just beautiful.

But, I get black-holed to a 404 whenever I enable the Security component (hoping to get some of the auto-magic CSRF protection).

I understand that this may be (probably is!) caused by the dynamically created form fields, as mentioned in the docs.

Is there a way to get them to play nicely together?

+1  A: 

You can't have your Cake and eat it, too. (Cha-ching!)

CSRF protection means precisely that only a certain list of form fields is allowed to be submitted. This list is decided upon and fixed at the time the form is created. You can't be CSRF protected and dynamically alter the fields in the form.

There are two solutions:
If the number and names of the dynamically created fields are limited, create them all in the form and hide them using CSS, then show them using Javascript. This way you're not dynamically creating the fields, but are only dynamically showing them.
If that doesn't work, you can either whitelist the fields using the $disabledFields option (again, only if their names are known in advance) or disable CSRF altogether with the $validatePost option.

deceze
@deceze do you regularly use the security component? Seems to me that it's probably a bit of overkill in the most general case. Especially while developing. Do you see it as reasonable to build an app without it included, then just turn it on for production?
Travis Leleu
So for the classic "hash for session, put hash in form, check hash matches session on form post" -- if I wanted slightly-more-lax security than what Cake provides by default -- I need to fiddle with the session and do it myself. Right? Thanks!
anonymous coward
@Travis I'd say if there's no reason *not* to use it, you should use it. If it does cause more problems than it solves though, it's not absolutely necessary. It depends on how much security you need in your app, the no-random-POSTs-from-strangers aspect of CSRF may be crucial to your app. The no-fiddling-with-form-fields aspect can be mostly replicated by careful coding and using the `$fieldlist` option of `Model::save()`. The SecurityComponent is nice for quickly setting up HTTP Basic authentication when you need it.
deceze
@anon Yes, should be easy enough to replicate yourself, if it's less of a hassle to go this way than to tone down the SecurityComponent.
deceze
@deceze thanks again for the background info. I just remember trying it when I was new to Cake, and remember having issues that were solved by turning it off. I'll have to give it a shot again.
Travis Leleu