Django:未在iframe中设置CSRF Coo​​kie-无需csrf豁免的解决方法 [英] Django: CSRF Cookie not set in iframe -- workaround without csrf exempt

查看:109
本文介绍了Django:未在iframe中设置CSRF Coo​​kie-无需csrf豁免的解决方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的项目是在django应用程序中已知并已注册的多个第三方站点上部署iframe.

My project is deploying iframes on several 3rd party sites, that are all known and registered within the django application.

在这些iframe中,用户可以触发一些ajax形式的事件.直接打开站点,一切正常.如果我打开包含iframe的第3方网站,则django在触发ajax事件(403)后抛出错误,说CSRF失败.

In these iframes, users can trigger some ajax-form events. Opening the site directly, everything works fine. If I open the 3rd party site, containing the iframe, django is throwing an error after firing the ajax event (403), saying that CSRF failed.

我使用了在HTML中设置的{%csrf_token%}的形式.但是,通过iframe调用网站时,它不会设置相应的cookie(使用浏览器中的检查模式可以找到两者).

In the form I used {% csrf_token %} which is set in the html. However it does not set the corresponding cookie, when calling the site through the iframe (found out both using inspection mode in browser).

我确实知道我可以使用装饰器 @csrf_exempt ,但这将禁用csrf保护,这是我不想做的.

I do know that I could use a decorator @csrf_exempt, but that will disable csrf-protection all in one, which I don´t want to do.

所以我的问题是:

  1. 当整个页面通过iframe加载时,django为什么不设置CSRF Coo​​kie?
  2. 是否可以让django设置cookie,还是只能从csrf中排除已知的URL?
  3. 有没有我看不见的方式?

非常感谢您的宝贵时间!:)

Thanks a lot for your time! :)

推荐答案

这是我在settings.py文件中所做的更改,以实现类似的工作:

This is what I changed in my settings.py file to get something similar working:

X_FRAME_OPTIONS = 'ALLOW-FROM example.com'
CSRF_TRUSTED_ORIGINS = ['example.com']
CSRF_COOKIE_SAMESITE = None

example.com 是将iframe插入其中的域.最后一个选项是在Django中才刚刚引入的,因此根据您的版本,可能没有必要.

Where example.com is the domain that you insert the iframe into. The last option was only introduced quite recently in Django, so depending on your version it might not be necessary.

这篇关于Django:未在iframe中设置CSRF Coo​​kie-无需csrf豁免的解决方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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