Monday, November 21, 2011

Authenticating Active Directory user in ASP.NET


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 ActiveDirectory; 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.

No comments: