Login

Authenticate against a Windows domain controller

Author:
calvin
Posted:
December 19, 2007
Language:
Python
Version:
.96
Score:
0 (after 0 ratings)

To activate, store this file as mysite/winauth.py and use in settings.conf:

AUTHENTICATION_BACKENDS = ('mysite.winauth.DomainControllerAuthBackend',)

Needs pywin32 extensions installed (and obviously only runs on Windows).

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# Authentication backend using a Windows NT domain controller.
# To activate, store this file as mysite/winauth.py and use:
# AUTHENTICATION_BACKENDS = ('mysite.winauth.DomainControllerAuthBackend',)
# in your settings.conf.
#
# Needs pywin32 extensions installed (and obviously only runs on Windows).
# Author: Bastian Kleineidam
from django.contrib.auth.models import User
from django.contrib.auth.backends import ModelBackend
import win32security

# Adjust this (you can also store it in settings.py)
DEFAULT_DOMAIN = "INTRANET"

class DomainControllerAuthBackend (ModelBackend):
    """Backend which verifies passwords against a Windows domain controller,
    except superusers where the model password is checked."""

    def authenticate (self, username=None, password=None):
        try:
            user = User.objects.get(username=username)
        except User.DoesNotExist:
            return None
        if user.is_superuser:
            # superusers are local users, so check native password
            if user.check_password(password):
                return user
        elif auth(username, password):
            return user
        return None


def auth (username, password, domain=DEFAULT_DOMAIN):
    """Authenticates user credentials to a Windows domain controller
    Return True if user is authenticated, else False."""
    try:
        return win32security.LogonUser(
          username, domain, password, win32security.LOGON32_LOGON_NETWORK,
          win32security.LOGON32_PROVIDER_DEFAULT)
    except win32security.error, msg:
        # error should be logged, ignore it in this snippet for simplicity
        pass
    return False

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
  5. Help text hyperlinks by sa2812 1 year, 8 months ago

Comments

Please login first before commenting.