Click here to Skip to main content
15,884,083 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I originally got this working on a ASP.net application (non MVC) but now that I have to change over to MVC I do not know how to adapt my old code. For reference, I am using the stock website you get for the application (needed to be quick and dirty) and I am also sewing in Zurb's Foundation framework. This is also C# based.

Here is the old way that worked:

LOGIN.ASPX
C#
<form id="Login" method="post"  runat="server">
          <fieldset>
              <legend>Please login</legend>
                    <asp:Label ID="errorLabel" Runat=server ForeColor=#ff3300></asp:Label><br>

              <div class="row">
                  <div class="large-12 columns">
                      <label>Domain:</label>
                      <asp:TextBox ID="txtDomain" Runat=server placeholder="Human Check: Please type WORKGROUP"></asp:TextBox>
                  </div>
              </div>
              <div class="row">
                  <div class="large-12 columns">
                      <label>Username:</label>
                       <asp:TextBox ID=txtUsername Runat=server ></asp:TextBox>
                  </div>
              </div>
              <div class="row">
                  <div class="large-12 columns">
                      <label>Password:</label>
                        <asp:TextBox ID="txtPassword" Runat=server TextMode=Password></asp:TextBox><br>
                  </div>
              </div>
              <div class="row">
                  <div class="large-6 columns">
<%--                      <a href="#" class="button" id="btnLogin"  runat="server"  önclick="Login_Click">Submit</a>--%>
                      <asp:Button ID="Button1" Runat=server Text="Login" OnClick="Login_Click" CssClass="button"></asp:Button>
                  </div>
                  <div class="large-6 columns">
                    <br />
                      <asp:CheckBox ID=chkPersist Runat=server /> Remember Me                  
                  </div>

              </div>
          </fieldset>
      </form>


Here was the script below (same page) that worked.

C#
<script  runat="server">
void Login_Click(object sender, EventArgs e)
{
  string adPath = "LDAP://DC03/DC=Meowmeow,dc=com"; //Path to your LDAP directory server
  Legend_Forms_Manager.LdapAuthentication adAuth = new Legend_Forms_Manager.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 was the LdapAuthentication.cs

C#
using System;
using System.Text;
using System.Collections;
using System.DirectoryServices;

namespace Legend_Forms_Manager
{
    public class LdapAuthentication
    {
        private string _path;
        private string _filterAttribute;

        public LdapAuthentication(string path)
        {
            _path = path;
        }

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

            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("|");
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Error obtaining group names. " + ex.Message);
            }
            return groupNames.ToString();
        }
    }
}


I included the following references:

~ System.DirectoryServices

I am having EXTREME difficulty finding anywhere that has any iota of consistency in a tutorial that does not date back to 2008 or so.

If you can please help me... I have everything out here and now it just needs to be translated, I think.
Posted
Comments
dfarr1 7-Aug-13 18:36pm    
I added the .aspx and .cs from the old to the new, added ADConnectionString to web.config, and added tokens to the .cs and the .aspx to prevent cross-site scripting (it forced me to as per the references). You can now get to the page, fill in the info, but when you click 'Submit' it blanks the page and does nothing. Still need help.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900