认证后如何获取用户名?

How to get user name after authentication?

我使用 Django 和 Apache 建立了一个网站。我有 Apache LDAP 身份验证。用户对网站进行身份验证后如何获取用户名?我想获取用户名并表示它。

所以您正在使用 Apache LDAP 身份验证。如果您使用 mod_auth_ldap,请参阅此处的文档 http://httpd.apache.org/docs/2.0/mod/mod_auth_ldap.html#frontpage。如果你使用 mod_authnz_ldap 在此处查看文档 https://httpd.apache.org/docs/2.4/mod/mod_authnz_ldap.html#exposed

文档告诉我们的是,当用户通过身份验证时,Apache 设置环境变量,可以从 CGI 脚本访问它。变量名称因您使用的版本而异。尽管 Python 使用 WSGI,您仍然应该尝试获取该变量,因为它是环境变量并且无论如何都应该可以访问。

在python中获取对环境变量的访问权限:

import os
username=os.getenv["REMOTE_USER"] #will return variable value or None
if username:
    pass
    #process username here

在此处查看有关此功能的文档:https://docs.python.org/3.5/library/os.html#os.getenv

您可以尝试在您需要用户名的 Python 代码中直接使用它。或者更好地在 Django 项目的 wsgi.py 中使用此代码,如果 username 可用,请添加特殊的 header 及其值,以便它在 Django 中可用 request 通过到 Django 视图。但请记住在添加 header 之前删除它,因此如果恶意用户伪造 header 它不会影响您的应用程序。有关这方面的更多信息,请参阅 https://docs.djangoproject.com/en/1.9/howto/deployment/wsgi/modwsgi/ and https://docs.djangoproject.com/en/1.9/howto/deployment/wsgi/apache-auth/

编辑:顺便说一句,REMOTE_USER 有一个 "How-to":https://docs.djangoproject.com/en/1.9/howto/auth-remote-user/

编辑:如果您对使用 Apache 执行身份验证没有任何要求,您可能希望直接在 Django 应用程序中执行身份验证,请参阅:https://pythonhosted.org/django-auth-ldap/ and in example https://djangosnippets.org/snippets/901/