DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Easy Oracle Database Migration with SQLcl
  • Troubleshooting Connection Issues When Connecting to MySQL Server
  • Managing AWS Managed Microsoft Active Directory Objects With AWS Lambda Functions
  • Jakarta WebSocket Essentials: A Guide to Full-Duplex Communication in Java

Trending

  • Debugging Core Dump Files on Linux - A Detailed Guide
  • Analyzing “java.lang.OutOfMemoryError: Failed to create a thread” Error
  • How to Convert Between PDF and TIFF in Java
  • SQL Server Index Optimization Strategies: Best Practices with Ola Hallengren’s Scripts

Working With LDAP and Active Directory

Learn more about working with LDAP and Active Directory.

By 
Dariusz Suchojad user avatar
Dariusz Suchojad
·
Updated Jun. 05, 19 · Tutorial
Likes (1)
Comment
Save
Tweet
Share
12.1K Views

Join the DZone community and get the full member experience.

Join For Free

A feature new in Zato 3.1 is the ability to connect to LDAP servers, including Active Directory instances, and this article covers basic administration as programming tasks involved in their usage from Python code.

Creating Connections

Connections can be easily created in web-admin. Navigate to Connections -> Outgoing -> LDAP and then click Create a new connection.

The same form works for both regular LDAP and AD — in the latter case, make sure that Auth type is set to NTLM.

The most important information is:

  • User credentials
  • Authentication type
  • Server or servers to connect to

Note that if authentication type is not NTLM, user credentials can be provided using the LDAP syntax, e.g. uid=MyUser,ou=users,o=MyOrganization,dc=example,dc=com.

Right after creating a connection, be sure to set its password too — the password assigned by default is a randomly generated one.

Pinging

It is always prudent to ping a newly created connection to ensure that all the information entered was correct.

Note that if you have more than one server in a pool, then the first available one of them will be pinged — it is the whole pool that is pinged, not a particular part of it.

Active Directory as a REST service

As the first usage example, let's create a service that will translate JSON queries into LDAP lookups — given username or email the service will basic information about the person's account, such as first and last name.

Note that the conn object returned by client.get() below is capable of running any commands that its underlying Python library offers — in this case, we are only using searches but any other operation can also be used, e.g. add or modify as well.

# -*- coding: utf-8 -*-

from __future__ import absolute_import, division, print_function, unicode_literals

# stdlib
from json import loads

# Bunch
from bunch import bunchify

# Zato
from zato.server.service import Service

# Where in the directory we expect to find the user
search_base = 'cn=users, dc=example, dc=com'

# On input, we are looking users up by either username or email
search_filter = '(&(|(uid={user_info})(mail={user_info})))'

# On output, we are interested in username, first name, last name and the person's email
query_attributes = ['uid', 'givenName', 'sn', 'mail']

class ADService(Service):
    """ Looks up users in AD by their username or email.
    """
    class SimpleIO:
        input_required = 'user_info'
        output_optional = 'message', 'username', 'first_name', 'last_name', 'email'
        response_elem = None
        skip_empty_keys = True

    def handle(self):

        # Connection name to use
        conn_name = 'My AD Connection'

        # Get a handle to the connection pool
        with self.out.ldap[conn_name].conn.client() as client:

            # Get a handle to a particular connection
            with client.get() as conn:

                # Build a filter to find a user by
                user_info = self.request.input['user_info']
                user_filter = search_filter.format(user_info=user_info)

                # Returns True if query succeeds and has any information on output
                if conn.search(search_base, user_filter, attributes=query_attributes):

                    # This is where the actual response can be found
                    response = conn.entries

                    # In this case, we expect at most one user matching input criteria
                    entry = response[0]

                    # Convert to JSON so it is easier to handle
                    entry = entry.entry_to_json()

                    # Load from JSON to a Python dict
                    entry = loads(entry)

                    # Convert to a Bunch instance to get dot access to dictionary keys
                    entry = bunchify(entry['attributes'])

                    # Now, actually produce a JSON response. For simplicity's sake,
                    # assume that users have only one of email or other attributes.
                    self.response.payload.message = 'User found'
                    self.response.payload.username = entry.uid[0]
                    self.response.payload.first_name = entry.givenName[0]
                    self.response.payload.last_name = entry.sn[0]
                    self.response.payload.email = entry.mail[0]

                else:
                    # No business response = no such user found
                    self.response.payload.message = 'No such user'

After creating a REST channel, we can invoke the service from the command line:

$ curl "localhost:11223/api/get-user?user_info=MyOrganization\\MyUser" ; echo
{
    "message": "User found",
    "username": "MyOrganization\\MyUser",
    "first_name": "First",
    "last_name": "Last",    
    "email": "address@example.com"
}
$

Checking User Credentials

A recurrent task in enterprise integrations in checking user credentials on behalf of systems that are not able to connect to AD or LDAP themselves; for instance, because they do not support the LDAP protocol or because a particular architecture disallows for them to make direct connections to backend servers.

To support this use-case, a separate method was added to the Python API specifically to validate user credentials — the code below is everything that is needed to confirm if user credentials are valid:

...

def handle(self):

    # Connection name to use
    conn_name = 'My AD Connection'

    # Credentials to check
    username = 'myuser'
    password = 'mypassword'

    # Get a handle to the connection pool object
    with self.out.ldap[conn_name].conn.client() as client:

        # Check credentials using the pool's configuration
        is_valid = client.check_credentials(username, password)

        if is_valid:
            # Credentials are valid, act accordingly here
            ...

        else:
            # Invalid username or password, return an error here
            ...

Summary

Full support for LDAP and Active Directory connections was added in Zato 3.1, and the Python API exposed grants one access to all the operations possible — offering means to integrate with directories or making them communicate with other technologies or protocols is now just a matter of authoring a service and exposing it through a channel, such as REST or one of the other types that Zato supports.

Directory Connection (dance)

Opinions expressed by DZone contributors are their own.

Related

  • Easy Oracle Database Migration with SQLcl
  • Troubleshooting Connection Issues When Connecting to MySQL Server
  • Managing AWS Managed Microsoft Active Directory Objects With AWS Lambda Functions
  • Jakarta WebSocket Essentials: A Guide to Full-Duplex Communication in Java

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!