![使用 django 作为身份验证服务器和登录页面的 auth_request nginx 反向代理](https://linux22.com/image/791989/%E4%BD%BF%E7%94%A8%20django%20%E4%BD%9C%E4%B8%BA%E8%BA%AB%E4%BB%BD%E9%AA%8C%E8%AF%81%E6%9C%8D%E5%8A%A1%E5%99%A8%E5%92%8C%E7%99%BB%E5%BD%95%E9%A1%B5%E9%9D%A2%E7%9A%84%20auth_request%20nginx%20%E5%8F%8D%E5%90%91%E4%BB%A3%E7%90%86.png)
我有一个 NginX,其受保护位置为 192.168.56.108,我的 django 应用程序位于 192.168.56.1,
受保护位置将对在端口 8008 上运行的本地“sFlow-RT”安装进行反向代理
这是我的 nginx 默认站点配置
server {
listen 80 default_server;
listen [::]:80 default_server;
root /var/www/html;
# Add index.php to the list if you are using PHP
index index.html index.htm index.nginx-debian.html;
server_name _;
location /sflow-rt/ {
proxy_buffering off;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Prefix /sflow-rt/;
proxy_set_header Host $host;
proxy_pass http://localhost:8008/;
proxy_redirect ~^http://[^/]+(/.+)$ /sflow-rt$1;
# insert access policy below
auth_request /auth;
}
location = /auth {
internal ;
proxy_pass http://192.168.56.1:8000/xpages/authonly;
proxy_pass_request_body off;
proxy_set_header Content-Length "";
}
location / {
# First attempt to serve request as file, then
# as directory, then fall back to displaying a 404.
try_files $uri $uri/ =404;
}
}
下面是我的 django 视图,它将被“proxy_pass”调用http://192.168.56.1:8000/xpages/authonly'
class authonly(FormView):
template_name = 'auth_only.html'
form_class = auth_only_form
def get(self, request, *args, **kwargs):
if request.user.is_authenticated:
print(f'REQUEST USER: {request.user}')
return HttpResponse('authenticated',status=200)
print('Non Authenticated User')
form = self.form_class()
return render(request, self.template_name, {"form": form})
def form_valid(self, form):
print(f'Cleaned data => {form.cleaned_data}')
name = form.cleaned_data['name']
password = form.cleaned_data['password']
try :
user = authenticate(username = name, password=password)
login(self.request, user)
return HttpResponse(status=200)
except Exception as e:
print(f'Failed Auth:\n\t{traceback.format_exc()}')
return HttpResponse(status=400)
仅当用户未经身份验证时,该视图才会显示一个简单的登录屏幕。
问题是,作为“正常”的 Web 服务器,任何非错误响应都将带有 http 状态 200 .. 而 nginx auth_request 将 200 视为“可以继续”。 这样会导致登录页面永远不会显示... 因为表单 html 也带有 http 状态 200。
请告诉我如何解决这个问题