简体   繁体   中英

How to develop a helper class to be used in all web-based applications to retrive the information from the Active Directory?

I am a new web developer and in my company all the ASP.NET applications rely on a system that pulls down the user information from the SAP system and retrieve them as a XML document. This system has only one textbox for inserting the username to retrieve his information. An example of it: If you insert the username: johnA the system will provide you with the following information: John Arneson Elli and so on.

Then, in the ASP.NET web-based applications, we used to use three C# classes that does the connections with this system and helpes in getting the specific user information from that system. Anyway, Now we want to replace that system with a new system that gets the user information from the Active Directory.

I put the following code in the server and it works well, so when the employee goes to this code in our server, he will see a page that shows all of his information. What I want to do right now is utilizing this in all our developed and the next new-developed web-based applications by putting a TextBox to put the username of the user and retrieve of all of his information from this system. So how to do that?

I am a beginner and I could not be able to find a way for doing this in Google or anywhere else.

My code of the class for accessing the Active Directory is:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.DirectoryServices;

/// <summary>
/// Summary description for ActiveDirectory
/// </summary>
public class ActiveDirectory
{
    public static string GetPersonData(string id, string datatype)
    {
        //return "x xx xxxx xxx xxx"; //comment this line.
        //Faster performance through Active Directory
        string property = datatype;
        switch (property) //backwards compatibility
        {
            /* case "tel":
                return FindProperty(id, Property.Tel);*/
            case "name":
                return FindProperty(id, Property.Name);
            case "dept":
                return FindProperty(id, Property.Dept);
            case "line":
                return FindProperty(id, Property.Line);
            case "email":
                return FindProperty(id, Property.Email);
            case "id":
                return FindProperty(id, Property.Name);
            default:
                return "";
        }
    }

    //ACTIVE DIRECTORY OPTION.. FOR A BETTER PERFORMANCE
    const string ID = "cn";
    const string NAME = "displayName";
    const string TEL = "telephoneNumber";
    const string DEPT = "department";
    const string LINE = "extensionAttribute3";
    const string UNIT = "extensionAttribute10";
    const string TITLE = "title";
    const string FNAME = "givenName";
    const string MNAME = "initials";
    const string LNAME = "sn";
    const string EMAIL = "mail";
    const string AREA = "extensionAttribute3";
    const string MANAGER = "manager";
    const string ORGCODE = "extensionAttribute10";
    const string DN = "distinguishedName";

    public enum Property
    {
        Name, Tel, Dept, Line, Unit, Title, Fname, Mname, Lname, Email, Manager, OrgCode, DistinguishedName
    }

    public static DirectoryEntry GetDirectoryEntry() 
    {
        using (((System.Security.Principal.WindowsIdentity)HttpContext.Current.User.Identity).Impersonate())
        {
            DirectoryEntry de = new DirectoryEntry(); //DirectoryEntry class encapsulates a node or object in the AD hierarchy
            de.Path = "LDAP://CompanyName.COM";
            de.AuthenticationType = AuthenticationTypes.Delegation;

            return de;
        }
    }

    public static bool UserExists(string username)
    {
        DirectoryEntry de = GetDirectoryEntry();
        DirectorySearcher deSearch = new DirectorySearcher(); //Directory Searcher: It will perform queries against the active directory hierarchy 

        deSearch.SearchRoot = de; //SearchRoot is used to specify where the search starts
        deSearch.Filter = "(&(objectClass=user) (cn=" + username + "))"; //the search retrieves all objects.

        // Create a SearchResultCollection object to hold a collection of SearchResults
        // returned by the FindAll method.
        SearchResultCollection results = deSearch.FindAll();

        return results.Count > 0;
    }
    public static String FindName(String userAccount)
    {
        DirectoryEntry entry = GetDirectoryEntry();
        String account = userAccount.Replace(@"Domain\", "");

        try
        {
            DirectorySearcher search = new DirectorySearcher(entry);
            search.Filter = "(SAMAccountName=" + account + ")";
            search.PropertiesToLoad.Add("displayName");

            SearchResult result = search.FindOne();

            if (result != null)
            {
                return result.Properties["displayname"][0].ToString();
            }
            else
            {
                return "Unknown User";
            }
        }
        catch (Exception ex)
        {
            string debug = ex.Message;

            return debug;
        }
    }

    public static String FindProperty(String userAccount, Property p)
    {
        string property = "";

        //proceed with LDAP search.
        switch (p)
        {
            case Property.Dept:
                property = DEPT;
                break;
            case Property.Email:
                property = EMAIL;
                break;
            case Property.Fname:
                property = FNAME;
                break;
            case Property.Line:
                property = LINE;
                break;
            case Property.Lname:
                property = LNAME;
                break;
            case Property.Mname:
                property = MNAME;
                break;
            case Property.Name:
                property = NAME;
                break;
            case Property.Tel:
                property = TEL;
                break;
            case Property.Title:
                property = TITLE;
                break;
            case Property.Unit:
                property = UNIT;
                break;
            case Property.Manager:
                property = MANAGER;
                break;
            case Property.OrgCode:
                property = ORGCODE;
                break;
            case Property.DistinguishedName:
                property = DN;
                break;
            default:
                return "";

        }

        DirectoryEntry entry = GetDirectoryEntry();
        String account = userAccount.Replace(@"Domain\", "");

        try
        {
            System.Text.Encoding enc = System.Text.Encoding.ASCII;
            DirectorySearcher search = new DirectorySearcher(entry);
            search.Filter = "(&(objectCategory=user)(SAMAccountName=" + account + "))";
            search.PropertiesToLoad.Add(property);

            SearchResult result = search.FindOne();
            search.Dispose();
            entry.Close();
            entry.Dispose();

            if (result != null)
            {
                object value = result.Properties[property][0];
                if (value is System.Byte[])
                    return enc.GetString((byte[])value);
                else
                    return value.ToString();
            }
            else
            {
                return "-";
            }
        }
        catch (Exception ex)
        {
            string debug = ex.Message;

            return "debug";
        }
    }


    public static List<string> FindChildren(string userAccount)
    {
        DirectoryEntry entry = GetDirectoryEntry();
        String account = userAccount.Replace(@"Domain\", "");
        string dn = FindProperty(userAccount, Property.DistinguishedName);
        dn.Replace("*","\\2a");
        dn.Replace("(", "\\28");
        dn.Replace(")", "\\29");
        dn.Replace("\\", "\\5c");
        dn.Replace("NUL", "\\00");
        dn.Replace("/", "\\2f");

        string property = ID;
        List<string> output = new List<string>();
        try
        {
            System.Text.Encoding enc = System.Text.Encoding.ASCII;
            DirectorySearcher search = new DirectorySearcher(entry);
            search.Filter = "(&(objectCategory=user)(manager=" + dn + "))";
            search.PropertiesToLoad.Add(property);

            SearchResultCollection results = search.FindAll();
            search.Dispose();
            entry.Close();
            entry.Dispose();

            if (results != null)
            {
                foreach (SearchResult result in results)
                {
                    object value = result.Properties[property][0];
                    if (value is System.Byte[])
                        output.Add(enc.GetString((byte[])value));
                    else
                        output.Add(value.ToString());
                }
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
        return output;
    }
    public static string FindOrg(string orgcode, string property)
    {
        DirectoryEntry entry = GetDirectoryEntry();

        try
        {
            System.Text.Encoding enc = System.Text.Encoding.ASCII;
            DirectorySearcher search = new DirectorySearcher(entry);
            search.Filter = "(&(objectCategory=user)(" + ORGCODE + "=" + orgcode + "*))";
            search.PropertiesToLoad.Add(property);

            SearchResult result = search.FindOne();
            search.Dispose();
            entry.Close();
            entry.Dispose();

            if (result != null)
            {
                object value = result.Properties[property][0];
                if (value is System.Byte[])
                    return enc.GetString((byte[])value);
                else
                    return value.ToString();
            }
            else
            {
                return "-";
            }
        }
        catch (Exception ex)
        {
            string debug = ex.Message;

            return "debug";
        }
    }
}

UPDATE:

For your information, the above classes are on the server. Now, I am developing a new web-based application. And in this web-based application, I have a textbox that I will use to enter the username. So how I will be able to send this username to that system and retrieve the user information for it to this application? Could you please provide me with an example?

Ok understand now what you really need. The best way for this to be accomplish is by using asp.net webservices. What this means is that you must make some edits to your code that is currently running on your server.
Please look up Asp.net Web Services and check out these links: Microsoft Web Services weblink and Create and Use ASP.NET Web Service

If you're on .NET 3.5 and up, you should check out the System.DirectoryServices.AccountManagement (S.DS.AM) namespace. Read all about it here:

Basically, you can define a domain context and easily find users and/or groups in AD:

// set up domain context
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);

// find a user
UserPrincipal user = UserPrincipal.FindByIdentity(ctx, "SomeUserName");

if(user != null)
{
   // do something here....     
}

// find the group in question
GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, "YourGroupNameHere");

// if found....
if (group != null)
{
   // iterate over members
   foreach (Principal p in group.GetMembers())
   {
      Console.WriteLine("{0}: {1}", p.StructuralObjectClass, p.DisplayName);
      // do whatever you need to do to those members
   }
}

The new S.DS.AM makes it really easy to play around with users and groups in AD!

And as "Nation" mentioned in his response, if you "hide" this behind a web service interface, then all sorts of applications can call into your code and get the information they need out of Active Directory!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM