How to achieve authentication with django-auth-ldap?
Asked Answered
W

3

12

I have an app running using django. Now i want only users that are authenticated via an openldap server to see "their view" (therefore i only need their uid after successfull authentication)

How can i achieve that?

I guess django-auth-ldap is the way to go, so i tried the whole day to get to know where the authentication actually takes place and how i can get the uid of the user requesting a view.

I used the documentation for the settings.py but i could not find out how to "actually use" it. Maybe someone can point me in the right direction?

settings.py:

import ldap

AUTHENTICATION_BACKENDS = (
    'django_auth_ldap.backend.LDAPBackend',
    'django.contrib.auth.backends.ModelBackend',
)

AUTH_LDAP_SERVER_URI = "ldap://123.60.56.61"

AUTH_LDAP_BIND_DN = ""
AUTH_LDAP_BIND_PASSWORD = ""
AUTH_LDAP_USER_DN_TEMPLATE = "uid=%(user)s,dc=rd,dc=corpintra,dc=net"

(By the way: i already can perform ldap-searche with python-ldap and get results like ldapsearch on the command line, so everything else works just fine...)

What do i need in my views?

Thanks for your help!

Walkling answered 27/3, 2013 at 20:49 Comment(1)
do you actually need the ldap UID of the person, or just a unique identifier for the person on the system?Didymous
D
8

Here's a snippet from one of our sites.

# Django Auth Ldap
main_dn = 'dc=____,dc=organisation,dc=com'
groups_dn = 'ou=Groups,'+main_dn
users_dn = 'ou=Users,'+main_dn

AUTHENTICATION_BACKENDS = (
    'django_auth_ldap.backend.LDAPBackend',
    'django.contrib.auth.backends.ModelBackend',
)

AUTH_LDAP_SERVER_URI = "ldap://ldap.organisation.com"
AUTH_LDAP_BIND_DN = 'cn=___,'+main_dn
AUTH_LDAP_BIND_PASSWORD = "__________________"
AUTH_LDAP_USER_SEARCH = LDAPSearch(users_dn, 2, "(uid=%(user)s)")
AUTH_LDAP_USER_ATTR_MAP = {
    "first_name": "givenName",
    "last_name": "sn",
    "email": "mail"
}
AUTH_LDAP_MIRROR_GROUPS = True
AUTH_LDAP_ALWAYS_UPDATE_USER = True
AUTH_LDAP_GROUP_TYPE = PosixGroupType()
AUTH_LDAP_GROUP_SEARCH = LDAPSearch(groups_dn, ldap.SCOPE_SUBTREE, "(objectClass=posixGroup)")

AUTH_LDAP_USER_FLAGS_BY_GROUP = {
    "is_staff":         "cn=admins,"+groups_dn,
    "is_superuser":     "cn=developers,"+groups_dn,
}

EDIT:

Since the question is "What do i need in my views?", The answer is that this config will save the user's uid as the username field on the User model, so in your views, you need

uid = request.user.username

Hopefully this gets you up and running.

Didymous answered 28/3, 2013 at 11:48 Comment(4)
The question asks: "What do i need in my views?"Aldas
Thank you for the update. However, tracing request.user.username gave me the admin account I used when installing Django. I am not sure whether this can be a new question in itself, but how can I authenticate the Django admin against my LDAP server. Note, from the console, I can query my server etc. I just do not know how to integrate the whole thing in Django.Aldas
the code I posted will authenticate users who have the same username as their UID in LDAP. It will not touch users who dont match up between systems (like your default superuser). If you login as a different LDAP user that does not exist in django, a new user object will be created for them, with username=UID, which you can then access through request.user.username. If you need to be sure that a django user is really an ldap user, you should query ldap with UID=username and see what comes back.Didymous
Actually, my LDAP server does not use UID. I see sAMAccountName. In addition to configuring the settings.py, I have a simple login.html which has a username/password form. When I press send, I want to authenticate the data with my ldap server. I can do that from the shell, and manually in the view. But then, if I do manual initialization in the view, I do not use Django's django_auth_ldap. There are no examples about this on the net. What can I do?Aldas
Z
2

Since django-auth-ldap is a normal Django authentication backend, request.user should be set to the authenticated user (assuming you have the standard middleware installed—see the Django docs). With a typical setup, request.user.username will be the uid of the user's DN. If you need more information, you can get it from request.user.ldap_user.

Zebrawood answered 29/3, 2013 at 21:21 Comment(0)
S
1

I'm not use django-auth-ldap, i write my own ldap authentification backend's.

#define your backend authentification
AUTHENTICATION_BACKENDS = (
    'netipa.managment.ldapwm.netipaldapdjango.NetIpaLdap',
    #'django.contrib.auth.backends.ModelBackend ',
)

For more information about extend the User model, see https://docs.djangoproject.com/en/1.5/topics/auth/customizing/#specifying-a-custom-user-model

#!/usr/bin/env python
#coding:utf-8
# Author:  peter --<[email protected]>
# Created: 22/04/12 
from django.conf import settings
import ldap
#this is a abstrac class to add some custom fields to the default django User model
#see https://docs.djangoproject.com/en/1.5/topics/auth/customizing/#specifying-a-custom-user-model, for more informacion
from netipa.contrib.accesos.models import LdapUsers as User    
from django.contrib.auth.backends import ModelBackend
#import logging


class NetIpaLdap(object):

    supports_inactive_user = False

    def authenticate(self, username=None, password=None):
#        logging.basicConfig(format='%(asctime)s %(message)s',filename="/tmp/auth.log",level=logging.DEBUG)

        if username is None:
            return None

        try:
            # a variable's define in settings
            ip_server = settings.LDAP_BASES.get('ip')
            userdn = settings.LDAP_BASES.get('users')
            ldap.initialize('ldap://%s' % ip_server)
            lop =  ldap.simple_bind_s(
                                            "uid=%s,%s" % (username, userdn),
                                            password
                                            )
        except ldap.LDAPError, e:
            print e
            return None
        except Exception,e:
            print e
            return None

        try:
            user = User.objects.get(username=username)
        except User.DoesNotExist:
            ldap_at = lop.search(settings.LDAP_BASES.get('users'),
                                                    fil='uid=%s' % username,
                                                    types=1,
                                                    attr=['uidnumber', 'mail'])
            user = User(username=username, password=password, ldap_id=ldap_at[0][-1].get('uidnumber')[0],
                        ldap_mail=ldap_at[0][-1].get('mail')[0])
            user.is_staff = True
            user.is_superuser = True
            user.save()
        return user

    def get_user(self, user_id):
        try:
            return User.objects.get(pk=user_id)
        except User.DoesNotExist:
            return None

Here is my extend User Class Model

from django.db import models
from django.contrib.auth.models import AbstractUser

# Create your models here.

class LdapUsers(AbstractUser):
    ldap_id = models.IntegerField()
    ldap_mail = models.EmailField()
Symphonious answered 15/5, 2013 at 5:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.