暴露会话的CSRF保护令牌是否安全? [英] Is exposing a session's CSRF-protection token safe?
问题描述
Django附带了 CSRF保护中间件,其中生成一个唯一的每会话令牌用于表单。它扫描所有传入的 POST
请求的正确令牌,如果令牌丢失或无效,则拒绝该请求。
Django comes with CSRF protection middleware, which generates a unique per-session token for use in forms. It scans all incoming POST
requests for the correct token, and rejects the request if the token is missing or invalid.
我想使用AJAX进行一些POST请求,但是所述请求没有可用的CSRF令牌。这些页面没有要挂钩的< form>
元素,我宁可不要将标记插入到隐藏值中。我想,一个很好的方式是公开一个像$ / get-csrf-token /
这样的邮票,以返回用户的令牌,依靠浏览器的跨站点脚本规则来防止敌对网站请求它。
I'd like to use AJAX for some POST requests, but said requests don't have the CSRF token availabnle. The pages have no <form>
elements to hook into and I'd rather not muddy up the markup inserting the token as a hidden value. I figure a good way to do this is to expose a vew like /get-csrf-token/
to return the user's token, relying on browser's cross-site scripting rules to prevent hostile sites from requesting it.
这是一个好主意吗?有没有更好的方法来保护免受CSRF攻击,同时仍然允许AJAX请求?
Is this a good idea? Are there better ways to protect against CSRF attacks while still allowing AJAX requests?
推荐答案
如果你知道你将需要CSRF令牌用于AJAX请求,您可以随时将其嵌入HTML中;那么你可以通过Javascript通过遍历DOM找到它。这样,您仍然可以访问令牌,但是您不会通过API暴露它。
If you know you're going to need the CSRF token for AJAX requests, you can always embed it in the HTML somewhere; then you can find it through Javascript by traversing the DOM. This way, you'll still have access to the token, but you're not exposing it via an API.
换句话说:通过Django的模板 - 不通过URL调度程序。这样更安全。
To put it another way: do it through Django's templates -- not through the URL dispatcher. It's much more secure this way.
这篇关于暴露会话的CSRF保护令牌是否安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!