我有一个 ajax
函数,可以触发从我的数据库中删除条目.
I have an ajax
function that triggers an entry deletion from my database.
我需要为此做 CSRF
验证.我该怎么做?
I need to do CSRF
validation for the same. How can I do that?
我将 CSRF cookie
与我的 post 请求一起发送,但是 Yii 2.0
没有验证它,任何通过 ajax 传递的输入都到达了服务器.
I am sending the CSRF cookie
along with my post request, but Yii 2.0
is not validating it and any input that is passed through ajax is reaching the server.
如何对ajax请求进行CSRF
验证.
How do I do CSRF
validation for ajax requests.
是否需要手动设置cookie并检查?
Whether we need to manually set cookie and check?
您无需手动设置 cookie.
You don't need to manually set cookie.
如果您使用 jQuery,CSRF 令牌将自动发送.
If you are using jQuery CSRF token will be sent automatically.
例如对于 AngularJS,您可以手动添加它以请求这样的参数:
For example for AngularJS you can add it manually to request params like that:
yii.getCsrfParam(): yii.getCsrfToken()
确保你包含了 YiiAsset
.
否则你可以从元标记中检索它们(这基本上就是这两种方法所做的):
Otherwise you can retrieve them from meta tags (that's basically what these two methods do):
$('meta[name=csrf-param]').prop('content'): $('meta[name=csrf-token]').prop('content')
另请注意,要启用 CSRF 验证,Controller
和 Request
的属性 enableCsrfValidation
必须设置为 true
.
Also note that for enabling CSRF validation both Controller
's and Request
's property enableCsrfValidation
property must be set to true
.
更新:
另一个需要了解的重要事项:
Another important thing to understand:
CSRF 令牌将仅在以下方法上进行验证:GET
、HEAD
、OPTIONS
.
CSRF token will be validated only on this methods: GET
, HEAD
, OPTIONS
.
还要确保在主布局中有 <?= Html::csrfMetaTags ?>
.
Also make sure you have <?= Html::csrfMetaTags ?>
in main layout.
这篇关于针对 AJAX 请求的 Yii 2.0 CSRF 验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!