REMOTE_USER 从 nginx 到 Django 的 ProxyPass 问题

Trouble with ProxyPass of REMOTE_USER from nginx to Django

我有一个配置了客户端证书身份验证的 nginx 网络服务器。一旦通过身份验证,我将请求代理到 uWSGI Django 应用程序服务器。我已经将我的 Django 应用程序设置为使用 REMOTE_USER (https://docs.djangoproject.com/en/3.1/howto/auth-remote-user/) 执行身份验证,但是它似乎不起作用,因为我收到“'AnonymousUser' 对象不可迭代”来自 Django 的错误。

我假设我的 nginx 配置中遗漏了一些东西:

server {
  listen 80;
  server_name my.website.net;
  return 301 https://$server_name$request_uri;
}
server {
  listen 443 ssl;
  ssl_certificate /etc/letsencrypt/live/my.website.net/fullchain.pem;
  ssl_certificate_key /etc/letsencrypt/live/my.website.net/privkey.pem;
  ssl_verify_client on;
  ssl_verify_depth 2;
  ssl_client_certificate /etc/nginx/ssl/cas.pem;
  proxy_set_header X-SSL-Client-Serial $ssl_client_serial;
  proxy_set_header X-SSL-Client-Verify $ssl_client_verify;
  proxy_set_header X-SSL-Client-S-DN   $ssl_client_s_dn;
  proxy_set_header X-Remote-User $remote_user;
  proxy_set_header REMOTE_USER $remote_user;

  location / {
    root /var/www/my.website.net;
    index index.html index.htm;
  }

  location /django {
    proxy_set_header Host 10.101.10.228;
    proxy_http_version 1.1;
    proxy_set_header Connection "Keep-Alive";
    proxy_set_header Proxy-Connection "Keep-Alive";

    proxy_pass http://10.101.10.228:8000/webapp;
    proxy_redirect http://10.101.10.228/django/ https://my.website.net/django/;

  }

}

我也尝试过使用 nginx uwsgi_* 指令,但没有成功:

upstream django {
  server 10.101.10.228:8000;
}
location /django {
  include         uwsgi_params;
  uwsgi_pass django;
  uwsgi_param SCRIPT_NAME /webapp;
  uwsgi_param REMOTE_USER $remote_user;
  uwsgi_param X-REMOTE-USER $remote_user;
}

有没有什么东西好像不见了?

使用客户端 DN 作为用户名的 $remote_user nginx variable is being populated only for HTTP Basic Authentication. You can rely on $ssl_client_s_dn 变量:

proxy_set_header Remote_User $ssl_client_s_dn;

uwsgi_param REMOTE_USER $ssl_client_s_dn;

您可以使用 map 块从客户端 DN 中仅检索某些特定字段,例如仅获取 CN(规范名称):

map $ssl_client_s_dn $remote_user_cn {
    ~,CN=(?<CN>[^,]+) $CN;
}

然后使用 $remote_user_cn 变量作为用户名。