Reputation: 2591
im using Django with Apache and LDAP backend auth, my http conf is as below:
LoadModule ldap_module modules/mod_ldap.so
LoadModule authnz_ldap_module modules/mod_authnz_ldap.so
#
<Location />
AuthName "Please enter your domain credentials."
AuthBasicProvider ldap
AuthType basic
AuthLDAPUrl "ldap://example.com:389/DC=example,DC=com?sAMAccountName"
AuthLDAPBindDN "CN=serv,OU=Service Accounts,DC=example,DC=com"
AuthLDAPBindPassword XXXX
AuthLDAPBindAuthoritative off
LDAPReferrals off
Require valid-user
</Location>
Which when i now load my site i get a basic auth prompt which is great, what id like to be able to do now is to receive the logged in username, ive searched and tried a few things such as:
LoggedInUser = request.user.username
which gives me a request is not defined message (i have import requests at the top)
LoggedInUser = os.getenv["REMOTE_USER"]
which gives me TypeError: 'function' object has no attribute 'getitem'
does anyone know what i need to be using?
i also need to hide certain urls from users if they are not in the correct ldap group, so would need to get the users AD groups aswell from the session
Thanks
Upvotes: 4
Views: 1304
Reputation: 77251
According to the documentation topic "Authentication using REMOTE_USER", in order to use Apache authentication, you must include a specific middleware:
Configuration
First, you must add the
django.contrib.auth.middleware.RemoteUserMiddleware
to theMIDDLEWARE_CLASSES
setting after thedjango.contrib.auth.middleware.AuthenticationMiddleware
:
MIDDLEWARE_CLASSES = [
'...',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.RemoteUserMiddleware',
'...',
]
Next, you must replace the
ModelBackend
withRemoteUserBackend
in theAUTHENTICATION_BACKENDS
setting:
AUTHENTICATION_BACKENDS = [
'django.contrib.auth.backends.RemoteUserBackend',
]
If you are already doing this without success, and given you need more granular access controls, I would just write a custom authentication backend and ditch mod_ldap altogether. Writing a custom authentication backend is really easy. The key is to get the python ldap module working before writing the backend.
In order to access request.user
you must be inside a Django view. For example:
def index(request):
user = request.user
return render(request, 'template.html', {"user": user})
And in the template.html
file:
<h1>Hi, {{ user }}</h1>
Upvotes: 2
Reputation: 58523
Per request WSGI environ key/values are found in Django request.META
object. Thus try:
request.META['REMOTE_USER']
Whether what Apache passes through to you is in format you expect is a different issue. You may find what you want in other variables passed through. See:
Upvotes: 3