Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Authenticating Active Directory user in ASP.NET

0.00/5 (No votes)
2 May 2002 2  
How to authenticate the AD user in ASP.NET by using Directory Services

Introduction

In this article I am concentrating on the validation of the Active Directory user through the ASP.NET pages and in fact you can validate the user in any sort of code (non-ASP.NET). The basic things remain the same but the implementation part will depend on the type of requirement. First of all you need to inclue the following code in the .cs file to freely use the directory services.

using System.DirectoryServices;

This will allow you to get the namespace available in your code. Then to get in to the Active Directory server you need to provide the LDAP path which will find the server from the network. Now this you can will be encapsulated in the DirectoryEntry class. The following code will try to contect the server by the user name and passwords provided by you.

DirectoryEntry entry = new DirectoryEntry(LDAP://ADservername,
"username","password");

As per the user name and password this will give you the abstracted property names and value pair collection. Which you can filter later to find out the information specific to the user. To get the specific information you need the DirectorySercher object which will find all the information you need in name value pairs.

DirectorySearcher mySearcher = new     DirectorySearcher(entry);
    SearchResultCollection results;
    mySearcher.Filter ("name=value");
      results = mySearcher.FindAll();
e.g
mySearcher.Filter  ("cn=jignesh");

Over here I try to get the information for the user named jignesh. So for the filter string it is cn=jignesh. This is specific to Active Directory; and you should know all LDAP information about your Active Direcotry. Now is the time to rotate through the name value pair which is quite easy and which you can easily understand.

    foreach(SearchResult resEnt in results)
                {
                    ResultPropertyCollection propcoll=resEnt.Properties;
                    foreach(string key in propcoll.PropertyNames)
                    {
                        foreach(object values in propcoll[key])
                        {
                            //name and value collection retrival

                        }

                    }
                }

Thats it. This way you can connect with the server through the LDAP and fetch all the information from that. Like user name password etc. You can set the parameters too.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here