【问题标题】:(Django REST Framework) Basic authentication doesn't work when app is served through NGINX(Django REST 框架)通过 NGINX 提供应用程序时,基本身份验证不起作用
【发布时间】:2021-08-07 00:13:30
【问题描述】:

我正在构建一个 API,我终于让它通过 Gunicorn 和 NGINX 提供服务。 Nginx 将传入请求代理到绑定到 Gunicorn 的套接字。问题是这样的:

当我尝试通过运行 'gunicorn 命令或使用 Django 中的内置 'runserver' 命令直接访问 API 并在 settings.py 文件中将 Django REST Framework 的 BasicAuthentication 配置为默认身份验证类时,一切工作正常。每次我尝试访问端点时,它都会要求我提供有效的用户名/密码组合,就像您期望的那样。

但是,当我尝试通过 NGINX 访问 API 时,它有一个 proxy_pass 配置到 Gunicorn 绑定到的 unix 套接字,BasicAuthentication 不再起作用。无需提供用户名和密码即可批准所有请求。

我知道应该避免基本身份验证,但这是我正在从事的项目的要求。有谁知道为什么会发生这种情况以及如何解决这个问题?

settings.py:

REST_FRAMEWORK = {

'DEFAULT_AUTHENTICATION_CLASSES': (
    'rest_framework.authentication.BasicAuthentication',
),
}

nginx.conf:

http {
log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                  '$status $body_bytes_sent "$http_referer" '
                  '"$http_user_agent" "$http_x_forwarded_for"';

access_log  /var/log/nginx/access.log  main;

sendfile            on;
tcp_nopush          on;
tcp_nodelay         on;
keepalive_timeout   65;
types_hash_max_size 2048;

include             /etc/nginx/mime.types;
default_type        application/octet-stream;

# Load modular configuration files from the /etc/nginx/conf.d directory.
# See http://nginx.org/en/docs/ngx_core_module.html#include
# for more information.
include /etc/nginx/conf.d/*.conf;


upstream *** {

    server unix:/***/***/***/***/***/***/***.sock
    fail_timeout=0;
}

server {

server_name     <server-name>;

    satisfy         all;

    allow           <IP-address>
    deny            all;


    # location = /favicon.ico {access_log off; log_not_found off;}

    location /static/ {
       autoindex on;
       alias ../static/;
    }

location / {
       proxy_set_header Host $http_host;
       proxy_set_header X-Real-IP $remote_addr;
       proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
       proxy_set_header X-Forwarded-Proto $scheme;
       proxy_pass http://<upstream>;
    }


listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/***/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/***/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

}

【问题讨论】:

  • 你有什么错误吗?
  • @SırrıKırımlıoğlu 不,我收到 200 作为回应。还检查了 NGINX 的错误日志,但也没有看到。

标签: django authentication nginx django-rest-framework gunicorn


【解决方案1】:

好的,所以我设法自己解决了。我不知道是什么原因,因为我在使用 Gunicorn 之前也遇到过同样的问题,但重新启动它以某种方式解决了它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-11
    • 2015-08-16
    • 2020-08-21
    • 1970-01-01
    • 2019-02-20
    相关资源
    最近更新 更多