ron
ron

Reputation: 151

How to get user name after authentication?

I built a website using Django and Apache. I have Apache LDAP authentication. How do I get the username after the user authenticate to the website? I want to get the username and represents it.

Upvotes: 0

Views: 2500

Answers (1)

Nikita
Nikita

Reputation: 6331

So you're using Apache LDAP Authentication. If you use mod_auth_ldap, see the docs here http://httpd.apache.org/docs/2.0/mod/mod_auth_ldap.html#frontpage. If you use mod_authnz_ldap see the docs here https://httpd.apache.org/docs/2.4/mod/mod_authnz_ldap.html#exposed.

What the docs tell is that, when the user is authenticated Apache sets environment variable, that can be accessed from CGI script. Variable name varies depending on the version you use. Though Python uses WSGI, you should still try to get the variable as it's environment variable and should be accessible anyway.

In python to get access to environment variable:

import os
username=os.getenv["REMOTE_USER"] #will return variable value or None
if username:
    pass
    #process username here

See docs on this function here: https://docs.python.org/3.5/library/os.html#os.getenv

You can try to use this directly in your Python code where you expect the username. Or better use this code in wsgi.py in your Django project and if username is available add special header with its value, so that it will be available inside Django in request passed to Django views. But remember to strip that header before adding it, so if a malicious user forges the header it doesn't affect your app. For more information on this see https://docs.djangoproject.com/en/1.9/howto/deployment/wsgi/modwsgi/ and https://docs.djangoproject.com/en/1.9/howto/deployment/wsgi/apache-auth/.

Edit: Btw, there's a "How-to" for REMOTE_USER: https://docs.djangoproject.com/en/1.9/howto/auth-remote-user/

Edit: If you don't have any requirements for performing authentication with Apache, you might want to perform authentication in Django app directly, see: https://pythonhosted.org/django-auth-ldap/ and in example https://djangosnippets.org/snippets/901/.

Upvotes: 2

Related Questions