How to authenticate using REMOTE_USERLink para este cabeçalho

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.

ConfiguraçãoLink para este cabeçalho

Primeiro você deve adicionar django.contrib.auth.middleware.RemoteUserMiddleware no MIDDLEWARE definindo depois do django.contrib.auth.middleware.AuthenticationMiddleware:

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

Depois você deve substituir a ModelBackend por RemoteUserBackend na configuração AUTHENTICATION_BACKENDS:

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

Com esta configuração, o :class:`~django.contrib.auth.middleware.RemoteUserMiddleware irá detectar o __username__ em request.META['REMOTE_USER'] e irá autenticar e automaticamente logar aquele usuário usando o RemoteUserBackend.

Esteja ciente de que essa definição em particular desabilita a autenticação com o padrão ModelBackend. Isso significa que se o valor de REMOTE_USER não estiver definido o usuário não conseguirá logar-se, mesmo utilizando a inteface do Django admin. Adicionando django.contrib.auth.backends.ModelBackend à lista AUTHENTICATION_BACKENDS ele será utilizado como um substituto se “REMOTE_USER” estiver ausente, e esse problema não acontecerá.

O gerenciamento de usuários do Django, bem como as views em contrib.admin, e o comando de gerenciamento createsuperuser, não fazem integração com usuários remotos. Esta interface trabalha com usuários armazenados no banco de dados independente do AUTHENTICATION_BACKENDS.

Se o seu mecanismo de autenticação utilizar um cabeçalho HTTP costumizado e não o REMOTE_USER`, você pode utilizar a subclass ``RemoteUserMiddleware e definir o atributo header para atribuir a chave request.META. Por exemplo:

Code
from django.contrib.auth.middleware import RemoteUserMiddleware

class CustomHeaderMiddleware(RemoteUserMiddleware):
    header = 'HTTP_AUTHUSER'

Se você precisa de mais controle, é possível criar seu próprio “backend” de autenticação que herda de RemoteUserBackend e sobrescreve um ou mais de seus atributos e métodos.

Usando REMOTE_USER apenas nas páginas de login.Link para este cabeçalho

The RemoteUserMiddleware authentication middleware assumes that the HTTP request header REMOTE_USER is present with all authenticated requests. That might be expected and practical when Basic HTTP Auth with htpasswd or similar mechanisms are used, but with Negotiate (GSSAPI/Kerberos) or other resource intensive authentication methods, the authentication in the front-end HTTP server is usually only set up for one or a few login URLs, and after successful authentication, the application is supposed to maintain the authenticated session itself.

A classe PersistentRemoteUserMiddleware provê suporte para este caso de uso. Ele manterá a sessão de autenticação até o logout explícito do usuário. A classe pode ser usada como um substituto constante para RemoteUserMiddleware na documentação acima.