Tuesday, January 29, 2013

Web Service to Authenticate Users in the Active Directory

 Very recently I was looking for solution to consume active directory authentication for applications like mobile apps,asp.net applications...etc.In this solution web service gets username and password of the active directory user and provide Boolean value whether this user is valid or invalid.Ok let's start building this web service.

1.Create web service application and add custom service to the project.In my case service name ADAuthentication.asmx .Then add reference to the project(System.DirectoryServices)
2.Create Web Method to authenticate users in the  active directory.In my case I'm named web method called ActiveDirectoryAuthentication which gets username and password as parameters.My method will be like this

.
[WebMethod]
        public bool ActiveDirectoryAuthentication(string userName, string password)
        {
                        bool IsUser = false;
            string domain = "Insert your domain here";
            try
            {
                DirectoryEntry entry = new DirectoryEntry("LDAP://" + domain,
                    userName, password);
                object nativeObject = entry.NativeObject;
                IsUser= true;
            }
            catch (DirectoryServicesCOMException) { }
            return IsUser;
        }
According to my web method this return boolean value whether this user valid or not.

3.Deploy web service to your local host.This will show something like this.

4.Once we invoke web service by giving username and password.It will provide xml which contain boolean value(true or false)

Thanks....