I discovered the Security Component in CakePHP helps to prevent CSRF by adding tokens as hidden values to forms.
What I was wondering is if there was anyway to prevent duplicate form submissions using this Component or some other component/helper?
In previous projects, I used a unique hash saved in a session, which is read then deleted upon submit. A repeated submit would have that same hash and an error would be produced.
thanks
I've puted onClick event that disables the button like this:
<?= $this->Form->button('Salvar', [
'value' =>'Submit',
'onClick' => 'form.submit();this.disabled=true'
])
?>
You could implement the same type of thing in Cake as you've done before.
On submit, set a session variable that marks that form as having been submitted. Make sure to put an expiry time after it (within a few seconds should do the trick). If the session variable is there when you process the form (and you're within that expiration time), then you've got a resubmit, so don't save the form data.
I'd recommend doing this within the save(..) method of your model, so you don't need to worry about adding it in multiple code locations.
There is a feature in CakePHP 2.x in the security component that allows you to choose to either use the same security token till it expires or just once. Place this in your controllers beforeFilter method:
$this->Security->csrfUseOnce = true;
Find more information here
@DoctorFox has already answered it with csrfUseOnce = true
, but this will throw you in blackholes that you still have to manage. So the complete solution for me is :
class YourAppController extends AppController {
public $helpers = array('Html', 'Form');
public $components = array('Security');
public function beforeFilter() {
$this->Security->csrfUseOnce = true;
$this->Security->blackHoleCallback = 'blackhole';
}
public function blackhole($type) {
$this->redirect(array('action' => 'index'));
}
If there is no redirection, you are still open for double form submission.
Ref : CakePHP security component
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With