{"id":7348,"date":"2014-06-07T02:30:00","date_gmt":"2014-06-07T02:30:00","guid":{"rendered":"https:\/\/unknownerror.org\/index.php\/2014\/06\/07\/active-directory-login-assistance-collection-of-common-programming-errors\/"},"modified":"2014-06-07T02:30:00","modified_gmt":"2014-06-07T02:30:00","slug":"active-directory-login-assistance-collection-of-common-programming-errors","status":"publish","type":"post","link":"https:\/\/unknownerror.org\/index.php\/2014\/06\/07\/active-directory-login-assistance-collection-of-common-programming-errors\/","title":{"rendered":"Active Directory Login assistance-Collection of common programming errors"},"content":{"rendered":"<p>I&#8217;m not really sure if this is a question for here or not, please let me know if I must post it else where. I followed the steps and code given in this Microsoft tutorial and everything is working fine as far as logging in goes.<\/p>\n<p>The problem a few users have submitted is that they can see other users data when they log in and click around.<\/p>\n<p>EG: Joshua logs in on his machine and then Craig logs in on his machine as well (Separate machines). For some reason unbeknownst to me, Joshua can sometimes see Craig&#8217;s data and Craig can sometimes see Joshua&#8217;s data (Which should <strong>not<\/strong> happen).<\/p>\n<p>I have a feeling it has something to do with Sessions? (But again, I am not sure and am fairly new to .Net and C# using AD)<\/p>\n<p>Here is My code after following the tutorial above, do you notice anything that I have done incorrectly OR should do better OR anything I need to add?<\/p>\n<p><strong>LOGON CODE BEHIND:<\/strong><\/p>\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Web;\nusing System.Web.UI;\nusing System.Web.UI.WebControls;\nusing FormsAuth;\nusing System.Web.Security;\n\nnamespace FormsAuthAd\n{\n    public partial class Logon : System.Web.UI.Page\n    {\n        public string fullname;\n\n        protected void Page_Load(object sender, EventArgs e)\n        {\n\n\n        }\n\n       public void Login_Click(object sender, EventArgs e)\n        {\n            string adPath = \"LDAP:\/\/MyServerIP\"; \/\/Path to your LDAP directory server\n            LdapAuthentication adAuth = new LdapAuthentication(adPath);\n            try\n            {\n                if (true == adAuth.IsAuthenticated(txtDomain.Text, txtUsername.Text, txtPassword.Text))\n                {\n                    fullname = adAuth.getFullName();\n\n                    string groups = adAuth.GetGroups();\n\n                    \/\/Create the ticket, and add the groups.\n                    bool isCookiePersistent = chkPersist.Checked;\n                    FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, txtUsername.Text, DateTime.Now, DateTime.Now.AddMinutes(60), isCookiePersistent, groups);\n\n                    \/\/Encrypt the ticket.\n                    string encryptedTicket = FormsAuthentication.Encrypt(authTicket);\n\n                    \/\/Create a cookie, and then add the encrypted ticket to the cookie as data.\n                    HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);\n\n                    if (true == isCookiePersistent)\n                        authCookie.Expires = authTicket.Expiration;\n\n                    \/\/Add the cookie to the outgoing cookies collection.\n                    Response.Cookies.Add(authCookie);\n\n                    \/\/You can redirect now.\n                    Response.Redirect(FormsAuthentication.GetRedirectUrl(txtUsername.Text, false));\n                }\n                else\n                {\n                    errorLabel.Text = \"Authentication did not succeed. Check user name and password.\";\n                }\n            }\n            catch (Exception ex)\n            {\n                errorLabel.Text = \"Please confirm Username &amp; Password! Password is case sensitive\";\n            }\n        }\n    }\n}\n<\/code><\/pre>\n<p><strong>In Global.asax.cs:<\/strong><\/p>\n<pre><code> void Application_AuthenticateRequest(object sender, EventArgs e)\n        {\n            string cookieName = FormsAuthentication.FormsCookieName;\n            HttpCookie authCookie = Context.Request.Cookies[cookieName];\n\n            if (null == authCookie)\n            {\n                \/\/There is no authentication cookie.\n                return;\n            }\n            FormsAuthenticationTicket authTicket = null;\n            try\n            {\n                authTicket = FormsAuthentication.Decrypt(authCookie.Value);\n            }\n            catch (Exception ex)\n            {\n                \/\/Write the exception to the Event Log.\n                return;\n            }\n            if (null == authTicket)\n            {\n                \/\/Cookie failed to decrypt.\n                return;\n            }\n            \/\/When the ticket was created, the UserData property was assigned a\n            \/\/pipe-delimited string of group names.\n            string[] groups = authTicket.UserData.Split(new char[] { '|' });\n            \/\/Create an Identity.\n            GenericIdentity id = new GenericIdentity(authTicket.Name, \"LdapAuthentication\");\n            \/\/This principal flows throughout the request.\n            GenericPrincipal principal = new GenericPrincipal(id, groups);\n            Context.User = principal;\n        }\n<\/code><\/pre>\n<p><strong>LdapAuthentication.cs:<\/strong><\/p>\n<pre><code>using System;\nusing System.Text;\nusing System.Collections;\nusing System.DirectoryServices;\nusing FormsAuthAd;\nusing System.Configuration;\n\nnamespace FormsAuth\n{\n    public class LdapAuthentication\n    {\n        private string _path;\n        private string _filterAttribute;\n        private DirectoryEntry entry;\n\n        public LdapAuthentication(string path)\n        {\n            _path = path;\n        }\n\n        public string getFullName()\n        {\n            return _filterAttribute;\n        }\n\n        public bool IsAuthenticated(string domain, string username, string pwd)\n        {\n            string domainAndUsername = domain + @\"\\\" + username;\n            entry = new DirectoryEntry(_path, domainAndUsername, pwd);\n\n            try\n            {\n                \/\/Bind to the native AdsObject to force authentication.\n                object obj = entry.NativeObject;\n\n                DirectorySearcher search = new DirectorySearcher(entry);\n\n                search.Filter = \"(SAMAccountName=\" + username + \")\";\n                search.PropertiesToLoad.Add(\"cn\");\n                SearchResult result = search.FindOne();\n\n                if (null == result)\n                {\n                    return false;\n                }\n\n                \/\/Update the new path to the user in the directory.\n                _path = result.Path;\n                _filterAttribute = (string)result.Properties[\"cn\"][0];\n\n                Constants.Fullname = _filterAttribute;\n\n            }\n            catch (Exception ex)\n            {\n                throw new Exception(\"Error authenticating user. \" + ex.Message);\n            }\n\n            return true;\n        }\n\n        public string GetGroups()\n        {\n\n            DirectorySearcher search = new DirectorySearcher(entry);\n            \/\/DirectoryEntry searchRoot = new DirectoryEntry(_path);\n            \/\/DirectorySearcher search = new DirectorySearcher(searchRoot);\n            search.Filter = \"(cn=\" + _filterAttribute + \")\";\n            search.PropertiesToLoad.Add(\"memberOf\");\n            StringBuilder groupNames = new StringBuilder();\n\n            try\n            {\n                SearchResult result = search.FindOne();\n                int propertyCount = result.Properties[\"memberOf\"].Count;\n                string dn;\n                int equalsIndex, commaIndex;    \n\n                for (int propertyCounter = 0; propertyCounter &lt; propertyCount; propertyCounter++)\n                {\n                    dn = (string)result.Properties[\"memberOf\"][propertyCounter];\n                    equalsIndex = dn.IndexOf(\"=\", 1);\n                    commaIndex = dn.IndexOf(\",\", 1);\n                    if (-1 == equalsIndex)\n                    {\n                        return null;\n                    }\n                    groupNames.Append(dn.Substring((equalsIndex + 1), (commaIndex - equalsIndex) - 1));\n                    groupNames.Append(\"|\");\n                }\n            }\n            catch (Exception ex)\n            {\n                throw new Exception(\"Error obtaining group names. \" + ex.Message);\n            }\n            return groupNames.ToString();\n        }\n    }\n}\n<\/code><\/pre>\n<p>Please let me know if you need any more information.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>I&#8217;m not really sure if this is a question for here or not, please let me know if I must post it else where. I followed the steps and code given in this Microsoft tutorial and everything is working fine as far as logging in goes. The problem a few users have submitted is that [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1],"tags":[],"class_list":["post-7348","post","type-post","status-publish","format-standard","hentry","category-uncategorized"],"_links":{"self":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/posts\/7348","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/comments?post=7348"}],"version-history":[{"count":0,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/posts\/7348\/revisions"}],"wp:attachment":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/media?parent=7348"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/categories?post=7348"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/tags?post=7348"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}