Ldap User Authetication in C#


// create class library 
using System;
using System.Collections.Generic;
using System.Text;
using System.DirectoryServices;

namespace UserAuthentication
{
    public class ActiveDirectoryValidator
    {
        private string _path;
        private string _filterAttribute;

        public ActiveDirectoryValidator(string path)
        {
            _path = path;
        }

        public bool IsAuthenticated(string domainName, string userName, string password)
        {
            string domainAndUsername = domainName + @"\" + userName;
            DirectoryEntry entry = new DirectoryEntry(_path, domainAndUsername, password);
            try
            {
                // Bind to the native AdsObject to force authentication.
                Object obj = entry.NativeObject;
                DirectorySearcher search = new DirectorySearcher(entry);
                search.Filter = "(SAMAccountName=" + userName + ")";
                search.PropertiesToLoad.Add("cn");
                SearchResult result = search.FindOne();
                if (null == result)
                {
                    return false;
                }
                // Update the new path to the user in the directory
                _path = result.Path;
                _filterAttribute = (String)result.Properties["cn"][0];
            }
            catch (Exception ex)
            {
                throw new Exception("Login Error: " + ex.Message);
            }
            return true;
        }
    }
}
// usage
  using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using UserAuthentication; // add reference of above class library

public partial class LogOn : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            string domainUser =System.Security.Principal.WindowsIdentity.GetCurrent().Name;
            string[] paramsLogin = domainUser.Split('\\');
            txtUser.Text = paramsLogin[1].ToString();
            txtDomain.Text = paramsLogin[0].ToString();
        }
    }
    protected void btnLogon_Click(object sender, EventArgs e)
    {
        try
        {
            this.AutenticateUser(txtDomain.Text, txtUser.Text, txtPassword.Text);
        }
        catch (Exception ex)
        {
            lblError.Text = ex.Message;
            lblError.Visible = true;
        }
    }

    private void AutenticateUser(string domainName, string userName, string password)
    {
        // Path to you LDAP directory server.
        // Contact your network administrator to obtain a valid path.


        string adPath = "LDAP://" +System.Configuration.ConfigurationSettings.AppSettings["DefaultActiveDirectoryServer"]; ;
        ActiveDirectoryValidator adAuth = new ActiveDirectoryValidator(adPath);
        if (true == adAuth.IsAuthenticated(domainName, userName, password))
        {
            // Create the authetication ticket
            FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, userName, DateTime.Now, DateTime.Now.AddMinutes(60), false, "");
            // Now encrypt the ticket.
            string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
            // Create a cookie and add the encrypted ticket to the
            // cookie as data.
            HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
            // Add the cookie to the outgoing cookies collection.
            HttpContext.Current.Response.Cookies.Add(authCookie);
            // Redirect the user to the originally requested page
            HttpContext.Current.Response.Redirect(FormsAuthentication.GetRedirectUrl(userName, false));
        }

        

    }
}

Comments