LDAP Authentication Class

Below is class for managing custom LDAP authentication, querying group membership, and a dump of assigned groups to the authenticated user. It will also populate all the various attributes related to the user. Keep in mind that some of these attributes are custom to my organization (for example “IPPHONE”), so update the switch/case and public variables as need. The code is written so that if your organization doesn’t use a defined attribute it will just be null and no error will occur.

FYI: LDAP typically runs on port 389 or over SSL on port 636 so make sure you have a hole in your firewall if this is running in your DMZ (least privileges) layer of your network as it is in most cases. More info on LDAP.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;
using System.DirectoryServices.Protocols;
using System.Text;
using System.Collections;
using System.Collections.Specialized;

namespace LDAPTest.Classes

    public class BVUser
        public string server;
        public string username;
        public string password;
        public bool successfully_loaded = false;
        public StringCollection ADGroups = new StringCollection();
        public string sidhistory; 
        public string legacyexchangedn; 
        public string msexchrecipientdisplaytype; 
        public string givenname; 
        public string samaccountname; 
        public string showinaddressbook; 
        public string homedirectory; 
        public string cn; 
        public string pwdlastset; 
        public string whencreated;
        public string accountexpires; 
        public string displayname; 
        public string lastlogon; 
        public string homedrive; 
        public string badpasswordtime; 
        public string countrycode; 
        public string objectguid; 
        public string lastlogontimestamp; 
        public string objectsid; 
        public string usnchanged; 
        public string mstslicenseversion; 
        public string mail; 
        public string msexchrecipienttypedetails; 
        public string usncreated; 
        public string admindisplayname; 
        public string name; 
        public string info; 
        public string msexchversion; 
        public string mstsmanagingls; 
        public string physicaldeliveryofficename; 
        public string lastlogoff; 
        public string internetencoding; 
        public string mailnickname; 
        public string msexchpoliciesincluded; 
        public string whenchanged; 
        public string instancetype; 
        public string mstsexpiredate; 
        public string primarygroupid; 
        public string objectcategory; 
        public string logoncount; 
        public string proxyaddresses; 
        public string useraccountcontrol; 
        public string description; 
        public string dscorepropagationdata; 
        public string distinguishedname; 
        public string ipphone; 
        public string objectclass; 
        public string adspath; 
        public string badpwdcount; 
        public string admindescription; 
        public string memberof; 
        public string userprincipalname; 
        public string samaccounttype; 
        public string employeeid; 
        public string admincount;
        public string targetaddress; 
        public string telephonenumber; 
        public string msexchumdtmfmap; 
        public string department; 
        public string scriptpath; 
        public string managedobjects; 
        public string codepage; 
        public string sn; 

        public BVUser(string _username, string _password, string _ldap_server = "LDAP://") // set your default LDAP Server
            server = _ldap_server;
            username = _username;
            password = _password;
            successfully_loaded = queryLDAP(); // use this public variable to determine if the connection was successful

        private bool queryLDAP()

            DirectoryEntry de = new DirectoryEntry(server, username, password, AuthenticationTypes.Secure);
                DirectorySearcher ds = new DirectorySearcher(de);
                ds.Filter = "(sAMAccountName=" + username + ")";
                SearchResult seares = ds.FindOne();
                StringBuilder str = new StringBuilder();
                ResultPropertyCollection prop = seares.Properties;
                ICollection coll = prop.PropertyNames;
                IEnumerator enu = coll.GetEnumerator();
                // load properties of User into related variables ----------
                while (enu.MoveNext())
                    assignValue(enu.Current.ToString(), seares.Properties[enu.Current.ToString()][0].ToString());
                    //System.Diagnostics.Debug.WriteLine(enu.Current + " = " + seares.Properties[enu.Current.ToString()][0] + "n");

                // load the AD groups into variable "ADGroups"--------------
                if (null != seares)
                    DirectoryEntry obUser = new DirectoryEntry(seares.Path);
                    object obGroups = obUser.Invoke("Groups");
                    foreach (object ob in (IEnumerable)obGroups)
                        DirectoryEntry obGpEntry = new DirectoryEntry(ob);
                        //System.Diagnostics.Debug.WriteLine(obGpEntry.Name + "n");
                return true;
                return false;

        public bool isMemberOf(string _group_name)
            bool _return = false;
            string temp = "";
            foreach (string gp in ADGroups)
                temp = gp.Replace("CN=", "");
                { _return = true; }
            return _return;


        private void assignValue(string _variable, string _value)
                case "sidhistory": sidhistory = _value; break;
                case "legacyexchangedn": legacyexchangedn = _value; break;
                case "msexchrecipientdisplaytype": msexchrecipientdisplaytype = _value; break;
                case "givenname": givenname = _value; break;
                case "samaccountname": samaccountname = _value; break;
                case "showinaddressbook": showinaddressbook = _value; break;
                case "homedirectory": homedirectory = _value; break;
                case "cn": cn = _value; break;
                case "pwdlastset": pwdlastset = _value; break;
                case "whencreated": whencreated = _value; break;
                case "accountexpires": accountexpires = _value; break;
                case "displayname": displayname = _value; break;
                case "lastlogon": lastlogon = _value; break;
                case "homedrive": homedrive = _value; break;
                case "badpasswordtime": badpasswordtime = _value; break;
                case "countrycode": countrycode = _value; break;
                case "objectguid": objectguid = _value; break;
                case "lastlogontimestamp": lastlogontimestamp = _value; break;
                case "objectsid": objectsid = _value; break;
                case "usnchanged": usnchanged = _value; break;
                case "mstslicenseversion": mstslicenseversion = _value; break;
                case "mail": mail = _value; break;
                case "msexchrecipienttypedetails": msexchrecipienttypedetails = _value; break;
                case "usncreated": usncreated = _value; break;
                case "admindisplayname": admindisplayname = _value; break;
                case "name": name = _value; break;
                case "info": info = _value; break;
                case "msexchversion": msexchversion = _value; break;
                case "mstsmanagingls": mstsmanagingls = _value; break;
                case "physicaldeliveryofficename": physicaldeliveryofficename = _value; break;
                case "lastlogoff": lastlogoff = _value; break;
                case "internetencoding": internetencoding = _value; break;
                case "mailnickname": mailnickname = _value; break;
                case "msexchpoliciesincluded": msexchpoliciesincluded = _value; break;
                case "whenchanged": whenchanged = _value; break;
                case "instancetype": instancetype = _value; break;
                case "mstsexpiredate": mstsexpiredate = _value; break;
                case "primarygroupid": primarygroupid = _value; break;
                case "objectcategory": objectcategory = _value; break;
                case "logoncount": logoncount = _value; break;
                case "proxyaddresses": proxyaddresses = _value; break;
                case "useraccountcontrol": useraccountcontrol = _value; break;
                case "description": description = _value; break;
                case "dscorepropagationdata": dscorepropagationdata = _value; break;
                case "distinguishedname": distinguishedname = _value; break;
                case "ipphone": ipphone = _value; break;
                case "objectclass": objectclass = _value; break;
                case "adspath": adspath = _value; break;
                case "badpwdcount": badpwdcount = _value; break;
                case "admindescription": admindescription = _value; break;
                case "memberof": memberof = _value; break;
                case "userprincipalname": userprincipalname = _value; break;
                case "samaccounttype": samaccounttype = _value; break;
                case "employeeid": employeeid = _value; break;
                case "admincount": admincount = _value; break;
                case "targetaddress": targetaddress = _value; break;
                case "telephonenumber": telephonenumber = _value; break;
                case "msexchumdtmfmap": msexchumdtmfmap = _value; break;
                case "department": department = _value; break;
                case "scriptpath": scriptpath = _value; break;
                case "managedobjects": managedobjects = _value; break;
                case "codepage": codepage = _value; break;
                case "sn": sn = _value; break;




<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="LDAPTest.WebForm1" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <form id="form1" runat="server">

        Username: <asp:TextBox id="tb_username" runat="server" /> <br />
        Password: <asp:TextBox ID="tb_password" runat="server" TextMode="Password"/> <br />
        <asp:Button OnClick="AuthButton" runat="server" Text="submit"/> <br />
        <asp:TextBox id="result" runat="server"  /> <br />

        <asp:TextBox id="TextBox1" runat="server"  /> <br />
        <asp:TextBox id="TextBox2" runat="server"  /> <br />
        <asp:TextBox id="TextBox3" runat="server"  /> <br />
        <asp:TextBox id="TextBox4" runat="server"  /> <br />
        <asp:TextBox id="TextBox5" runat="server"  /> <br />
        <asp:TextBox id="TextBox6" runat="server"  /> <br />
        <asp:TextBox id="TextBox7" runat="server"  /> <br />
        <asp:TextBox id="TextBox8" runat="server"  /> <br />



using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;
using System.DirectoryServices.Protocols;
using System.Text;
using System.Collections;
using LDAPTest.Classes;

namespace LDAPTest
    public partial class WebForm1 : System.Web.UI.Page
        protected void Page_Load(object sender, EventArgs e)
            // test comment for teamview

        protected void AuthButton(object sender, EventArgs e)
            BVUser user = new BVUser(tb_username.Text, tb_password.Text);
            if (user.successfully_loaded)
                TextBox1.Text = user.displayname;
                TextBox2.Text = user.givenname;
                TextBox3.Text = user.sn;
                TextBox4.Text = user.description;
                TextBox5.Text = user.employeeid;
                TextBox6.Text = user.isMemberOf("Domain Admins").ToString();
                // user failed to load