addRequiredToken - how does it work?

Permalink
I've tried endless ways to implement this feature in one of my blocks. (Yes, I'm aware that blocks already have a token attached to them, but I'd like to learn how to do it manually).

My questions: 1. How does one go about including a token in their form to protect against CSRF attacks? 2. Is there a token included automatically in an AJAX call?

 
Temposaur replied on at Permalink Best Answer Reply
Temposaur
You can use custom "tokens" like this:

form
$validation = Loader::helper('validation/token');
$edittoken = $validation->generate('mySaveForm' );
echo '<input name="myEditorToken" type="hidden" value="'.$edittoken.'" />



form-controller
$validation= Loader::helper('validation/token');
if ($validation->validate('mySaveForm',$_REQUEST["myEditorToken"])){
   // valid
}else{
   // invalid
}


When You use ajax-functions form-fields are normally submitted also, so there's no need to change anything (excluding ajax html-outputting).
Martificiam replied on at Permalink Reply
Thanks! Out of the three ways to do it that I've discovered, this one finally works. One more question, just for clarification - all forms in concrete5 use a token anyway, so I don't need to do all this, right? I have several forms in my blocks which are submitted using an ajax call, here's an example:

function postFormSubmission(){
   tinyMCE.triggerSave();
   var data = $('form.submission-form').serialize();
   $('.popup .content #loader-wrapper').show();
   $.post(
      '<?php echo str_replace("&","&",$this->action('add')) ?>', 
      data,
      function(data) {
         showSubmissionErrors(data);
         $('.popup .content #loader-wrapper').hide();
      },
      'json'
   );
}


Will the form submitted using the function above have a token?
Temposaur replied on at Permalink Reply
Temposaur
If the form has token, then yes, jQuery's $.post will submit token also.

There are many ways to create (html) forms on C5. The best way is to to be sure about token, is to use somekind of Webdeveloper tool (Google Chrome press F12 and check if token parameter exists).
JohntheFish replied on at Permalink Reply
JohntheFish
Martificiam replied on at Permalink Reply
I've already tried this, it didn't work.