Jumat, 22 Mei 2015

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

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

by Thamilselvan Jagadeesan   on Jun 02, 2013   Category: ASP.NET  | Level: Intermediate  |  Views: 57285    |  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.

Source : http://www.dotnetgallery.com/kb/resource6-Login-authentication-using-LDAP-Active-Directory-for-ASPNET-applications.aspx

Tidak ada komentar:

Posting Komentar