See if user is part of Active Directory group in C# + Asp.net

前端 未结 14 1241
花落未央
花落未央 2020-11-30 19:06

I need a way to see if a user is part of an active directory group from my .Net 3.5 asp.net c# application.

I am using the standard ldap authentication example off o

14条回答
  •  自闭症患者
    2020-11-30 19:38

    You could try the following code:

    public bool Check_If_Member_Of_AD_Group(string username, string grouptoCheck, string domain, string ADlogin, string ADpassword)
    {
        
         try {
            
            string EntryString = null;
            EntryString = "LDAP://" + domain;
            
            DirectoryEntry myDE = default(DirectoryEntry);
            
            grouptoCheck = grouptoCheck.ToLower();
            
            
            myDE = new DirectoryEntry(EntryString, ADlogin, ADpassword);
            
            DirectorySearcher myDirectorySearcher = new DirectorySearcher(myDE);
            
            myDirectorySearcher.Filter = "sAMAccountName=" + username;
            
            myDirectorySearcher.PropertiesToLoad.Add("MemberOf");
            
            SearchResult myresult = myDirectorySearcher.FindOne();
            
            int NumberOfGroups = 0;
            
            NumberOfGroups = myresult.Properties["memberOf"].Count - 1;
            
            string tempString = null;
            
            while ((NumberOfGroups >= 0)) {
                
                tempString = myresult.Properties["MemberOf"].Item[NumberOfGroups];
                tempString = tempString.Substring(0, tempString.IndexOf(",", 0));
                
                tempString = tempString.Replace("CN=", "");
                
                tempString = tempString.ToLower();
                tempString = tempString.Trim();
                
                if ((grouptoCheck == tempString)) {
                    
                        
                    return true;
                }
                
                    
                NumberOfGroups = NumberOfGroups - 1;
            }
            
                
            return false;
        }
        catch (Exception ex) {
            
            System.Diagnostics.Debugger.Break();
        }
        //HttpContext.Current.Response.Write("Error: 

    " & ex.ToString) }

提交回复
热议问题