Github – snok/django-auth-adfs: a django authentication backend for microsoft adfs and azuread

Available settings

Note: The settings below show their default values. You only need to add settings to your settings.py file that you intend to override.

# The URL of the LDAP server(s).  List multiple servers for high availability ServerPool connection.LDAP_AUTH_URL= ["ldap://localhost:389"]

# Initiate TLS on connection.LDAP_AUTH_USE_TLS=False# Specify which TLS version to use (Python 3.10 requires TLSv1 or higher)importsslLDAP_AUTH_TLS_VERSION=ssl.PROTOCOL_TLSv1_2# The LDAP search base for looking up users.LDAP_AUTH_SEARCH_BASE="ou=people,dc=example,dc=com"# The LDAP class that represents a user.LDAP_AUTH_OBJECT_CLASS="inetOrgPerson"# User model fields mapped to the LDAP# attributes that represent them.LDAP_AUTH_USER_FIELDS= {
    "username": "uid",
    "first_name": "givenName",
    "last_name": "sn",
    "email": "mail",
}

# A tuple of django model fields used to uniquely identify a user.LDAP_AUTH_USER_LOOKUP_FIELDS= ("username",)

# Path to a callable that takes a dict of {model_field_name: value},# returning a dict of clean model data.# Use this to customize how data loaded from LDAP is saved to the User model.LDAP_AUTH_CLEAN_USER_DATA="django_python3_ldap.utils.clean_user_data"# Path to a callable that takes a user model, a dict of {ldap_field_name: [value]}# a LDAP connection object (to allow further lookups), and saves any additional# user relationships based on the LDAP data.# Use this to customize how data loaded from LDAP is saved to User model relations.# For customizing non-related User model fields, use LDAP_AUTH_CLEAN_USER_DATA.LDAP_AUTH_SYNC_USER_RELATIONS="django_python3_ldap.utils.sync_user_relations"# Path to a callable that takes a dict of {ldap_field_name: value},# returning a list of [ldap_search_filter]. The search filters will then be AND'd# together when creating the final search filter.LDAP_AUTH_FORMAT_SEARCH_FILTERS="django_python3_ldap.utils.format_search_filters"# Path to a callable that takes a dict of {model_field_name: value}, and returns# a string of the username to bind to the LDAP server.# Use this to support different types of LDAP server.LDAP_AUTH_FORMAT_USERNAME="django_python3_ldap.utils.format_username_openldap"# Sets the login domain for Active Directory users.LDAP_AUTH_ACTIVE_DIRECTORY_DOMAIN=None# The LDAP username and password of a user for querying the LDAP database for user# details. If None, then the authenticated user will be used for querying, and# the `ldap_sync_users`, `ldap_clean_users` commands will perform an anonymous query.LDAP_AUTH_CONNECTION_USERNAME=NoneLDAP_AUTH_CONNECTION_PASSWORD=None# Set connection/receive timeouts (in seconds) on the underlying `ldap3` library.LDAP_AUTH_CONNECT_TIMEOUT=NoneLDAP_AUTH_RECEIVE_TIMEOUT=None

Binding to active directory using django-auth-ldap

I’m trying to create user login authentication in my django app via Active Directory using django-auth-ldap. The problem is that I cannot bind to the AD using username (which is sAMAccountName LDAP equivalent). Part of my settings.py below:

import ldap
from django_auth_ldap.config import LDAPSearch

AUTHENTICATION_BACKENDS = [
    'django_auth_ldap.backend.LDAPBackend',
]

AUTH_LDAP_START_TLS = False
AUTH_LDAP_ALWAYS_UPDATE_USER = False
AUTH_LDAP_SERVER_URI = 'ldap://ip_address:389'
AUTH_LDAP_BIND_DN = ''
AUTH_LDAP_BIND_PASSWORD = ''
AUTH_LDAP_USER_SEARCH = LDAPSearch('DC=example,DC=com', ldap.SCOPE_SUBTREE, '(sAMAccountName=%(user)s)')
AUTH_LDAP_CONNECTION_OPTIONS = {
    ldap.OPT_REFERRALS: 0,
}

Console log:

ERROR search_s('DC=example,DC=com', 2, '(sAMAccountName=user)') raised OPERATIONS_ERROR({'desc': 'Operations error', 'info': '00000000: LdapErr: DSID-0C090627, comment: In order to perform this operation a successful bind must be completed on the connection., data 0, vece'})
DEBUG search_s('DC=example,DC=com', 2, '(sAMAccountName=%(user)s)') returned 0 objects:
DEBUG Authentication failed for user: failed to map the username to a DN.

Any idea why this is not working?

Похожее:  Пин код Теле2 по умолчанию - как узнать и разблокировать pin-код если забыл

Can’t get authentication to work?

LDAP is a very complicated protocol. Enable logging (see below), and see what error messages the LDAP connection is throwing.

Contributing

If you’d like to contribute, the best approach is to send a well-formed pull
request, complete with tests and documentation. Pull requests should be
focused: trying to do more than one thing in a single request will make it more
difficult to process.

If you have a bug or feature request you can try logging an issue.

There’s no harm in creating an issue and then submitting a pull request to
resolve it. This can be a good way to start a conversation and can serve as an
anchor point.

Creation of the django application

The first step is to create our contained pipenv environment and install Django and ldap3, a library to connect to an LDAP:


mkdir DjangoApplications && cd DjangoApplications
pipenv install Django ldap3

Now that we have a configured environment, we can create our Django application and initialize the database:

Ldap authentication parameter

Optional parameter.
If you want to change method of authorization with your LDAP from SIMPLE to any else (FIRST, SYNC, SIMPLE, NTLM), you can do it by setting parameter in settings.

Ldap engine

As some capabilities differs between LDAP engines, you can define your engine to use specific features.

Actual used values are:

Logging

Print information about failed logins to your console by adding the following to your settings.py file.

LOGGING= {
    "version": 1,
    "disable_existing_loggers": False,
    "handlers": {
        "console": {
            "class": "logging.StreamHandler",
        },
    },
    "loggers": {
        "django_python3_ldap": {
            "handlers": ["console"],
            "level": "INFO",
        },
    },
}

Microsoft active directory support

django-python3-ldap is configured by default to support login via OpenLDAP. To connect to
a Microsoft Active Directory, you need to modify your settings file.

More information

The django-python3-ldap project was developed by Dave Hall. You can get the code
from the django-python3-ldap project site.

Dave Hall is a freelance web developer, based in Cambridge, UK. You can usually
find him on the Internet in a number of different places:

Obfuscate password

If, for security reason, you don’t want the real password to be stored in the database at authentication time, you can ask to obfuscate it. When set to true, the password stored at authentication time will be randomly generated.

Prerequisites

Before creating our application, you need to install python and pip.This article gives the installation details on Mac and Linux.

We will also need pipenv to create a contained environment and avoid conflicts with other projects (more details on why using pipenv).

Servers

Mandatory parameter.
List of LDAP server to authenticate against. 3 information are needed for each:

  • it’s name or IP (prefer IP to avoid spending time with the DNS lookup)
  • the TCP port to connect on (default: 389 for non SSL and 636 for SSL)
  • a boolean tag to enable or not the use of SSL during authentication process against this server.

You can define as many authentication servers as needed (as many as you have in you network) with, for each, it’s own parameters.
The pool is used in the order you defined. If the first one is available, authentication is against it, if the server is not available, the next is used. In all cases, if an answer is received for a server, it’s considered authoritative even if it’s negative

LDAP_SERVERS= [
    {
        'host': '<server 1 IP>',
        'port': 389,
        'use_ssl': False,
        'get_info': 'NONE',
    },
    {
        'host': '<server 2 IP>',
        'port': 389,
        'use_ssl': False,
        'get_info': 'NONE',
    },
]

get_info:
specifies if the server schema and server specific info must be read (defaults to SCHEMA).

Possible values are:
NONE: no information is gathered from the server
DSA: server information is stored in server.info
SCHEMA: schema information is stored in server.schema
ALL: server and schema information are gathered and stored in server.info and server.

schema
OFFLINE_EDIR_8_8_8: pre-built schema and info for NetIQ eDirectory 8.8.8
OFFLINE_AD_2022_R2: pre-built schema and info for Microsoft Active Directory from Windows Server 2022 R2
OFFLINE_SLAPD_2_4: pre-built schema and info for Openldap 2.4
OFFLINE_DS389_1_3_3: pre-built schema and info for DS389 1.3.3

Support and announcements

Downloads and bug tracking can be found at the main project
website.

Auth backend setting

Mandatory parameter to tell django to use this module as it’s authentication backend. See django’s documentation to use it in an authentication chain. The example shows how to set it as the only authoritative authentication backend.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *