Integrated authentication + LDAP user authentication in Django. How?
Introduction
- Django version: 1.10
- Python version: 3.5.2
I am trying to implement LDAP condition based authentication and I cannot figure out how to do it.
My project already uses Django's built-in authentication system, which works great and looks like this:
# urls.py
from django.conf.urls import include, url
from django.contrib import admin
from django.contrib.auth import views
from coffee_app.forms import LoginForm
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'', include('coffee_app.urls')),
url(r'^login/$', views.login, {'template_name': 'login.html', 'authentication_form': LoginForm}, name='login'),
url(r'^logout/$', views.logout, {'next_page': '/login'}, name='logout'),
]
# forms.py
from django.contrib.auth.forms import AuthenticationForm
from django import forms
class LoginForm(AuthenticationForm):
username = forms.CharField(label="Username", max_length=32,
widget=forms.TextInput(attrs={
'class': 'form-control',
'name': 'username'
}))
password = forms.CharField(label="Password", max_length=20,
widget=forms.PasswordInput(attrs={
'class': 'form-control',
'name': 'password'
}))
<!--login.html (relevant part)-->
<form class="form-horizontal" action="{% url 'login' %}" method="post" id="contact_form">
{% csrf_token %}
<fieldset>
<div class="form-group">
<label class="col-md-4 control-label">{{ form.username.label_tag }}</label>
<div class="col-md-4 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
{{ form.username }}
</div>
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label" >{{ form.password.label_tag }}</label>
<div class="col-md-4 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
{{ form.password }}
</div>
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label"></label>
<div class="col-md-4 text-center">
<br>
<button value="login" type="submit" class="btn btn-warning" >
LOG IN
<span class="glyphicon glyphicon-send"></span>
</button>
</div>
</div>
</fieldset>
<input type="hidden" name="next" value="{{ next }}"/>
</form>
Problem
Now, what I'm trying to do is check if the user exists in LDAP or not, before going to the original Django version:
from ldap3 import Server, Connection, ALL, NTLM
server = Server('server here', get_info=ALL, use_ssl=True)
conn = Connection(server,
user='DOMAIN\\username',
password='password',
authentication=NTLM)
print(conn.bind())
If it conn.bind()
does return True
, I would like to go to Django's built-in authentication system and authenticate the user. Unfortunately I don't know where / how to add this step to achieve this.
Some views look like this:
from django.shortcuts import render
from django.http import HttpResponse
from django.contrib.auth.decorators import login_required
@login_required(login_url="login/")
def home(request):
return render(request, "home.html")
@login_required(login_url="login/")
def activity_report_page(request):
return render(request, "activity_report.html")
...
And their url:
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.home, name='home'),
url(r'report$', views.activity_report_page, name='activity_report')
]
Can anyone point out where I should add some of the LDAP code so that I can first check if the user exists there?
PS: I didn't consider using django-auth-ldap
it because I really don't need a pure LDAP based authentication system. Simple confirmation.
You want to set up authentication in Django , where you more specifically want to write an authentication backend . I assume your project is called "coffee_site" and you have a "coffee_app" application. First you want to modify coffee_site/settings.py
and add AUTHENTICATION_BACKENDS = ['coffee_site.auth.LDAP']
to it. After that, you want to do and edit coffee_site/auth.py
. As you said in the question that you want to use the default authentication and therefore you must inherit from django.contrib.auth.backends.ModelBackend
, then you want to make it so that if conn.bind()
not True then you are not using the default authentication and therefore you should return None
. This can be accomplished with:
from django.contrib.auth.backends import ModelBackend
from ldap3 import Server, Connection, ALL, NTLM
server = Server('server here', get_info=ALL, use_ssl=True)
class LDAP(ModelBackend):
def authenticate(self, *args, **kwargs):
username = kwargs.get('username')
password = kwargs.get('password')
if username is None or password is None:
return None
conn = Connection(server,
user='DOMAIN\\{}'.format(username),
password=password,
authentication=NTLM)
if not conn.bind():
return None
return super().authenticate(*args, **kwargs)
Note . I have tested this on the Django side, but I have not tried to test if the LDAP code is working.
source to share
I recommend using django-auth-ldap. Here is the documentation for it and a good example: django-auth-ldap documentation .
source to share