Authenticate against Active Directory

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Jon

    #1

    Authenticate against Active Directory

    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.Director yServices 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

  • ABHIJIT B

    #2
    Re: Authenticate against Active Directory

    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 GetSearchUserDa ta()
    {
    try
    {
    //Bind Search UserList grid as per user entered

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

    string ActiveDirectory Server =
    Convert.ToStrin g(Configuration Manager.AppSett ings["ActiveDirector yServer"]);

    // User that can access domain user details
    string ADUserName =
    Convert.ToStrin g(Configuration Manager.AppSett ings["ADUserName "]);
    string ADUserPassword =
    Convert.ToStrin g(Configuration Manager.AppSett ings["ADUserPassword "]);

    DirectoryEntry entry = new
    DirectoryEntry( ActiveDirectory Server, ADUserName, ADUserPassword) ;
    DirectorySearch er ds = new DirectorySearch er(entry);

    ds.Filter = "(&(objectClass =user)(objectCl ass=person))";
    if (loginName != "")
    {
    ds.Filter = ds.Filter.Remov e(ds.Filter.Len gth - 1, 1);
    ds.Filter += "(sAMAccountNam e=" + loginName.Trim( ) +
    "*))";
    }
    if (firstName != "")
    {
    ds.Filter = ds.Filter.Remov e(ds.Filter.Len gth - 1, 1);
    ds.Filter += "(givenName =" + firstName.Trim( ) + "*))";
    }
    if (lastName != "")
    {
    ds.Filter = ds.Filter.Remov e(ds.Filter.Len gth - 1, 1);
    ds.Filter += "(sn=" + lastName.Trim() + "*))";
    }

    dtSearchUserLis t.Columns.Clear ();
    dtSearchUserLis t.Columns.Add(n ew DataColumn("Log inName",
    typeof(string)) );
    dtSearchUserLis t.Columns.Add(n ew DataColumn("Fir stName",
    typeof(string)) );
    dtSearchUserLis t.Columns.Add(n ew DataColumn("Las tName",
    typeof(string)) );

    foreach (SearchResult sr in ds.FindAll())
    {
    DataRow row = dtSearchUserLis t.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.Repla ce("'", "");
    row["LastName"] = lastname.Replac e("'", "");
    row["LoginName"] = sr.Properties["SamAccountName "]
    [0].ToString();
    dtSearchUserLis t.Rows.Add(row) ;
    }

    if (dtSearchUserLi st != null &&
    dtSearchUserLis t.Rows.Count 0)
    {
    dtSearchUserLis t.DefaultView.S ort = "LoginName ASC,
    FirstName ASC, LastName ASC";
    dgADUserList.Da taSource = dtSearchUserLis t;
    dgADUserList.Da taBind();
    blSUSearchSuces s = true;
    lblSUErrorText. Text = "";
    }
    else
    {
    dtSearchUserLis t.Columns.Clear ();
    dtSearchUserLis t.Columns.Add(n ew DataColumn("Sel ect",
    typeof(string)) );
    dtSearchUserLis t.Columns.Add(n ew
    DataColumn("Log inName", typeof(string)) );
    dtSearchUserLis t.Columns.Add(n ew
    DataColumn("Fir stName", typeof(string)) );
    dtSearchUserLis t.Columns.Add(n ew
    DataColumn("Las tName", typeof(string)) );
    dgADUserList.Da taSource = dtSearchUserLis t;
    dgADUserList.Da taBind();
    lblSUErrorText. Text = ErrorLog.GetTex t("NoUsers");
    blSUSearchSuces s = false;
    }
    }
    catch (Exception ex)
    {
    blSUSearchSuces s = false;
    TraceSUError.Lo g("\nAn error occurred while fetching user
    details.\nExcep tion occurred : " + ex.Message);
    strURL = "ErrorPage.aspx ?strErrPageName =SearchUsers.as px";
    Response.Redire ct(strURL, false);
    }

    return blSUSearchSuces s;
    }

    Also you can check login user details,

    IIdentity WinId = HttpContext.Cur rent.User.Ident ity;
    WindowsIdentity wi = (WindowsIdentit y)WinId;

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

    if (ValidLoginUser Data(strDCHLogi nID)) //check user is
    present in Database

    Regards,
    Abhijit B

    On May 7, 12:59 pm, "Jon" <rosenb...@main streams.comwrot e:
    I am modifying an app for a customer in ASP.Net 1.1. The app is running ona
    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 havinga
    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.Director yServices 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

    Comment

    • Jon

      #3
      Re: Authenticate against Active Directory

      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 ActiveDirectory Server variable - would that just be the windows
      machine name of the AD server or a full domain name, etc?

      Thanks, again
      Jon



      "ABHIJIT B" <abhijitbavdhan kar@gmail.comwr ote in message
      news:4f07c019-1272-40f4-8ff3-3ca95b6bd586@e5 3g2000hsa.googl egroups.com...
      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 GetSearchUserDa ta()
      {
      try
      {
      //Bind Search UserList grid as per user entered

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

      string ActiveDirectory Server =
      Convert.ToStrin g(Configuration Manager.AppSett ings["ActiveDirector yServer"]);

      // User that can access domain user details
      string ADUserName =
      Convert.ToStrin g(Configuration Manager.AppSett ings["ADUserName "]);
      string ADUserPassword =
      Convert.ToStrin g(Configuration Manager.AppSett ings["ADUserPassword "]);

      DirectoryEntry entry = new
      DirectoryEntry( ActiveDirectory Server, ADUserName, ADUserPassword) ;
      DirectorySearch er ds = new DirectorySearch er(entry);

      ds.Filter = "(&(objectClass =user)(objectCl ass=person))";
      if (loginName != "")
      {
      ds.Filter = ds.Filter.Remov e(ds.Filter.Len gth - 1, 1);
      ds.Filter += "(sAMAccountNam e=" + loginName.Trim( ) +
      "*))";
      }
      if (firstName != "")
      {
      ds.Filter = ds.Filter.Remov e(ds.Filter.Len gth - 1, 1);
      ds.Filter += "(givenName =" + firstName.Trim( ) + "*))";
      }
      if (lastName != "")
      {
      ds.Filter = ds.Filter.Remov e(ds.Filter.Len gth - 1, 1);
      ds.Filter += "(sn=" + lastName.Trim() + "*))";
      }

      dtSearchUserLis t.Columns.Clear ();
      dtSearchUserLis t.Columns.Add(n ew DataColumn("Log inName",
      typeof(string)) );
      dtSearchUserLis t.Columns.Add(n ew DataColumn("Fir stName",
      typeof(string)) );
      dtSearchUserLis t.Columns.Add(n ew DataColumn("Las tName",
      typeof(string)) );

      foreach (SearchResult sr in ds.FindAll())
      {
      DataRow row = dtSearchUserLis t.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.Repla ce("'", "");
      row["LastName"] = lastname.Replac e("'", "");
      row["LoginName"] = sr.Properties["SamAccountName "]
      [0].ToString();
      dtSearchUserLis t.Rows.Add(row) ;
      }

      if (dtSearchUserLi st != null &&
      dtSearchUserLis t.Rows.Count 0)
      {
      dtSearchUserLis t.DefaultView.S ort = "LoginName ASC,
      FirstName ASC, LastName ASC";
      dgADUserList.Da taSource = dtSearchUserLis t;
      dgADUserList.Da taBind();
      blSUSearchSuces s = true;
      lblSUErrorText. Text = "";
      }
      else
      {
      dtSearchUserLis t.Columns.Clear ();
      dtSearchUserLis t.Columns.Add(n ew DataColumn("Sel ect",
      typeof(string)) );
      dtSearchUserLis t.Columns.Add(n ew
      DataColumn("Log inName", typeof(string)) );
      dtSearchUserLis t.Columns.Add(n ew
      DataColumn("Fir stName", typeof(string)) );
      dtSearchUserLis t.Columns.Add(n ew
      DataColumn("Las tName", typeof(string)) );
      dgADUserList.Da taSource = dtSearchUserLis t;
      dgADUserList.Da taBind();
      lblSUErrorText. Text = ErrorLog.GetTex t("NoUsers");
      blSUSearchSuces s = false;
      }
      }
      catch (Exception ex)
      {
      blSUSearchSuces s = false;
      TraceSUError.Lo g("\nAn error occurred while fetching user
      details.\nExcep tion occurred : " + ex.Message);
      strURL = "ErrorPage.aspx ?strErrPageName =SearchUsers.as px";
      Response.Redire ct(strURL, false);
      }

      return blSUSearchSuces s;
      }

      Also you can check login user details,

      IIdentity WinId = HttpContext.Cur rent.User.Ident ity;
      WindowsIdentity wi = (WindowsIdentit y)WinId;

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

      if (ValidLoginUser Data(strDCHLogi nID)) //check user is
      present in Database

      Regards,
      Abhijit B

      On May 7, 12:59 pm, "Jon" <rosenb...@main streams.comwrot e:
      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.Director yServices 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

      Comment

      • ABHIJIT B

        #4
        Re: Authenticate against Active Directory

        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 ActiveDirectory Server variable - would that just be the
        windows
        machine name of the AD server or a full domain name, etc?

        ActiveDirectory Server is domainname

        In Web.Config you can mention for example :-

        <add key="ActiveDire ctoryServer" value="LDAP://xyznet.org" />
        domainname
        <add key="ADUserName " value="xyz\jon" /domainname\user name or
        simply username
        <add key="ADUserPass word" value="password " />

        Regards,
        Abhijit B

        On May 8, 7:49 am, "Jon" <rosenb...@main streams.comwrot e:
        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 ActiveDirectory Server variable - would that just be the windows
        machine name of the AD server or a full domain name, etc?
        >
        Thanks, again
        Jon
        >
        "ABHIJIT B" <abhijitbavdhan ...@gmail.comwr ote in message
        >
        news:4f07c019-1272-40f4-8ff3-3ca95b6bd586@e5 3g2000hsa.googl egroups.com...
        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 GetSearchUserDa ta()
            {
                try
                {
                    //Bind Search UserList grid  as per user entered
        >
                    string loginName = txtSULoginName. Text;
                    string firstName = txtSUFirstName. Text;
                    string lastName = txtSULastName.T ext;
        >
                    string ActiveDirectory Server =
        Convert.ToStrin g(Configuration Manager.AppSett ings["ActiveDirector yServer"])­;
        >
                   // User that can access domain user details
                    string ADUserName =
        Convert.ToStrin g(Configuration Manager.AppSett ings["ADUserName "]);
                    string ADUserPassword =
        Convert.ToStrin g(Configuration Manager.AppSett ings["ADUserPassword "]);
        >
                    DirectoryEntry entry = new
        DirectoryEntry( ActiveDirectory Server, ADUserName, ADUserPassword) ;
                    DirectorySearch er ds = new DirectorySearch er(entry);
        >
                    ds.Filter = "(&(objectClass =user)(objectCl ass=person))";
                    if (loginName != "")
                    {
                        ds.Filter = ds.Filter.Remov e(ds.Filter.Len gth - 1, 1);
                        ds.Filter += "(sAMAccountNam e=" + loginName.Trim( ) +
        "*))";
                    }
                    if (firstName != "")
                    {
                        ds.Filter = ds.Filter.Remov e(ds.Filter.Len gth - 1, 1);
                        ds.Filter += "(givenName =" + firstName..Trim () + "*))";
                    }
                    if (lastName != "")
                    {
                        ds.Filter = ds.Filter.Remov e(ds.Filter.Len gth - 1, 1);
                        ds.Filter += "(sn=" + lastName.Trim() + "*))";
                    }
        >
                    dtSearchUserLis t.Columns.Clear ();
                    dtSearchUserLis t.Columns.Add(n ew DataColumn("Log inName",
        typeof(string)) );
                    dtSearchUserLis t.Columns.Add(n ew DataColumn("Fir stName",
        typeof(string)) );
                    dtSearchUserLis t.Columns.Add(n ew DataColumn("Las tName",
        typeof(string)) );
        >
                    foreach (SearchResult sr in ds.FindAll())
                    {
                        DataRow row = dtSearchUserLis t.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.Repla ce("'", "");
                        row["LastName"] = lastname.Replac e("'", "");
                        row["LoginName"] = sr.Properties["SamAccountName "]
        [0].ToString();
                        dtSearchUserLis t.Rows.Add(row) ;
                    }
        >
                    if (dtSearchUserLi st != null &&
        dtSearchUserLis t.Rows.Count 0)
                    {
                        dtSearchUserLis t.DefaultView.S ort = "LoginName ASC,
        FirstName ASC, LastName ASC";
                        dgADUserList.Da taSource = dtSearchUserLis t;
                        dgADUserList.Da taBind();
                        blSUSearchSuces s = true;
                        lblSUErrorText. Text = "";
                    }
                    else
                    {
                        dtSearchUserLis t.Columns.Clear ();
                        dtSearchUserLis t.Columns.Add(n ew DataColumn("Sel ect",
        typeof(string)) );
                        dtSearchUserLis t.Columns.Add(n ew
        DataColumn("Log inName", typeof(string)) );
                        dtSearchUserLis t.Columns.Add(n ew
        DataColumn("Fir stName", typeof(string)) );
                        dtSearchUserLis t.Columns.Add(n ew
        DataColumn("Las tName", typeof(string)) );
                        dgADUserList.Da taSource = dtSearchUserLis t;
                        dgADUserList.Da taBind();
                        lblSUErrorText. Text = ErrorLog.GetTex t("NoUsers");
                        blSUSearchSuces s = false;
                    }
                }
                catch (Exception ex)
                {
                    blSUSearchSuces s = false;
                    TraceSUError.Lo g("\nAn error occurred while fetching user
        details.\nExcep tion occurred : " + ex.Message);
                    strURL = "ErrorPage.aspx ?strErrPageName =SearchUsers.as px";
                    Response.Redire ct(strURL, false);
                }
        >
                return blSUSearchSuces s;
            }
        >
        Also you can check login user details,
        >
        IIdentity WinId = HttpContext.Cur rent.User.Ident ity;
                        WindowsIdentity wi = (WindowsIdentit y)WinId;
        >
                        strDCHLoginID = wi.Name.Split(' \\')[1];
                        hidDHLoginID.Va lue = wi.Name.Split(' \\')
        [1];
        >
                        if (ValidLoginUser Data(strDCHLogi nID)) //check user is
        present in Database
        >
        Regards,
        Abhijit B
        >
        On May 7, 12:59 pm, "Jon" <rosenb...@main streams.comwrot e:
        >
        >
        >
        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.Director yServices 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 -

        Comment

        • Andy

          #5
          Re: Authenticate against Active Directory

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

          String ldapPath=
          Convert.ToStrin g( ConfigurationMa nager.AppSettin gs["ActiveDirector yServer"] );
          String domainAndUserna me = String.Format( "{0}\\{1}", domainName,
          userName); // values from login page
          try
          {
          // Authenticate the userName/password against an LDAP server
          System.Director yServices.Direc toryEntry dirEntry = new
          System.Director yServices.Direc toryEntry( ldapPath, domainAndUserna me,
          password );
          Object obj = dirEntry.Native Object; // 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


          Comment

          Working...