用户未登录时如何使用AJAX和CakePHP 3检查CSRF令牌? [英] How to check CSRF token using AJAX and CakePHP 3 when user is not logged in?

查看:93
本文介绍了用户未登录时如何使用AJAX和CakePHP 3检查CSRF令牌?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我启用了网站,并进入了人们并不总是友善的公共领域。我刚刚开始学习CSRF,并看到了我的Cakephp 3网站上线时需要的东西。 如此处所示!

So I made my site live and I am entering into the public realm where people aren't always nice. I just started learning about CSRF and saw that it was something I needed when I made my cakephp 3 site live. As seen here!

我向我的站点添加了csrf组件和安全组件,但是我有1个主要问题。现在,当用户想要注册时,他们不能注册。我对条带使用自定义表单来发送付款,但还将使用ajax的用户添加到我的数据库中。首先添加用户,然后处理付款,并将订单也保存到数据库中。

I added the csrf component and the security component to my site, but I have 1 major problem. Now, when users want to sign up they can't. I use a custom form for stripe to send payment, but also add a user using ajax to my database. The user gets added first and then the payment is processed and saves the order to the database as well.

根据条带文档单击提交按钮后,我将令牌以隐藏值添加到表单中,并且可以不禁要注意,我的新安全性不允许发生这种情况。

According to stripe docs I add the token in a hidden value to the form after I click the submit button and can't help but notice that my new security is not allowing this to happen.

由于我使用ajax将帖子数据发送到我的用户控制器并在提交时添加了表单输入,

Since I am using ajax to send the post data to my users controller and adding a form input on submit,

如何在不禁用所涉及操作的安全性的情况下检查csrf令牌并确保不存在安全性泄漏?

How do I check the csrf token and make sure there isn't a security leak without disabling the security for the actions involved?

由于在Cakephp 3中似乎缺少执行此操作的示例,因此将不胜感激。自cakephp 3 automagic以来,一切工作原理如何将令牌添加到表单和cookie。我不确定如何/在哪里/要检查什么。

An example of how this is to be done would be greatly appreciated since examples seem to be lacking for doing this in cakephp 3. It is also hard for me to figure out how everything works since the cakephp 3 automagic adds the tokens to the forms and cookie. I am unsure how/where/what to check.

推荐答案

通过 X-CSRF-Token ,在Ajax请求中使用 beforeSend 参数,并定义Cookie的 csrfToken 值。

For pass X-CSRF-Token, use beforeSend parameter in your Ajax request, and define csrfToken value of cookie.

$.ajax({
    url: '/foo/bar',
    type: 'POST',
    dataType: 'HTML',
    data: data,
    beforeSend: function(xhr){
        xhr.setRequestHeader('X-CSRF-Token', csrfToken);
    },
})
.done(function(data) {
    alert('done !');
});

这篇关于用户未登录时如何使用AJAX和CakePHP 3检查CSRF令牌?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆