2013-03-27 18 views
11

Ho un'applicazione in esecuzione con django. Ora voglio solo utenti che sono autenticati tramite un server openldap per vedere "la loro vista" (quindi ho bisogno del loro uid solo dopo autenticazione avvenuta)Come ottenere l'autenticazione con django-auth-ldap?

Come posso raggiungere questo?

Immagino che django-auth-ldap sia la strada da percorrere, così ho provato tutto il giorno per sapere dove si verifica effettivamente l'autenticazione e come posso ottenere l'uid dell'utente che richiede una vista.

Ho utilizzato il documentation for the settings.py ma non sono riuscito a scoprire come "effettivamente utilizzarlo". Forse qualcuno può indicarmi la giusta direzione?

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" 

(A proposito: ho già possibile eseguire ldap-searche con python-ldap e ottenere risultati come ldapsearch sulla riga di comando, quindi tutto il resto funziona bene ...)

Cosa mi serve nelle mie visualizzazioni?

Grazie per il vostro aiuto!

+0

si fa effettivamente bisogno l'UID LDAP della persona, o solo un identificativo univoco per la persona sul sistema? – Thomas

risposta

6

Ecco uno snippet da uno dei nostri siti.

# 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:

Dal momento che la domanda è "? Di cosa ho bisogno in mio punto di vista", la risposta è che questa configurazione salverà uid dell'utente come il campo nome utente sul modello utente, quindi in il tuo punto di vista, è necessario

uid = request.user.username 

Speriamo che questo ti alzi e funzionante.

+0

La domanda chiede: "Di cosa ho bisogno nelle mie opinioni?" – shailenTJ

+0

@shailenTJ Ho aggiornato la mia risposta – Thomas

+0

Ehi @ user982809, se questa risposta ti ha aiutato, considera di contrassegnarla come accettata. – Thomas

2

Poiché django-auth-ldap è un normale back-end di autenticazione Django, request.user deve essere impostato sull'utente autenticato (presupponendo di avere il middleware standard installato — vedere i documenti di Django). Con una configurazione tipica, request.user.username sarà l'uid del DN dell'utente. Se hai bisogno di ulteriori informazioni, puoi ottenerlo dal request.user.ldap_user.

1

Io non uso django-auth-ldap, scrivo il mio backend di autenticazione Ldap.

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

Per ulteriori informazioni su estendere il modello di utente, vedere 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 

Ecco il mio estendere User Class Modello

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() 
Problemi correlati