0

I have developed a project that is quite big, I was thinking in improving security by saving a token in Session variable and sending that token in each form to check if it is correct to prevent from CSRF attacks.

The thing is that the project has many forms and it could be painful and take a lot of time to go through each form in order to add the token in a hidden input.

So I was asking myself, is there any easy way to add that hidden value to each form without having to go through each form? Maybe using jquery, I could localize each form inside the page to add a hidden input, then add a general $_POST/$_GET function to check for any request if token is correct.

This is an idea, but probably there may be another simple and better way. Is there any simple, fast and decent way to do so? What would be the best approach in this situation (preparing CSRF attack prevention after project has been developed). As far as I know the best way to prevent from CSR attacks is using token variables, is there maybe another decent way to do so without having to use a token and go through each form?

1 Answers1

0

See here: Automatically insert CSRF token in all forms with JQuery.

You could add some code to a function, inline in a <script> tag as demonstrated:

jQuery(document).ready(function() {
  jQuery("form").each(function() {
    var tokenElement = jQuery(document.createElement('input'));
    tokenElement.attr('type', 'hidden');
    tokenElement.attr('name', 'token');
    tokenElement.val(<?= $token ?>);
    jQuery(this).append(tokenElement);
  });
});

This will automatically add the server side $token to be included as a hidden form field for each <form> element.

If you want to achieve this without any server side processing, with the added benefit that all the above code could be included in a .js file, you could store the token in a cookie and simply access this value client side (using COOKIE plugin):

tokenElement.val($.cookie("csrftoken"));
Community
  • 1
  • 1
SilverlightFox
  • 32,436
  • 11
  • 76
  • 145