Authenticate against Active Directory

J

Jon

I am modifying an app for a customer in ASP.Net 1.1. The app is running on a
server outside their network, yet they want to authenticate users against
their internal active directory set up (they will open the necessary ports).

So, I have a simple login page with username and password, and then I will
authenticate that credentials entered against their AD server. I am having a
real hard time figuring this out. We can't use Windows Forms Auth, so I need
to do it all manually in code.

On the System.DirectoryServices namespace I can't find what methods I need
to connect to their AD using SSL and then to authenticate the user. I've
found a lot online using Forms Auth and ADAM, but nothing has really fit
what I'm doing.

Could anyone point me to a tutorial or outline what methods, etc I need to
use to accomplish this?

Thank you so much!
Jon
 
A

ABHIJIT B

Hi Jon,

I did AD authentication in one of my page in ASP.NET 2.0 , you can
find same in 1.1

/// <summary>
/// This will get user list.
/// </summary>
protected bool GetSearchUserData()
{
try
{
//Bind Search UserList grid as per user entered

string loginName = txtSULoginName.Text;
string firstName = txtSUFirstName.Text;
string lastName = txtSULastName.Text;

string ActiveDirectoryServer =
Convert.ToString(ConfigurationManager.AppSettings["ActiveDirectoryServer"]);

// User that can access domain user details
string ADUserName =
Convert.ToString(ConfigurationManager.AppSettings["ADUserName"]);
string ADUserPassword =
Convert.ToString(ConfigurationManager.AppSettings["ADUserPassword"]);

DirectoryEntry entry = new
DirectoryEntry(ActiveDirectoryServer, ADUserName, ADUserPassword);
DirectorySearcher ds = new DirectorySearcher(entry);

ds.Filter = "(&(objectClass=user)(objectClass=person))";
if (loginName != "")
{
ds.Filter = ds.Filter.Remove(ds.Filter.Length - 1, 1);
ds.Filter += "(sAMAccountName=" + loginName.Trim() +
"*))";
}
if (firstName != "")
{
ds.Filter = ds.Filter.Remove(ds.Filter.Length - 1, 1);
ds.Filter += "(givenName=" + firstName.Trim() + "*))";
}
if (lastName != "")
{
ds.Filter = ds.Filter.Remove(ds.Filter.Length - 1, 1);
ds.Filter += "(sn=" + lastName.Trim() + "*))";
}

dtSearchUserList.Columns.Clear();
dtSearchUserList.Columns.Add(new DataColumn("LoginName",
typeof(string)));
dtSearchUserList.Columns.Add(new DataColumn("FirstName",
typeof(string)));
dtSearchUserList.Columns.Add(new DataColumn("LastName",
typeof(string)));

foreach (SearchResult sr in ds.FindAll())
{
DataRow row = dtSearchUserList.NewRow();
string name = sr.Properties["Name"][0].ToString();
string firstname = "";
string lastname = "";

if (name.Length == 0)
{
firstname = "";
lastname = "";
}
else if (name.IndexOf(",") != -1)
{
iActualLength = name.Length;
iLength = name.IndexOf(",") + 2;

if (iActualLength < iLength)
{
firstname = "";
lastname = name;
}
else
{
firstname = name.Substring(name.IndexOf(",") +
2);
lastname = name.Substring(0,
name.IndexOf(","));
}
}
else if (name.IndexOf(" ") != -1)
{
iActualLength = name.Length;
iLength = name.IndexOf(" ") + 1;

if (iActualLength < iLength)
{
firstname = "";
lastname = name;
}
else
{
lastname = name.Substring(name.IndexOf(" ") +
1);
firstname = name.Substring(0, name.IndexOf("
"));
}
}
else
{
firstname = "";
lastname = name;
}
row["FirstName"] = firstname.Replace("'", "");
row["LastName"] = lastname.Replace("'", "");
row["LoginName"] = sr.Properties["SamAccountName"]
[0].ToString();
dtSearchUserList.Rows.Add(row);
}

if (dtSearchUserList != null &&
dtSearchUserList.Rows.Count > 0)
{
dtSearchUserList.DefaultView.Sort = "LoginName ASC,
FirstName ASC, LastName ASC";
dgADUserList.DataSource = dtSearchUserList;
dgADUserList.DataBind();
blSUSearchSucess = true;
lblSUErrorText.Text = "";
}
else
{
dtSearchUserList.Columns.Clear();
dtSearchUserList.Columns.Add(new DataColumn("Select",
typeof(string)));
dtSearchUserList.Columns.Add(new
DataColumn("LoginName", typeof(string)));
dtSearchUserList.Columns.Add(new
DataColumn("FirstName", typeof(string)));
dtSearchUserList.Columns.Add(new
DataColumn("LastName", typeof(string)));
dgADUserList.DataSource = dtSearchUserList;
dgADUserList.DataBind();
lblSUErrorText.Text = ErrorLog.GetText("NoUsers");
blSUSearchSucess = false;
}
}
catch (Exception ex)
{
blSUSearchSucess = false;
TraceSUError.Log("\nAn error occurred while fetching user
details.\nException occurred : " + ex.Message);
strURL = "ErrorPage.aspx?strErrPageName=SearchUsers.aspx";
Response.Redirect(strURL, false);
}

return blSUSearchSucess;
}

Also you can check login user details,

IIdentity WinId = HttpContext.Current.User.Identity;
WindowsIdentity wi = (WindowsIdentity)WinId;

strDCHLoginID = wi.Name.Split('\\')[1];
hidDHLoginID.Value = wi.Name.Split('\\')
[1];

if (ValidLoginUserData(strDCHLoginID)) //check user is
present in Database

Regards,
Abhijit B
 
J

Jon

Thank you! I will try this and see if I can get it working. Two questions -
the AppSettings AD user and pass - do those need to be for the domain admin?
Second, the ActiveDirectoryServer variable - would that just be the windows
machine name of the AD server or a full domain name, etc?

Thanks, again
Jon



Hi Jon,

I did AD authentication in one of my page in ASP.NET 2.0 , you can
find same in 1.1

/// <summary>
/// This will get user list.
/// </summary>
protected bool GetSearchUserData()
{
try
{
//Bind Search UserList grid as per user entered

string loginName = txtSULoginName.Text;
string firstName = txtSUFirstName.Text;
string lastName = txtSULastName.Text;

string ActiveDirectoryServer =
Convert.ToString(ConfigurationManager.AppSettings["ActiveDirectoryServer"]);

// User that can access domain user details
string ADUserName =
Convert.ToString(ConfigurationManager.AppSettings["ADUserName"]);
string ADUserPassword =
Convert.ToString(ConfigurationManager.AppSettings["ADUserPassword"]);

DirectoryEntry entry = new
DirectoryEntry(ActiveDirectoryServer, ADUserName, ADUserPassword);
DirectorySearcher ds = new DirectorySearcher(entry);

ds.Filter = "(&(objectClass=user)(objectClass=person))";
if (loginName != "")
{
ds.Filter = ds.Filter.Remove(ds.Filter.Length - 1, 1);
ds.Filter += "(sAMAccountName=" + loginName.Trim() +
"*))";
}
if (firstName != "")
{
ds.Filter = ds.Filter.Remove(ds.Filter.Length - 1, 1);
ds.Filter += "(givenName=" + firstName.Trim() + "*))";
}
if (lastName != "")
{
ds.Filter = ds.Filter.Remove(ds.Filter.Length - 1, 1);
ds.Filter += "(sn=" + lastName.Trim() + "*))";
}

dtSearchUserList.Columns.Clear();
dtSearchUserList.Columns.Add(new DataColumn("LoginName",
typeof(string)));
dtSearchUserList.Columns.Add(new DataColumn("FirstName",
typeof(string)));
dtSearchUserList.Columns.Add(new DataColumn("LastName",
typeof(string)));

foreach (SearchResult sr in ds.FindAll())
{
DataRow row = dtSearchUserList.NewRow();
string name = sr.Properties["Name"][0].ToString();
string firstname = "";
string lastname = "";

if (name.Length == 0)
{
firstname = "";
lastname = "";
}
else if (name.IndexOf(",") != -1)
{
iActualLength = name.Length;
iLength = name.IndexOf(",") + 2;

if (iActualLength < iLength)
{
firstname = "";
lastname = name;
}
else
{
firstname = name.Substring(name.IndexOf(",") +
2);
lastname = name.Substring(0,
name.IndexOf(","));
}
}
else if (name.IndexOf(" ") != -1)
{
iActualLength = name.Length;
iLength = name.IndexOf(" ") + 1;

if (iActualLength < iLength)
{
firstname = "";
lastname = name;
}
else
{
lastname = name.Substring(name.IndexOf(" ") +
1);
firstname = name.Substring(0, name.IndexOf("
"));
}
}
else
{
firstname = "";
lastname = name;
}
row["FirstName"] = firstname.Replace("'", "");
row["LastName"] = lastname.Replace("'", "");
row["LoginName"] = sr.Properties["SamAccountName"]
[0].ToString();
dtSearchUserList.Rows.Add(row);
}

if (dtSearchUserList != null &&
dtSearchUserList.Rows.Count > 0)
{
dtSearchUserList.DefaultView.Sort = "LoginName ASC,
FirstName ASC, LastName ASC";
dgADUserList.DataSource = dtSearchUserList;
dgADUserList.DataBind();
blSUSearchSucess = true;
lblSUErrorText.Text = "";
}
else
{
dtSearchUserList.Columns.Clear();
dtSearchUserList.Columns.Add(new DataColumn("Select",
typeof(string)));
dtSearchUserList.Columns.Add(new
DataColumn("LoginName", typeof(string)));
dtSearchUserList.Columns.Add(new
DataColumn("FirstName", typeof(string)));
dtSearchUserList.Columns.Add(new
DataColumn("LastName", typeof(string)));
dgADUserList.DataSource = dtSearchUserList;
dgADUserList.DataBind();
lblSUErrorText.Text = ErrorLog.GetText("NoUsers");
blSUSearchSucess = false;
}
}
catch (Exception ex)
{
blSUSearchSucess = false;
TraceSUError.Log("\nAn error occurred while fetching user
details.\nException occurred : " + ex.Message);
strURL = "ErrorPage.aspx?strErrPageName=SearchUsers.aspx";
Response.Redirect(strURL, false);
}

return blSUSearchSucess;
}

Also you can check login user details,

IIdentity WinId = HttpContext.Current.User.Identity;
WindowsIdentity wi = (WindowsIdentity)WinId;

strDCHLoginID = wi.Name.Split('\\')[1];
hidDHLoginID.Value = wi.Name.Split('\\')
[1];

if (ValidLoginUserData(strDCHLoginID)) //check user is
present in Database

Regards,
Abhijit B
 
A

ABHIJIT B

Hi Jon,

Two questions -
the AppSettings AD user and pass - do those need to be for the domain
admin?

It can be any user who can access all user details present in your
domain(e.g. firstname, lastname, email, loginid etc.).
If your site is hosted in QA/Production environment I suggest to have
Admin user credentials.

Second, the ActiveDirectoryServer variable - would that just be the
windows
machine name of the AD server or a full domain name, etc?

ActiveDirectoryServer is domainname

In Web.Config you can mention for example :-

<add key="ActiveDirectoryServer" value="LDAP://xyznet.org" />
domainname
<add key="ADUserName" value="xyz\jon" /> domainname\username or
simply username
<add key="ADUserPassword" value="password" />

Regards,
Abhijit B

Thank you! I will try this and see if I can get it working. Two questions -
the AppSettings AD user and pass - do those need to be for the domain admin?
Second, the ActiveDirectoryServer variable - would that just be the windows
machine name of the AD server or a full domain name, etc?

Thanks, again
Jon


Hi Jon,

I did AD authentication in one of my page in ASP.NET 2.0 , you can
find same in 1.1

/// <summary>
    /// This will get user list.
    /// </summary>
    protected bool GetSearchUserData()
    {
        try
        {
            //Bind Search UserList grid  as per user entered

            string loginName = txtSULoginName.Text;
            string firstName = txtSUFirstName.Text;
            string lastName = txtSULastName.Text;

            string ActiveDirectoryServer =
Convert.ToString(ConfigurationManager.AppSettings["ActiveDirectoryServer"])­;

           // User that can access domain user details
            string ADUserName =
Convert.ToString(ConfigurationManager.AppSettings["ADUserName"]);
            string ADUserPassword =
Convert.ToString(ConfigurationManager.AppSettings["ADUserPassword"]);

            DirectoryEntry entry = new
DirectoryEntry(ActiveDirectoryServer, ADUserName, ADUserPassword);
            DirectorySearcher ds = new DirectorySearcher(entry);

            ds.Filter = "(&(objectClass=user)(objectClass=person))";
            if (loginName != "")
            {
                ds.Filter = ds.Filter.Remove(ds.Filter.Length - 1, 1);
                ds.Filter += "(sAMAccountName=" + loginName.Trim() +
"*))";
            }
            if (firstName != "")
            {
                ds.Filter = ds.Filter.Remove(ds.Filter.Length - 1, 1);
                ds.Filter += "(givenName=" + firstName..Trim() + "*))";
            }
            if (lastName != "")
            {
                ds.Filter = ds.Filter.Remove(ds.Filter.Length - 1, 1);
                ds.Filter += "(sn=" + lastName.Trim() + "*))";
            }

            dtSearchUserList.Columns.Clear();
            dtSearchUserList.Columns.Add(new DataColumn("LoginName",
typeof(string)));
            dtSearchUserList.Columns.Add(new DataColumn("FirstName",
typeof(string)));
            dtSearchUserList.Columns.Add(new DataColumn("LastName",
typeof(string)));

            foreach (SearchResult sr in ds.FindAll())
            {
                DataRow row = dtSearchUserList.NewRow();
                string name = sr.Properties["Name"][0].ToString();
                string firstname = "";
                string lastname = "";

                if (name.Length == 0)
                {
                    firstname = "";
                    lastname = "";
                }
                else if (name.IndexOf(",") != -1)
                {
                    iActualLength = name.Length;
                    iLength = name.IndexOf(",") + 2;

                    if (iActualLength < iLength)
                    {
                        firstname = "";
                        lastname = name;
                    }
                    else
                    {
                        firstname = name.Substring(name.IndexOf(",") +
2);
                        lastname = name.Substring(0,
name.IndexOf(","));
                    }
                }
                else if (name.IndexOf(" ") != -1)
                {
                    iActualLength = name.Length;
                    iLength = name.IndexOf(" ") + 1;

                    if (iActualLength < iLength)
                    {
                        firstname = "";
                        lastname = name;
                    }
                    else
                    {
                        lastname = name.Substring(name.IndexOf(" ") +
1);
                        firstname = name.Substring(0, name.IndexOf("
"));
                    }
                }
                else
                {
                    firstname = "";
                    lastname = name;
                }
                row["FirstName"] = firstname.Replace("'", "");
                row["LastName"] = lastname.Replace("'", "");
                row["LoginName"] = sr.Properties["SamAccountName"]
[0].ToString();
                dtSearchUserList.Rows.Add(row);
            }

            if (dtSearchUserList != null &&
dtSearchUserList.Rows.Count > 0)
            {
                dtSearchUserList.DefaultView.Sort = "LoginName ASC,
FirstName ASC, LastName ASC";
                dgADUserList.DataSource = dtSearchUserList;
                dgADUserList.DataBind();
                blSUSearchSucess = true;
                lblSUErrorText.Text = "";
            }
            else
            {
                dtSearchUserList.Columns.Clear();
                dtSearchUserList.Columns.Add(new DataColumn("Select",
typeof(string)));
                dtSearchUserList.Columns.Add(new
DataColumn("LoginName", typeof(string)));
                dtSearchUserList.Columns.Add(new
DataColumn("FirstName", typeof(string)));
                dtSearchUserList.Columns.Add(new
DataColumn("LastName", typeof(string)));
                dgADUserList.DataSource = dtSearchUserList;
                dgADUserList.DataBind();
                lblSUErrorText.Text = ErrorLog.GetText("NoUsers");
                blSUSearchSucess = false;
            }
        }
        catch (Exception ex)
        {
            blSUSearchSucess = false;
            TraceSUError.Log("\nAn error occurred while fetching user
details.\nException occurred : " + ex.Message);
            strURL = "ErrorPage.aspx?strErrPageName=SearchUsers.aspx";
            Response.Redirect(strURL, false);
        }

        return blSUSearchSucess;
    }

Also you can check login user details,

IIdentity WinId = HttpContext.Current.User.Identity;
                WindowsIdentity wi = (WindowsIdentity)WinId;

                strDCHLoginID = wi.Name.Split('\\')[1];
                hidDHLoginID.Value = wi.Name.Split('\\')
[1];

                if (ValidLoginUserData(strDCHLoginID)) //check user is
present in Database

Regards,
Abhijit B

I am modifying an app for a customer in ASP.Net 1.1. The app is running on
a
server outside their network, yet they want to authenticate users against
their internal active directory set up (they will open the necessary
ports).
So, I have a simple login page with username and password, and then I will
authenticate that credentials entered against their AD server. I am having
a
real hard time figuring this out. We can't use Windows Forms Auth, so I
need
to do it all manually in code.
On the System.DirectoryServices namespace I can't find what methods I need
to connect to their AD using SSL and then to authenticate the user. I've
found a lot online using Forms Auth and ADAM, but nothing has really fit
what I'm doing.
Could anyone point me to a tutorial or outline what methods, etc I need to
use to accomplish this?
Thank you so much!
Jon- Hide quoted text -

- Show quoted text -
 
A

Andy

If all you want to do is authenticate the userid/password against AD,
here is a very simple solution:

String ldapPath=
Convert.ToString( ConfigurationManager.AppSettings["ActiveDirectoryServer"] );
String domainAndUsername = String.Format( "{0}\\{1}", domainName,
userName); // values from login page
try
{
// Authenticate the userName/password against an LDAP server
System.DirectoryServices.DirectoryEntry dirEntry = new
System.DirectoryServices.DirectoryEntry( ldapPath, domainAndUsername,
password );
Object obj = dirEntry.NativeObject; // bind to the native object to
force authentication
}
catch(Exception ex)
{
return false;
}
return true;


As Abhijit B mentions, the format of the ldapPath is: "LDAP://
<hostname>".
This technique does not require an admin account.

- Andy
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,968
Messages
2,570,154
Members
46,702
Latest member
LukasConde

Latest Threads

Top