{"id":7321,"date":"2014-06-07T02:25:04","date_gmt":"2014-06-07T02:25:04","guid":{"rendered":"https:\/\/unknownerror.org\/index.php\/2014\/06\/07\/asp-net-active-directory-ldap-trying-to-filter-down-into-a-group-level-collection-of-common-programming-errors\/"},"modified":"2014-06-07T02:25:04","modified_gmt":"2014-06-07T02:25:04","slug":"asp-net-active-directory-ldap-trying-to-filter-down-into-a-group-level-collection-of-common-programming-errors","status":"publish","type":"post","link":"https:\/\/unknownerror.org\/index.php\/2014\/06\/07\/asp-net-active-directory-ldap-trying-to-filter-down-into-a-group-level-collection-of-common-programming-errors\/","title":{"rendered":"Asp.net Active Directory LDAP: Trying to filter down into a group level-Collection of common programming errors"},"content":{"rendered":"<p>I have created a login page in asp.net using c# but I am having difficulty trying to only allow a certain group to have access. Right now I am accessing everyone but I can&#8217;t seem to just filter the group that I need so only those person(s) can have access to my application.<\/p>\n<p>Any help would be great so I can just permission this application out to that one group within Active Directory.<\/p>\n<p>Here is my class that I am using to pass the groups:<\/p>\n<pre><code>public class LdapAuthentication\n{\n    private string _path;\n    private string _filterAttribute;\n\n    public LdapAuthentication(string path)\n    {\n        _path = path;\n    }\n\n    public bool IsAuthenticated(string domain, string username, string pwd)\n    {\n      string domainAndUsername = domain + @\"\\\" + username;\n      DirectoryEntry 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        DirectorySearcher search = new DirectorySearcher(entry);\n        search.Filter = \"(SAMAccountName=\" + username + \")\";\n        search.PropertiesToLoad.Add(\"cn\");\n        SearchResult result = search.FindOne();\n        if(null == result)\n        {\n          return false;\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      catch (Exception ex)\n      {\n        throw new Exception(\"Error authenticating user. \" + ex.Message);\n      }\n      return true;\n    }\n\n    public string GetGroups()\n    {\n        DirectorySearcher search = new DirectorySearcher(_path);\n        search.Filter = \"(cn=\" + _filterAttribute + \")\";\n        search.PropertiesToLoad.Add(\"memberOf\");\n        StringBuilder groupNames = new StringBuilder();\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;\n                 propertyCounter++)\n            {\n                dn = (String)result.Properties[\"memberOf\"][propertyCounter];\n\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),\n                                  (commaIndex - equalsIndex) - 1));\n                groupNames.Append(\"|\");\n            }\n        }\n        catch (Exception ex)\n        {\n            throw new Exception(\"Error obtaining group names. \" +\n              ex.Message);\n        }\n        return groupNames.ToString();\n    }\n\n    public bool isMember( String groupname )\n    {\n        DirectorySearcher search = new DirectorySearcher(_path);\n        search.Filter = \"(cn=\" + _filterAttribute + \")\";\n        search.PropertiesToLoad.Add(\"memberOf\");\n        try\n        {\n            SearchResult result = search.FindOne();\n            int propertyCount = result.Properties[\"memberOf\"].Count;\n\n            for (int propertyCounter = 0; propertyCounter &lt; propertyCount;\n                    propertyCounter++)\n            {\n                String dn = (String)result.Properties[\"memberOf\"][propertyCounter];\n                \/\/ The comma in the regex is important to prevent accidental matches\n                if ( Regex.IsMatch( dn, @\"cn=\"+groupname+\",.*\", RegexOptions.IgnoreCase))\n                    return true;\n            }\n        }\n        catch (Exception ex)\n        { \n            \/\/ Some logging here probably\n        }\n        return false;\n    }\n}\n<\/code><\/pre>\n<p>It has to be in the Get groups function but I am not sure how to pass the group I am looking for. If anyone can help that would be greatly appreciated. Thanks in advance.<\/p>\n<p>Here is my button click event:<\/p>\n<pre><code>    protected void btnLogin_Click(object sender, EventArgs e)\n    {\n        \/\/ Path to you LDAP directory server.\n        \/\/ Contact your network administrator to obtain a valid path.\n        string adPath = \"LDAP:\/\/domain.com\";\n        LdapAuthentication adAuth = new LdapAuthentication(adPath);\n        String myGroupName = \"Some_Group\";\n\n        try\n        {\n            if (true == adAuth.IsAuthenticated(txtDomainName.Text, txtLoginID.Text, txtPassword.Text))\n            {\n                if( adAuth.isMember( myGroupName ) )\n                  {\n                      \/\/ User is authenticated and a member of the group. \n                      \/\/ Create your auth ticket, cookie, and whatnot\n                      \/\/ Retrieve the user's groups\n                        string groups = adAuth.GetGroups();\n                        \/\/ Create the authetication ticket\n                        FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1,  \/\/ version\n                                                          txtLoginID.Text,\n                                                          DateTime.Now,\n                                                          DateTime.Now.AddMinutes(60),\n                                                          false, groups);\n                        \/\/ Now encrypt the ticket.\n                        string encryptedTicket = FormsAuthentication.Encrypt(authTicket);\n                        \/\/ Create a cookie and add the encrypted ticket to the \n                        \/\/ cookie as data.\n                        HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);\n\n                        \/\/ Add the cookie to the outgoing cookies collection.\n                        Response.Cookies.Add(authCookie);\n\n                        \/\/ Redirect the user to the originally requested page\n                        \/\/Response.Redirect(FormsAuthentication.GetRedirectUrl(txtLoginID.Text, false));\n\n                        Response.Redirect(\"LookupEdit.aspx\");   \n                  }\n                  else\n                  {\n                      lblError.Text = \"Authorization failed. You are not a member of the \"+myGroupName+\" group\";\n                  }\n                }\n                else\n                {\n                  lblError.Text = \"Authentication did not succeed. Check user name and password.\";\n                }\n              }\n              catch(Exception ex)\n              {\n                lblError.Text = \"Error authenticating. \" + ex.Message;\n              }\n    }\n<\/code><\/pre>\n","protected":false},"excerpt":{"rendered":"<p>I have created a login page in asp.net using c# but I am having difficulty trying to only allow a certain group to have access. Right now I am accessing everyone but I can&#8217;t seem to just filter the group that I need so only those person(s) can have access to my application. Any help [&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-7321","post","type-post","status-publish","format-standard","hentry","category-uncategorized"],"_links":{"self":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/posts\/7321","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=7321"}],"version-history":[{"count":0,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/posts\/7321\/revisions"}],"wp:attachment":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/media?parent=7321"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/categories?post=7321"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/tags?post=7321"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}