How to authenticate using REMOTE_USERLink to this heading

This document describes how to make use of external authentication sources (where the web server sets the REMOTE_USER environment variable) in your Django applications. This type of authentication solution is typically seen on intranet sites, with single sign-on solutions such as IIS and Integrated Windows Authentication or Apache and mod_authnz_ldap, CAS, Cosign, WebAuth, mod_auth_sspi, etc.

When the web server takes care of authentication it typically sets the REMOTE_USER environment variable for use in the underlying application. In Django, REMOTE_USER is made available in the request.META attribute. Django can be configured to make use of the REMOTE_USER value using the RemoteUserMiddleware or PersistentRemoteUserMiddleware, and RemoteUserBackend classes found in django.contrib.auth.

設定Link to this heading

最初に次のように MIDDLEWARE 設定に django.contrib.auth.middleware.RemoteUserMiddleware を加える必要があります。これは django.contrib.auth.middleware.AuthenticationMiddleware後に 追加してください:

Code
MIDDLEWARE = [
    '...',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.RemoteUserMiddleware',
    '...',
]

続いて、AUTHENTICATION_BACKENDS 設定の ModelBackendRemoteUserBackend に変更します:

Code
AUTHENTICATION_BACKENDS = [
    'django.contrib.auth.backends.RemoteUserBackend',
]

この設定を行うと RemoteUserMiddlewarerequest.META['REMOTE_USER'] 内の username を検索し、 RemoteUserBackend を使用したユーザーの認証と自動ログインを行います。

この特定の設定は、デフォルトの ModelBackend による認証を無効にすることに注意してください。つまり、 REMOTE_USER の値が設定されていなければ、Django の admin interface を使ったとしても、ユーザーはログインすることができないということです。 REMOTE_USER が存在しない場合のフォールバックとして AUTHENTICATION_BACKENDS のリストに 'django.contrib.auth.backends.ModelBackend' を追加しておけば、この問題は解決できます。

contrib.admin 画面や createsuperuser 管理コマンドなどの、Django のユーザ管理機能はリモートユーザを統合管理しません。これらのインタフェースは AUTHENTICATION_BACKENDS の設定にかかわらず、データベース中のユーザだけを管理します。

認証メカニズムが REMOTE_USER 以外のカスタム HTTP ヘッダを使っている場合には、以下の例のように RemoteUserMiddleware をサブクラス化して、クラスの header 属性を適切な request.META のキー名に設定してください:

Code
from django.contrib.auth.middleware import RemoteUserMiddleware

class CustomHeaderMiddleware(RemoteUserMiddleware):
    header = 'HTTP_AUTHUSER'

認証メカニズムをより細かく制御したければ、 RemoteUserBackend を継承する独自の認証バックエンドを作成し、属性やメソッドをいくつかオーバライドしてください。

ログインページでのみ REMOTE_USER を使用するLink to this heading

RemoteUserMiddleware 認証ミドルウェアは、 HTTP リクエストヘッダーの REMOTE_USER が認証されたリクエストに存在していることを仮定しています。これが htpasswd、または同様のメカニズムを備えた Basic 認証なら、妥当で実用的かもしれませんが、ネゴシエート(GSSAPI/ケルベロス)や他の資源を利用した認証メソッドでは、フロントエンド HTTP サーバの認証では、通常、ひとつもしくはいくつかのログイン URL のみ設置します。そして、認証が成功した後、アプリケーションは認証されたセッションそれ自体を維持しようとします。

PersistentRemoteUserMiddleware は、この使用事例の補助を提供する。これは、はっきりとユーザーにログアウトされるまで、認証されたセッションを維持しようとする。このクラスは、このドキュメントの上にある RemoteUserMiddleware の当座の代替として使うことができる。