【发布时间】:2018-08-10 04:54:30
【问题描述】:
我对 nginx 和 django-rest-framework 有一些问题。大约 24 小时以来,我一直在尝试弄清楚如何向 API 发出经过身份验证的请求。我真的很累,希望有人能帮助我。
我有以下 nginx 配置:
location / {
if ($request_method = OPTIONS ) {
add_header 'Access-Control-Allow-Origin' "*;
add_header 'Access-Control-Allow-Methods' "GET, PUT, POST, PATCH, DELETE, OPTIONS";
add_header 'Access-Control-Allow-Headers' "Authorization, 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range";
add_header 'Access-Control-Allow-Credentials' "true";
}
uwsgi_pass django;
include /path/to/your/mysite/uwsgi_params;,
}
客户端的代码如下:
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.open('POST', 'http://api/v0/api-token-auth/', true);
xhr.setRequestHeader('Authorization', 'JWT ' + getCookie("token"))
xhr.send(JSON.stringify(json));
而且我总是得到 401 Unauthorized。我不知道我还需要做什么来解决这个问题。
【问题讨论】:
-
我不确定,但也许你应该在你的配置中添加一些 CORS,检查这个github.com/OttoYiu/django-cors-headers
-
非常感谢。它对我有帮助。
-
有趣的是我什么也没做。我刚刚将此应用添加到我已安装的应用中,并将 CorsMiddleware 添加到中间件列表中。
-
很高兴它对您有所帮助,我会添加答案以便您接受它
标签: django authentication nginx django-rest-framework jwt