We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Using CSRF Protection Service with Ajax

I have trouble with CSRF protection component in Phalcon with Ajax.

html form

<form id="signup-form" onSubmit="onSignUpSubmit(); return false;">
    <input id="username" type="text" placeholder="Username" />
    <input id="password" type="password" placeholder="Password" />
    <input id="email" type="text" placeholder="Email" />
    <input id="signup-csrf-token" name="{{ security.getTokenKey() }}" val="{{ security.getToken() }}" type="hidden" />
    <button class="btn btn-primary btn-block" type="submit">Sign Up</button>
</form> <!-- #signup-form -->

Ajax code

var username    = $('#username', '#signup-form').val(),
    password    = $('#password', '#signup-form').val(),
    email       = $('#email', '#signup-form').val(),
    csrfKey     = $('#signup-csrf-token').attr('name'),
    csrfValue   = $('#signup-csrf-token').attr('val');

    var postData = {
        'username': username,
        'password': password,
        'email': email
    };
    postData[csrfKey] = csrfValue;

    $.ajax({
        type: 'POST',
        url: '{{ url('/accounts/signup.action') }}',
        data: postData,
        dataType: 'JSON',
        success: function(result){
            console.log(result);
        }
    });

When send Ajax request for the first time, the $this->security->checkToken() function in Controller returns true. But for the second time and later, the function returns false.

I think the csrfToken changes for each HTTP request caused this problem. But how to solve it?

Can anyone help me?

I solved this problem with the help of StackOverflow.