Active Directory

Read this in "about 1 minute".

Introduction

These days, I am doing some work on Active Directory administration system meant to monitor the user, group under the same domain environment.

Suppose that there are hundreds of users in a company, administrators should add his or her entry permission to each user account. It’s quite annoying, right? So its necessary to administrate all users and create groups with different authorizations.

The Lightweight Directory Access Protocol (LDAP) is an open, standards-based, mature, efficient, extensible, and popular means of interacting with the data contained in directory servers.We need to bind service to it.

Solution

There are two solutions in .NET framework : System.DirectoryServices.AccountManagement
System.DirectoryServices.

Example

The same method of getting user by userName.
Solution 1:

public IUserInfo FindUser(string userName, string password)
        {
            using (var de = new DirectoryEntry("LDAP://" + _principalContext.Name, userName, password))
            {
                using (var adSearch = new DirectorySearcher(de))
                {
                    adSearch.Filter = $"(sAMAccountName={userName})";

                    var result = adSearch.FindOne();

                    return result == null ? null : new DomainUserInfo(result.GetDirectoryEntry());
                }
            }
        }

Solution 2:

public  UserPrincipal GetUser(string userName)
      => UserPrincipal.FindByIdentity(_principalContext, userName)

The difference: the former is to choose certain item by condition query, the latter is to get item directly. The former is easier, the latter is more stable.
PrincipalContext will connect and bind to the base directory when creating an object. While DirectoryEntry won’t bind until you execute a forced connection. As a result, PrincipalContext will get the feedback immediately of whether the connection is bound to the directory successfully.

Author

Typing Theme

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tempora non aut eos voluptas debitis unde impedit aliquid ipsa.

 The comment for this post is disabled.