Django のユーザーデータベースに対する Apache からの認証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 から直接提供する。

  • 特定のパーミッションを持つ 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 ディレクティブは、プロンプトから受け取ったユーザ名とパスワードを渡して、指定した wsgi スクリプトの check_password 関数を実行するように mod_wsgi に指示します。この例では、 WSGIAuthUserScriptdjango-admin startproject で作成される アプリケーションを定義する WSGIScriptAlias と同じです。

最後に、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 の access control mechanisms documentation に、認証の代替方法についての詳細と情報があります。

mod_wsgi と Django グループを使った認可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" グループのメンバーであることも要求するようになりました。