Login with active directory in ASP.Net using C#

sofia
 
on Jan 04, 2022 10:05 PM
777 Views

Hi dharmendr sir,

Sir I have write the code for login with active directory.

Can u help me for writing login code with active directory.

Actually sir I have watched all youtube channels and videos for doing this but didn’t got any help. I am a beginner and couldn’t write the code in advanced level.

My last option is you. Please help me.

 

My code is attached below.

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

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="txtLoginID" runat="server"></asp:TextBox>
        <asp:Label ID="lblError" runat="server" Text="Label"></asp:Label>
        <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
    
    </div>
    </form>
</body>
</html>

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
 using System.DirectoryServices;
using System.Web.Security;

namespace WebApplication38
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            string dominName = string.Empty;
            string adPath = string.Empty;
            string userName = txtLoginID.Text;
            string strError = string.Empty;
            try
            {
                foreach (string key in ConfigurationManager.AppSettings.Keys)
                {
                    dominName = key.Contains("DirectoryDomain") ? ConfigurationManager.AppSettings[key] : dominName;
                    adPath = key.Contains("DirectoryPath") ? ConfigurationManager.AppSettings[key] : adPath;
                    if (!String.IsNullOrEmpty(dominName) && !String.IsNullOrEmpty(adPath))
                    {
                        if (true == AuthenticateUser(dominName, userName, txtPassword.Text, adPath, out strError))
                        {
                            Response.Redirect("HomePage.aspx"); // Authenticated user redirects to WebFormslide.aspx
                        }
                        dominName = string.Empty;
                        adPath = string.Empty;
                        if (String.IsNullOrEmpty(strError)) break;
                    }
 
                }
                if (!string.IsNullOrEmpty(strError))
                {
                    lblError.Text = "Invalid user name or Password!";
                }
            }
            catch (Exception ex)
            {
                 
            }
            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;
        }
 
        
        }
    }

 

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Jan 05, 2022 03:01 AM

Hi sofia,

Refer below link and follow the steps.

https://www.c-sharpcorner.com/article/active-directory-and-net/