Welcome Guest, Not a member yet? Register   Sign In
ajax csrf regenerate
#1

(This post was last modified: 02-28-2022, 06:16 AM by devo.)

hii i just try to make csrf regenrate in ajax request is this the right way??
add <?php echo csrf_meta(); ?> in head tag
and in every response must include csrf_hash();
return $this->response->setJSON(['status' => true, 'message' => 'Hello World', 'csrf' => csrf_hash()]);

Code:
<script type="text/javascript">

    function csrfSafeMethod(method) {
        // these HTTP methods do not require CSRF protection
        return (/^(GET|HEAD|OPTIONS)$/.test(method));
    }

    $.ajaxSetup({
        beforeSend: function(xhr, settings) {
            if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
                xhr.setRequestHeader("<?php echo csrf_header(); ?>", $('meta[name="<?php echo csrf_header(); ?>"]').attr('content'));
            }
        }
    });

    $(document).ajaxComplete(function (event, xhr, settings) {
        if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
            let response = JSON.parse(xhr.responseText);
            $('meta[name="<?php echo csrf_header(); ?>"]').attr('content', response.csrf);
        }
       
    });
</script>
Reply
#2

Makitweb - How to Send AJAX request with CSRF token in CodeIgniter 4
What did you Try? What did you Get? What did you Expect?

Joined CodeIgniter Community 2009.  ( Skype: insitfx )
Reply
#3

(03-01-2022, 01:18 AM)InsiteFX Wrote: Makitweb - How to Send AJAX request with CSRF token in CodeIgniter 4

btw i want ask how if i make csrf regenerate to false?? are that any problem i use codeigniter 4.1.9
Reply
#4

You can read more about it here.
CodeIgniter 4 User Guide - Security - Cross-site request forgery (CSRF)
What did you Try? What did you Get? What did you Expect?

Joined CodeIgniter Community 2009.  ( Skype: insitfx )
Reply




Theme © iAndrew 2016 - Forum software by © MyBB