Help Needed: New to AD

Last post 05-04-2008 11:10 AM by TBarton. 2 replies.

Sort Posts:

  • Help Needed: New to AD

    04-29-2008, 10:08 AM
    • Loading...
    • wtkearns
    • Joined on 11-01-2006, 7:50 PM
    • Posts 4

    My first ad project and I'm lost, hope y'all can help point me in the right direction.
    I'll post my code below but here's my problem in a nutshell.

    I have been successful in authenticating users in Active Directory with my code and using impersonation on IIS 7.
    But now I need to pull user information out of AD (address, phone number, email, etc) and I don't know where to start.

    Any help much appreciated.

    Here is my form "Logon.aspx":
    *********************************************************************************************************************
    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Logon.aspx.cs" Inherits="Logon" %>
    <%@ Import Namespace="FormsAuth" %>

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head id="Head1" runat="server">
        <title>Untitled Page</title>
    </head>
      <body> 
        <form id="Login" method="post" runat="server">
          <asp:Label ID="Label1" Runat=server >Domain:</asp:Label>
          <asp:TextBox ID="txtDomain" Runat=server >mydomain</asp:TextBox><br>   
          <asp:Label ID="Label2" Runat=server >Username:</asp:Label>
          <asp:TextBox ID=txtUsername Runat=server ></asp:TextBox><br>
          <asp:Label ID="Label3" Runat=server >Password:</asp:Label>
          <asp:TextBox ID="txtPassword" Runat=server TextMode=Password></asp:TextBox><br>
          <asp:Button ID="btnLogin" Runat=server Text="Login" OnClick="Login_Click"></asp:Button><br>
          <asp:Label ID="errorLabel" Runat=server ForeColor=#ff3300></asp:Label><br>
          <asp:CheckBox ID=chkPersist Runat=server Text="Persist Cookie" />
        </form> 
      </body>
    </html>
    <script runat=server>
    void Login_Click(Object sender, EventArgs e)
    {
      String adPath = "LDAP://mydomain.com"; //Fully-qualified Domain Name
      LdapAuthentication adAuth = new LdapAuthentication(adPath);
      try
      {
        if(true == adAuth.IsAuthenticated(txtDomain.Text, txtUsername.Text, txtPassword.Text))
        {
          String groups = adAuth.GetGroups();

          //Create the ticket, and add the groups.
          bool isCookiePersistent = chkPersist.Checked;
          FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1,  txtUsername.Text,
       DateTime.Now, DateTime.Now.AddMinutes(60), isCookiePersistent, groups);
     
          //Encrypt the ticket.
          String encryptedTicket = FormsAuthentication.Encrypt(authTicket);
      
          //Create a cookie, and then add the encrypted ticket to the cookie as data.
          HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);

          if(true == isCookiePersistent)
       authCookie.Expires = authTicket.Expiration;
        
          //Add the cookie to the outgoing cookies collection.
          Response.Cookies.Add(authCookie);  

          //You can redirect now.
          Response.Redirect(FormsAuthentication.GetRedirectUrl(txtUsername.Text, false));
        }
        else
        {
          errorLabel.Text = "Authentication did not succeed. Check user name and password.";
        }
      }
      catch(Exception ex)
      {
        errorLabel.Text = "Error authenticating. " + ex.Message;
      }
    }
    </script>

    Here is my C# class file LdapAuthentication.cs:
    *********************************************************************************************************************

    using System;
    using System.Text;
    using System.Collections;
    using System.DirectoryServices;
    using System.DirectoryServices.ActiveDirectory;

    namespace FormsAuth
    {
        public class LdapAuthentication
        {
            private String _path;
            private String _filterAttribute;

            public LdapAuthentication(String path)
            {
                _path = "LDAP://DC=mydomain,DC=com";
            }

            public bool IsAuthenticated(String domain, String username, String pwd)
            {
                String domainAndUsername = domain + @"\" + username;
                DirectoryEntry entry = new DirectoryEntry(_path, domainAndUsername, pwd);

                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.
                    _path = result.Path;
                    _filterAttribute = (String)result.Properties["cn"][0];
                }
                catch (Exception ex)
                {
                    throw new Exception("Error authenticating user. " + ex.Message);
                }

                return true;
            }

            public String GetGroups()
            {
                DirectorySearcher search = new DirectorySearcher(_path);
                search.Filter = "(cn=" + _filterAttribute + ")";
                search.PropertiesToLoad.Add("memberOf");
                StringBuilder groupNames = new StringBuilder();

                try
                {
                    SearchResult result = search.FindOne();

                    int propertyCount = result.Properties["memberOf"].Count;

                    String dn;
                    int equalsIndex, commaIndex;

                    for (int propertyCounter = 0; propertyCounter < propertyCount; propertyCounter++)
                    {
                        dn = (String)result.Properties["memberOf"][propertyCounter];

                        equalsIndex = dn.IndexOf("=", 1);
                        commaIndex = dn.IndexOf(",", 1);
                        if (-1 == equalsIndex)
                        {
                            return null;
                        }

                        groupNames.Append(dn.Substring((equalsIndex + 1), (commaIndex - equalsIndex) - 1));
                        groupNames.Append("|");
                        Console.WriteLine(groupNames + ": " + groupNames.ToString());
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception("Error obtaining group names. " + ex.Message);
                }
                return groupNames.ToString();
            }
        }
    }

    -b-
  • Re: Help Needed: New to AD

    04-30-2008, 4:20 AM
    • Loading...
    • johram
    • Joined on 06-13-2006, 6:36 AM
    • Sweden
    • Posts 1,865
    • Moderator

    I'd suggest you start with Ryan Dunn's Common Patterns in System.DirectoryServices

    If this post was useful to you, please mark it as answer. Thank you!
  • Re: Help Needed: New to AD

    05-04-2008, 11:10 AM
    • Loading...
    • TBarton
    • Joined on 03-17-2008, 2:38 PM
    • Posts 68

    Just out of curiosity,

    How is this working for you?

    I am using the same code only I moved the script out and into the code behind page and am using a vb version of LdapAuthentication.

    The problem I have now is that is authenticates and redirects me to my page but if you try to navigate to anyother page on the site it forces you to log in again which is as I'm sure you can imagine not the way I had hoped it would work.

    Thanks,

    Ty

Page 1 of 1 (3 items)