Home > Articles > ASP.NET Articles > Login authentication using LDAP (Active Directory) for ASP.NET applications

Login authentication using LDAP (Active Directory) for ASP.NET applications

by Thamil   on Jun 02, 2013   Category: ASP.NET  | Level: Intermediate  |  Views: 99984    |  Points: 100   
Like this article? Bookmark and Share:
This article explains how to authenticate the users while login into asp.net application against active directory in a simple way.

 

Introduction


Generally every applications needs user authentication and we have few ways to authenticate the users in web applications. Most of the intranet asp.net web applications authenticate the users againts active directory by using windows user name and passwords.

 

The main benefit of this LDAP (lightweight directory access protocol) authentication is application users do not maintain seperate user name and password for each application. Users can able to use their windows user name and password for all application.

Namespace details


System.DirectoryServices library plays main role on this functionatliy, this takes the user’s user name and password and validating againts windows active directory. So first we need to reference this System.DirectoryServices dll into application. See the below step by step process.



Login page


Now we need the login page for the users to enter user name and passowrd. In this page application user required name & passowrd text box , submit and cancel button as like below

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %>

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title>LDAP Authentication</title>

</head>

<body>

    <form id="form1" runat="server">

    <div>

        <div>

            <table cellpadding="1" cellspacing="1" style="background-color: #E0E0E0; border: 1px solid #727272">

                <tr>

                    <td>

                        <asp:Label ID="lblName" runat="server" Text="Name"></asp:Label>

                    </td>

                    <td>

                        <asp:TextBox ID="txtLoginID" Width="150" runat="server"></asp:TextBox>

                    </td>

                </tr>

                <tr>

                    <td>

                        <asp:Label ID="lblpwd" runat="server" Text="Password"></asp:Label>

                    </td>

                    <td>

                        <asp:TextBox ID="txtPassword" Width="150" TextMode="Password" runat="server"></asp:TextBox>

                    </td>

                </tr>

                <tr>

                    <td colspan="2">

                        <asp:Button ID="btnLogin" runat="server" Text="Login" OnClick="btnLogin_Click" />

                        &nbsp;<asp:Button ID="btnCancel" runat="server" Text="Cancel" OnClick="btnCancel_Click" />

                    </td>

                </tr>

                <tr>

                    <td colspan="2">

                        <asp:Label ID="lblError" runat="server" ForeColor="Red" Text=""></asp:Label>

                    </td>

                </tr>

            </table>

        </div>

    </div>

    </form>

</body>

</html>



 


Once you copy the above code and place in login.aspx page, the page looks like below

 

 

 LDAP path :

For this authentication we need LDAP path to get into the active directory server to validate the user. So configure the LDAP path and domain name details into web.config file under appsetting as like below.

 

 <appSettings>

    <add key="DirectoryPath" value="LDAP://XXXXXXXX,XXXXXX,XXXXXX"></add>

    <add key="DirectoryDomain" value="YY"></add>

  </appSettings>

 

 

Place the below code in cs file under login click event. By using DirectoryEntry class connects the server based on the directory path, user name and password. Using DirectorySearcher object filter the details for particular user from property name and value collections.

 

 

using System;

using System.Collections;

using System.Configuration;

using System.Data;

using System.Linq;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.HtmlControls;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Xml.Linq;

using System.Text;

using System.DirectoryServices;

 

namespace WebApplication1

{

    public partial class WebForm1 : System.Web.UI.Page

    {

        protected void Page_Load(object sender, EventArgs e)

        {

 

        }

 

        protected void btnLogin_Click(object sender, EventArgs e)

        {

            string dominName    = string.Empty;

            string adPath       = string.Empty;

            string userName     = txtLoginID.Text.Trim().ToUpper();

            string strError     = string.Empty;

            try

            {

                foreach (string key in ConfigurationSettings.AppSettings.Keys)

                {

                    dominName = key.Contains("DirectoryDomain") ? ConfigurationSettings.AppSettings[key] : dominName;

                    adPath = key.Contains("DirectoryPath") ? ConfigurationSettings.AppSettings[key] : adPath;

                    if (!String.IsNullOrEmpty(dominName) && !String.IsNullOrEmpty(adPath))

                    {

                        if (true == AuthenticateUser(dominName, userName, txtPassword.Text,adPath, out strError))

                        {

                            Response.Redirect("default.aspx");// Authenticated user redirects to default.aspx

                        }

                        dominName = string.Empty;

                        adPath = string.Empty;

                        if (String.IsNullOrEmpty(strError)) break;

                    }

 

                }

                if (!string.IsNullOrEmpty(strError))

                {

                    lblError.Text = "Invalid user name or Password!";

                }

            }

            catch

            {

                

            }

            finally

            {

               

            }

        }

 

        public bool AuthenticateUser(string domain, string username, string password,string LdapPath, out string Errmsg)

        {

            Errmsg = "";

            string domainAndUsername = domain + @"\" + username;

            DirectoryEntry entry = new DirectoryEntry(LdapPath, 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

                LdapPath = result.Path;

                string _filterAttribute = (String)result.Properties["cn"][0];

            }

            catch (Exception ex)

            {

                Errmsg = ex.Message;

                return false;

                throw new Exception("Error authenticating user." + ex.Message);

            }

            return true;

        }

 

        protected void btnCancel_Click(object sender, EventArgs e)

        {

            txtLoginID.Text = string.Empty;

            txtPassword.Text = string.Empty;

        }

    }

 }

 

 

Once clicks the login button and validate the user against active directory then redirect to default.aspx page for valid user and displays the error message if user details are not found in active directory as like below.

 

For valid user :

 

 

Invalid user :

 

 

 

This is the way to verify the users credentials againts windows active directoy, hope this will help you.




Like this article? Bookmark and Share:

Most viewed Articles

User Comments


  Re :Login authentication using LDAP (Active Directory) for ASP.NET applications   
Posted by gift
on 10/23/2013 4:39:17 AM
Points : 10

we are new to LDAP ... i used ur coding .. but it shows error "The specified domain either does not exist or could not be contacted." like that... if u get a time ,please guide us... .. user authentication using LDAP... our mail id : giftsoftwareteam@gmail.com .. please consider this... we are waiting for ur positive reply
  Re :Login authentication using LDAP (Active Directory) for ASP.NET applications   
Posted by Thamil
on 10/23/2013 11:02:23 AM
Points : 10

hi

every organization/company will have a domain in ldap directory, so just check with your network administrators and get the domain name and LDAP string which is having list employee ids where you want to authenticate the users,
say for example you want to authenticate only finance department user then you will need to get LDAP string for finance users and common domain name

<appSettings>
<add key="DirectoryPath" value="LDAP://XXXXXXXX,XXXXXX,XXXXXX"></add>
<add key="DirectoryDomain" value="YY"></add>
</appSettings>

above i have mentioned sample web.config settings for domain and ldap directory, so you need to get this details from network administrators. Please let me know if you need any further details.
  Re :Login authentication using LDAP (Active Directory) for ASP.NET applications   
Posted by gift
on 10/23/2013 9:38:36 PM
Points : 10

LDAP Server .... network administrator said that he did know how to configure LDAP server ... we are small company in coimbatore,Tamilnadu... i am working as asp.net software developer.. They are asking me to see LDAP Server implementation ... we have a server ... i installed OpenLDAP in my server and i configure by googling in net ... i used nslookup to check whether domain existent or not... i user _ldap._tcp.dc._msdcs.domainname... it says "Non Existent domain " like that ...but we can browse LDAP users in IE in server ... while from asp.net, it gives error ... can u pls give support to me that how to configure or whether my configuration correct or not ... pls do for me ... advance in thanks ... my mail id : giftsoftwareteam@gmail.com
  Re :Login authentication using LDAP (Active Directory) for ASP.NET applications   
Posted by Thamil
on 10/23/2013 11:53:47 PM
Points : 10

hi,

this is simple and easy, domain name you will get it from your system login itself say for ex everytime you will need to entr your userid/login id and password so prefix of user id you need to enter something like IT\userid or CBE\userid or by default it will be displayed. so you can get it from that and LDAP connection string, you need to get it from admin only, they only knows that wehere the employees AD account will be stored. So from your side no need to install anything in the server or your machine.

check the below link for sample ldap connection string.

http://serverfault.com/questions/130543/how-can-i-figure-out-my-ldap-connection-string
http://msdn.microsoft.com/en-us/library/ms257181(v=vs.80).aspx
http://stackoverflow.com/questions/11458291/how-do-i-build-this-ldap-connection-string
http://stackoverflow.com/questions/11966261/ldap-connection-string
  Re :Login authentication using LDAP (Active Directory) for ASP.NET applications   
Posted by Mohd Imadoddin
on 6/15/2015 10:53:22 PM
Points : 10

Nice explaination, but why we are resetting path and filter in last lines?
  Re :Login authentication using LDAP (Active Directory) for ASP.NET applications   
Posted by osman demren
on 7/11/2015 4:20:34 PM
Points : 10

article very successful and running.
I am writing from Istanbul, and I thank you very much.
  Re :Login authentication using LDAP (Active Directory) for ASP.NET applications   
Posted by hieugie
on 7/13/2015 11:35:33 PM
Points : 10

hi,
Can i use asp.net with apacheDS
  Re :Login authentication using LDAP (Active Directory) for ASP.NET applications   
Posted by sunil muthanna
on 11/3/2016 8:21:22 PM
Points : 10

this code worked for me... thanks a lot.
it is simple & well explained..
we have to give correct LDAP path & AD (DirectoryPath)
  Re :Login authentication using LDAP (Active Directory) for ASP.NET applications  New  
Posted by Kumaran
on 12/7/2016 5:50:25 AM
Points : 10

Hi, I have used this code and its working for the current login user? How to create/verify the windows users without using LDAP?

Submit feedback about this article

Please sign in to post feedback

Latest Posts