AD authentication in C# – Code Sample

This post will donate you some sample codes to authenticate User’a Login Name & Password against Active Directory (AD). In addition, this will show you how to retrieve some information related the the particular AD account.

It has been created a method to insert an User Log to track approximately users which is stored data in MS SQL server, Therefore, it has been created a Connection class to build the DB connection to the database.

Connection class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;

namespace eCanionCore
{
    public class Connection
    {
        public static SqlConnection DBConnection()
        {

            SqlConnection con = new SqlConnection(@"user id=sa; password=; initial catalog=Test; data source=.;");
            return con;
        }
    }
}

All the methods necessary to implement AD authentication application have been defined in the Interface class of the project.

This is the class where defined Interfaces

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace eCanionCore
{
    interface IAuthentication
    {
        Boolean ValidateUser(string varDomain, string varUserName, string varPwd);
        Boolean LogEntry(string varIPAddress, string varUserName);
        string ResetPassword(string varDomain, string varUserID, string varCurrPwd, string varNewPwd);
        string GetUserName(string varDomain, string varUserID);
    }
}

It has been coded for the functions which have been already defined in the Interface class.

This is the implementation of defined Interfaces at the IAuthentication Interface

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;

namespace eCanionCore
{
    public class AuthenticateUsers:IAuthentication
    {    
        public bool  ValidateUser(string varDomain, string varUserName, string varPwd)
        {
            Boolean isValidUser;
            using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, varDomain))
            {
                isValidUser = pc.ValidateCredentials(varUserName, varPwd);
            }
            return isValidUser;

        }

        public bool  LogEntry(string varIPAddress, string varUserName)
        {
            try
            {
                SqlDataAdapter da = new SqlDataAdapter();
                SqlCommand sqlCom = new SqlCommand("insert into tblAD_Log values(@IP,@UserName,getDate())");
                sqlCom.CommandType = CommandType.Text;
                sqlCom.Connection = Connection.DBConnection();
                sqlCom.Parameters.AddWithValue("@IP", varIPAddress);
                sqlCom.Parameters.AddWithValue("@UserName", varUserName);
                sqlCom.Connection.Open();
                sqlCom.ExecuteNonQuery();
                return true;
            }
            catch
            {
                return false;
            }

        }
        public string ResetPassword(string varDomain,string varUserID,string varCurrPwd,string varNewPwd)
        {
            try
            {
                using (var context = new PrincipalContext(ContextType.Domain, varDomain))
                {
                    using (var user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, varUserID))
                    {
                        user.ChangePassword(varCurrPwd, varNewPwd);
                        user.Save();
                        return "0";
                    }
                }                             
            }
            catch (Exception ex)
            {
                return ex.Message;
            }            
        }
        public string GetUserName(string varDomain, string varUserID)
        {
            try
            {
                using (var context = new PrincipalContext(ContextType.Domain, varDomain))
                {
                    using (var user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, varUserID))
                    {

                        string name = user.Name;
                        return name;

                    }
                }
            }
            catch (Exception ex)
            {
                return "1";
            }             
        }
    }
}

Here is the code which create the HTML login form to accept the Login Name & Password. You can you any client you post data and received the result as an example windows form, or mobile apps or what ever it can accept data from user & received data from server.

Code for Login form

<table cellpadding="0" cellspacing="0" border="0" height="175px" bgcolor="#006666">
                        <tr>
                            <td>&nbsp;</td>                    
                        </tr>
                        <tr>
                            <td><h1 class="titleText">Enter Your Credentials</h1></td>                    
                        </tr>
                        <tr>
                            <td class="normalText">User Name</td>                    
                        </tr>
                        <tr>
                            <td>
                                <input type="text" name="txtUserName" ID="txtUserName" size="55" runat="server" />
                            </td>                    
                        </tr>
                        <tr>
                            <td class="normalText">Password</td>                    
                        </tr>
                        <tr>
                            <td>
                                <input type="password" name="txtPwd"  ID="txtPwd"  size="55" runat="server" />
                            </td>                    
                        </tr>
                        <tr>
                            <td>&nbsp;</td>                    
                        </tr>
                        <tr>
                            <td align="right">&nbsp;<asp:Button  class="classname" ID="btnLogin" runat="server" 
                                    Text="Sign In" onclick="btnLogin_Click" />&nbsp;<input type="button" class="classname" ID="btnReset" value="Reset" onclick="ResetValues();" /></td>                    
                        </tr>
                    </table>

sdf

Code behinde file of the “Login.aspx”

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using eCanionCore;

namespace eCanionPortal
{
    public partial class Default : System.Web.UI.Page
    {
        AuthenticateUsers au;
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void btnLogin_Click(object sender, EventArgs e)
        {
            Boolean isValidUser;
            au = new AuthenticateUsers();
            isValidUser = au.ValidateUser("ecanion.com", txtUserName.Value, txtPwd.Value);

            if (isValidUser == true)
            {
                Session["UserName"] = txtUserName.Value;                
                au.LogEntry(Convert.ToString(Request.ServerVariables["REMOTE_ADDR"]), txtUserName.Value);
                Response.Redirect("ecanionHome.aspx");
            }
            else
            {
                divMessage.InnerText = "Authentication Failed! Please check User Name & Password..";
            }
        }
    }
}

Change Password form

<div class="Pwd_box">
                        <table valign="top">
                            <tr>
                                <td colspan="2">&nbsp;<h2>Change Password</h2><hr></td>
                            </tr>  
                            <tr>
                                <td colspan="2">
                                    <asp:Label ID="lblMsg" runat="server" ForeColor="Red"></asp:Label>
                                </td>
                            </tr>
                            <tr>
                                <td align="left">User Name</td>
                                <td align="left">
                                    <asp:TextBox ID="txtUserID" runat="server" ReadOnly Width="150px"></asp:TextBox>
                                </td>
                            </tr>                                                   
                            <tr>
                                <td align="left">Current Password</td>
                                <td align="left">
                                    <asp:TextBox ID="txtCurrPwd" runat="server" TextMode="Password" Width="150px"></asp:TextBox>
                                </td>
                            </tr>
                            <tr>
                                <td align="left">New Password</td>
                                <td align="left">
                                    <asp:TextBox ID="txtNewPwd" runat="server" TextMode="Password" Width="150px"></asp:TextBox>
                                </td>
                            </tr>
                            <tr>
                                <td align="left">Confirm Password</td>
                                <td align="left">
                                    <asp:TextBox ID="txtConfirmPwd" runat="server" TextMode="Password" Width="150px"></asp:TextBox>
                                </td>
                            </tr>
                            <tr>
                                <td align="left">&nbsp;</td>
                                <td align="right">
                                    <asp:Button ID="Button1" class="main_container" runat="server" Text="Reset" 
                                        onclick="Button1_Click" />
                                </td>
                            </tr>
                        </table>
                    </div>

Code behind window of login form

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using eCanionCore;
using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;

namespace eCanionPortal
{
    public partial class ChangePwd : System.Web.UI.Page
    {
        AuthenticateUsers au;
        bool isValidUser;
        string varRetMsg;
        protected void Page_Load(object sender, EventArgs e)
        {

            if (Session != null)
            {
                txtUserID.Text = Session["UserName"].ToString().Trim();
            }
            else
            {
                Response.Redirect("logout.aspx");
            }
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            lblMsg.Text = "";

            au = new AuthenticateUsers();
            isValidUser = au.ValidateUser("ecanion.com", txtUserID.Text, txtCurrPwd.Text);
            if (isValidUser == true)
            {
                varRetMsg = au.ResetPassword("ecanion.com", txtUserID.Text.Trim(), txtCurrPwd.Text.Trim(), txtNewPwd.Text.Trim());
                if (varRetMsg == "0")
                {
                    Response.Redirect("logout.aspx");
                }
                else
                {
                    lblMsg.Text = varRetMsg.ToString();
                }
            }
            else
            {
                lblMsg.Text = "Authentication Failed!";
            }     

        }
    }
}

If you have any question regarding this Codes please comments, I will assist you to overcome the issues.




Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>