将csrf令牌存储在meta标签中是一种好习惯吗? [英] Is it a good practice to store the csrf token in meta tag?

查看:786
本文介绍了将csrf令牌存储在meta标签中是一种好习惯吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在不使用表单的情况下发出POST请求并希望防止CSRF攻击,我可以做的就是在meta标签中设置csrf-token,并在触发请求时将其放回标头.这是个好习惯吗?

If I make a POST request without using form and want to prevent CSRF attack, what I can do is to set the csrf-token in meta tag and put it back to the header when the request is triggered. Is it a good practice?

<meta name="csrf-token" content="xxx">

例如使用JQuery,通过标头将令牌放回原位

Put the token back via the header, using JQuery for example:

$.ajaxSetup({
   headers: {
      'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
   }
});

推荐答案

是的,这是一个好习惯.如果您使用的是Ajax,我认为这是最干净的解决方案.

Yes this is good practice. If you are using ajax I think this is the cleanest solution.

您也可以将令牌放入表单中(提交整个表单更方便),但是如果您使用的是Ajax,则只需将其放到可以抓取令牌的地方即可.

You could also put the token inside of the form (which is more convenient if submitting the whole form), but if you are using ajax, it just needs to go somewhere that you can grab it.

在隐藏字段或meta标签中都是很好的选择.

in a hidden field, or in a meta tag are both very good options.

这篇关于将csrf令牌存储在meta标签中是一种好习惯吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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