简体   繁体   English

在Phalcon中将CSRF保护服务与Ajax一起使用

[英]Using CSRF Protection Service with Ajax in Phalcon

I have trouble with CSRF protection component in Phalcon with Ajax. 我在使用Ajax的Phalcon中使用CSRF保护组件时遇到麻烦。

html form html表格

<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 Ajax代码

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. 首次发送Ajax请求时,Controller中的$this->security->checkToken()函数返回true。 But for the second time and later, the function returns false. 但是在第二次及以后,该函数返回false。

I think the csrfToken changes for each HTTP request caused this problem. 我认为每个HTTP请求的csrfToken更改都会导致此问题。 But how to solve it? 但是如何解决呢?

Can anyone help me? 谁能帮我?

You will need to return the new CSRF token in your AJAX success response. 您将需要在AJAX成功响应中返回新的CSRF令牌。 Then update your form field with the new token. 然后使用新令牌更新您的表单字段。

accounts/signup.action 账户/ signup.action

return json_encode((object) array(
    'output' => $original_output,
    'csrf' => (object) array('name' => $csrf_name, 'value' => $csrf_token)
));

Javascript 使用Javascript

$.ajax({
    type: 'POST',
    url: '{{ url('/accounts/signup.action') }}',
    data: postData,
    dataType: 'JSON',
    success: function(result){
        $('input#signup-csrf-token')
            .attr('name', result.csrf.name)
            .val(result.csrf.value);
        console.log(result.output);
    }
});

You should also change 你也应该改变

$('#signup-csrf-token').attr('val');

to

$('#signup-csrf-token').val();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM