django nginx 在生产中通过 http 获取 csrf 验证错误 [英] django nginx getting csrf verification error in production over http
问题描述
我刚刚使用 nginx 在 AWS 上部署了我的 django 项目.一切正常,除了当我尝试发出任何 POST 请求(仅通过 http)时,出现错误:
I've just deployed my django project on AWS with nginx. Everything works well except for when when I try to make any POST requests (over just http), I get the error:
"禁止 (403)CSRF 验证失败.请求已中止."
"Forbidden (403) CSRF verification failed. Request aborted."
如果我直接使用 Django 运行我的服务器,CSRF 验证会起作用,这让我认为我没有正确设置我的 nginx.conf
.
有人可以就如何配置 nginx 以使用 csrf 提供一些指导吗?
这是我当前的配置:
CSRF verification works if I run my server directly using Django which leads me to think that I did not set up my nginx.conf
correctly.
Can someone give some guidance as to how I can configure nginx to work with csrf?
Here's my current config:
#nginx.conf
upstream django {
# connect to this socket
server unix:///tmp/uwsgi.sock; # for a file socket
#server 127.0.0.1:8001; # for a web port socket
}
server {
# the port your site will be served on
listen 80;
root /opt/apps/site-env/site;
# the domain name it will serve for
server_name mysite.org
charset utf-8;
#Max upload size
client_max_body_size 75M; # adjust to taste
location /media {
alias /opt/apps/site-env/site/media;
}
location /static {
alias /opt/apps/site-env/site/static;
}
location / {
uwsgi_pass django;
include /etc/nginx/uwsgi_params;
proxy_pass_header X-CSRFToken;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto http;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header HOST $http_host;
proxy_set_header X-NginX-Proxy true;
}
}
我还在 django 设置中关闭了 SESSION_COOKIE_SECURE
和 CSRF_COOKIE_SECURE
.
I've also turned off both SESSION_COOKIE_SECURE
and CSRF_COOKIE_SECURE
in my django settings.
谢谢
推荐答案
当您从 javascript 发布帖子时,请确保将 settings.CSRF_COOKIE_HTTPONLY
设置为 False
When you're issuing posts from javascript, ensure that settings.CSRF_COOKIE_HTTPONLY
is set to False
来自 [1] 的片段:是否在 CSRF cookie 上使用 HttpOnly 标志.如果设置为 True,客户端 JavaScript 将无法访问 CSRF cookie."
Snippet from [1]: "Whether to use HttpOnly flag on the CSRF cookie. If this is set to True, client-side JavaScript will not to be able to access the CSRF cookie."
[1] https://docs.djangoproject.com/en/2.0/ref/settings/#csrf-cookie-httponly
这篇关于django nginx 在生产中通过 http 获取 csrf 验证错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!