如何从 Apache 对 Django 的用户数据库进行认证Link to this heading

Since keeping multiple authentication databases in sync is a common problem when dealing with Apache, you can configure Apache to authenticate against Django's authentication system directly. This requires Apache version >= 2.2 and mod_wsgi >= 2.0. For example, you could:

  • 仅为已授权的用户直接从 Apache 提供 static/media 文件。

  • 仅为有特定权限的 Django 用户提供 Subversion 仓库访问。

  • 允许某些用户连接到 mod_dav 创建的 WebDAV 共享。

mod_wsgi 进行授权认证Link to this heading

确保 mod_wsgi 已经安装并激活,并且你已经按照步骤设置了 Apache 的 mod_wsgi

然后,编辑 Apache 配置,添加只允许授权用户查看的位置:

Apache
WSGIScriptAlias / /path/to/mysite.com/mysite/wsgi.py
WSGIPythonPath /path/to/mysite.com

WSGIProcessGroup %{GLOBAL}
WSGIApplicationGroup %{GLOBAL}

<Location "/secret">
    AuthType Basic
    AuthName "Top Secret"
    Require valid-user
    AuthBasicProvider wsgi
    WSGIAuthUserScript /path/to/mysite.com/mysite/wsgi.py
</Location>

WSGIAuthUserScript 指令告诉 mod_wsgi 在指定 wsgi 脚本中执行 check_password 函数,并传递从提示符获取的用户名和密码。在本例中, WSGIAuthUserScriptWSGIScriptAlias 一样,后者 由 django-admin startproject 创建,定义了应用。

最后,编辑 WSGI 脚本 mysite.wsgi,通过导入 check_password 函数,将 Apache 的认证授权机制接续在你站点的授权机制之后:

Code
import os

os.environ["DJANGO_SETTINGS_MODULE"] = "mysite.settings"

from django.contrib.auth.handlers.modwsgi import check_password

from django.core.handlers.wsgi import WSGIHandler

application = WSGIHandler()

/secret/ 开头的请求现在会要求用户认证。

mod_wsgi 可达性控制机制文档 提供了其它授权机制和方法的更多细节和信息。

利用 mod_wsgi 和 Django 用户组(groups)进行授权Link to this heading

mod_wsgi 也提供了将组成员限制至特定路径的功能。

在本例中,Apache 配置应该看起来像这样:

Apache
WSGIScriptAlias / /path/to/mysite.com/mysite/wsgi.py

WSGIProcessGroup %{GLOBAL}
WSGIApplicationGroup %{GLOBAL}

<Location "/secret">
    AuthType Basic
    AuthName "Top Secret"
    AuthBasicProvider wsgi
    WSGIAuthUserScript /path/to/mysite.com/mysite/wsgi.py
    WSGIAuthGroupScript /path/to/mysite.com/mysite/wsgi.py
    Require group secret-agents
    Require valid-user
</Location>

要支持 WSGIAuthGroupScript 指令,同样的 WSGI 脚本 mysite.wsgi 必须也导入 groups_for_user 函数,函数会返回用户所属用户组的列表。

Python
from django.contrib.auth.handlers.modwsgi import check_password, groups_for_user

/secret 的请求现在也会要求用户是 "secret-agents" 用户组的成员。