Regenerate CRSF token codeigniter on submit Ajax

后端 未结 5 580
遥遥无期
遥遥无期 2021-01-07 04:46

Hi I am looking for the process of regeneration of csrf token in codeigniter when ever a form is submitted using ajax. I want the token to be regenerated without page refres

5条回答
  •  天涯浪人
    2021-01-07 05:16

    There are two solutions I use at different times depending on the situation.

    1. Slightly messy way but recommended

    Get the token name and hash value in your controller and set it somewhere on your page as a data field (wherever you choose). For instance

     // get the data and pass it to your view
     $token_name = $this->security->get_csrf_token_name();
     $token_hash = $this->security->get_csrf_hash();
    
     // in your view file, load it into a div for instance
     

    Now in your js ajax code, you can just read the data values in "my_div" to get the right data for your ajax call.

    It is made much easier if you have a genuine form on your page, in which case rather than using some div, just do not use form_open on the form, but instead create the hidden form field yourself, so you can read it easily via js.

     
    

    This is the important bit: Of course after sending post data, you need to refresh the token hash value (in your form input field or a div data, however you have chosen to do it). Write a js function called 'refresh_csrf_data' and use 'GET' to get the data and update the fields. This function can then be called whenever you have done an ajax post.

    So every ajax call reads the token data, does the call, then refreshes the token data ready for the next call.

    2. Easy but less secure

    Alternatively, you can disable CSRF for your ajax calls by using the

     $config['csrf_exclude_uris'] = array('controller/method');
    

    in the config file for CSRF settings.

    3. Even easier but also less secure and I do not use it Finally, you could turn off regenerating CSRF hash on every submission

     $config['csrf_regenerate'] = FALSE;
    

    But, do so with caution. This can open you up to certain types of attacks.

    The answer that is best for you depends entirely on the type of page, the usage, if users are logged in at the time or not, is it mission critical stuff or minor stuff, is it financial etc.

    Nothing is entirely secure, so it is a compromise sometimes. Personally I would do it with CSRF on full regenerate, no exceptions in the URI's, and reload the token and hash data whenever I needed to. It seems complicated and it is to explain, but once you have done it once, it is genuinely easy to do again and again whenever you need it, and your site will be far more secure than simply avoiding the issue with the other options.

提交回复
热议问题