.NET ActiveDirectory Authentication Across Domain Controller

By Robbe Morris

Using C# or VB.NET to authenticate a user in ActiveDirectory against a different domain controller can be accomplished using the code below:

using System;
using System.Collections.Generic;
using System.Text;
using System.DirectoryServices.AccountManagement;
using System.Security.Principal;
using System.DirectoryServices;

public class SessionController
{

  public static bool LoadSession(string userName, string password, string domainControllerServerName)
  {
      var activeDirectoryGroups = new List<string>();

       using (var pc = new PrincipalContext(ContextType.Domain, domainControllerServerName))
       {
                 var validated = pc.ValidateCredentials(userName.Trim(), password.Trim());

                 if (!validated) return false;

                 var user = UserPrincipal.FindByIdentity(pc,IdentityType.SamAccountName,  userName);

                if (user == null) return false;

                 // get properties from active directory user.  

                 using (var entry = (DirectoryEntry)user.GetUnderlyingObject())
                 {
                     using (var search = new DirectorySearcher(entry))
                    {

                         search.PropertiesToLoad.Add("memberOf");
                      
                         var result = search.FindOne();

                         if (result != null)
                         {
                              var groupCount = result.Properties["memberOf"].Count;

                              for (int i = 0; i < groupCount; i++)
                              {
                                   var group = result.Properties["memberOf"][i].ToString().ToLower().Replace("cn=", string.Empty).Trim();
                                group = group.Substring(0, group.IndexOf(","));
                                  if (activeDirectoryGroups.Contains(group)) continue;
                                  activeDirectoryGroups.Add(group);
                              }
                              // do something with the captured active directory groups for this user.
                         }

                     }
                 }
                  
             }

            return true;
        }
}

.NET ActiveDirectory Authentication Across Domain Controller  (1850 Views)