0

So I planned to implement CSRF in my website and set what's needed which I think I set correctly but still having issue with ajax submit form.

$config['csrf_protection'] = TRUE;
$config['csrf_token_name'] = 'csrf_token_name';
$config['csrf_cookie_name'] = 'csrf_cookie_name';
$config['csrf_expire'] = 7200;
$config['csrf_regenerate'] = FALSE;
$config['csrf_exclude_uris'] = array();

This is what I have in my config, where I set $config['csrf_regenerate'] = FALSE; to prevent the regeneration on every submission (based on this discussion Ajax CSRF 403 forbidden codeigniter).

And my form, instead of using html form tag, I use form_open() and form_close().

Ajax submit form :

$('#formData').on('submit', function(e){
    e.preventDefault();
    var formData = new FormData($(this)[0]);

    $.ajax({
        type: 'post',
        cache : false,
        processData: false,
        dataType: 'json',
        url: 'example.com.sg/login/verify',
        data: formData,
        success: function (res) {
            if(res.status == true){
                window.location.href = res.redirect;
            }
        },
        error: function(err){
            console.log(err.responseText)
        }
    });
})

PHP function

public function verify(){
    $this->form_validation
        ->set_rules('email', 'Email', 'trim|required|valid_email')
        ->set_rules('password', 'Password', 'trim|required');

    if($this->form_validation->run() == true){
        // do email and password verification
        echo json_encode([ 'status' => true, 'redirect' => base_url('dashboard') ]);
    } else {
        $this->returnFormError($this->form_validation->error_array());
    }
}

If I change the ajax type to get it works but not post. If viewing the code from console, my form has this csrf token included in hidden input.

Leon
  • 329
  • 2
  • 3
  • 15
  • its a bit less information i think - take a look @your browsers console (in chrome its the network tab) - this post should help you https://stackoverflow.com/questions/15603561/how-can-i-debug-a-http-post-in-chrome - and analyze your data in the headers tab - if you dont see the csrf information there - something went wrong – Atural Apr 29 '20 at 10:26
  • @sintakonte sorry for the late reply. I have checked from console at network tab at header section and I can see the csrf information at there. – Leon May 08 '20 at 03:28

1 Answers1

0

// in config.php $config['encryption_key'] = 'some key'; update this first

rajratna maitry
  • 378
  • 3
  • 9