【问题标题】:Query From LDAP for User Groups从 LDAP 查询用户组
【发布时间】:2011-07-12 05:55:59
【问题描述】:

如何在 C# .NET for ASP 中从 LDAP 活动目录中获取用户组。在我的场景中,我想将用户名传递给从 LDAP 活动目录查询的方法,并告诉我我的用户是该用户组的成员。请在这方面帮助我

【问题讨论】:

    标签: c# asp.net active-directory ldap activedirectorymembership


    【解决方案1】:

    研究使用System.DirectoryServices 命名空间。您可以使用DirectorySearcher 来查找用户。一旦您拥有该用户的 DirectoryEntry 对象,请执行以下操作:

    public List<string> GetMemberOf(DirectoryEntry de)
    {
      List<string> memberof = new List<string>();
    
      foreach (object oMember in de.Properties["memberOf"])
      {
        memberof.Add(oMember.ToString());
      }
    
      return memberof;
    }
    

    这将返回一个字符串列表,这些字符串是用户所属的组名。

    当然,您可以进一步完善它以包含 DirectorySearcher 代码,这样您就可以将 samAccountName 传递给函数。

    【讨论】:

      【解决方案2】:

      使用 DirectorySearcher 类执行 ldap 查询。

      供参考:

      http://www.codeproject.com/KB/system/QueryADwithDotNet.aspx

      【讨论】:

        【解决方案3】:

        如果您使用的是 .NET 3.5 或更高版本,您还可以使用新的 System.DirectoryServices.AccountManagement (S.DS.AM) 命名空间。

        有了这个,你可以做这样的事情:

        // create context for domain
        PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
        
        // find the user
        UserPrincipal up = UserPrincipal.FindByIdentity(ctx, "YourUserName");
        
        if(up != null)
        {
            // get groups for that user
            var authGroups = up.GetAuthorizationGroups();
        }
        

        详细了解新的 S.DS.AM 命名空间:

        Managing Directory Security Principals in the .NET Framework 3.5

        【讨论】:

          【解决方案4】:

          试试这个...

          public override string[] GetRolesForUser(string username)
              {
              var allRoles = new List<string>();
              var root = new DirectoryEntry(WebConfigurationManager.ConnectionStrings[ConnectionStringName].ConnectionString,
                                              ConnectionUsername,
                                              ConnectionPassword);
          
              var searcher = new DirectorySearcher(root,
                                                  string.Format(CultureInfo.InvariantCulture, "(&(objectClass=user)({0}={1}))",
                                                                                              AttributeMapUsername,
                                                                                              username));
          
              searcher.PropertiesToLoad.Add("memberOf");
              SearchResult result = searcher.FindOne();
              if (result != null && !string.IsNullOrEmpty(result.Path))
              {
                  DirectoryEntry user = result.GetDirectoryEntry();
                  PropertyValueCollection groups = user.Properties["memberOf"];
                  foreach (string path in groups)
                  {
                      string[] parts = path.Split(',');
                      if (parts.Length > 0)
                      {
                          foreach (string part in parts)
                          {
                              string[] p = part.Split('=');
                              if (p[0].Equals("cn", StringComparison.OrdinalIgnoreCase))
                              {
                                  allRoles.Add(p[1]);
                              }
                          }
                      }
                  }
              }
              return allRoles.ToArray();
          }
          

          【讨论】:

            【解决方案5】:

            我认为上面列出的大多数方法都应该有效,但我建议添加代码以确保您的代码可以“检测嵌套组成员资格中的循环循环”,如果发现,打破您选择的脚本可能获得的任何无限循环进入。

            【讨论】:

              【解决方案6】:

              我需要一种对用户进行身份验证的方法并检查他们是否在特定的用户组中。我通过推送用户名和密码并将“memberOf”属性加载到“搜索”实例中来做到这一点。下面的示例将显示该特定用户名的所有组。 'catch' 语句将捕获错误的用户名或密码。

              DirectoryEntry entry = new DirectoryEntry("LDAP://xxxxxxxx/OU=xxxxxxx,DC=xxxxxx,DC=xxxxx,DC=xxxxxx", strLdapUserName, strLdapPassword);
              
                  try
                  {
                  //the object is needed to fire off the ldap connection
                  object obj = entry.NativeObject;
              
                  DirectorySearcher search = new DirectorySearcher(entry);
                  search.Filter = "(SAMAccountName=" + strLdapUserName + ")";
                  search.PropertiesToLoad.Add("memberOf");
                  SearchResult result = search.FindOne();
                  string filterAttribute = (String)result.Properties["cn"][0];
              
                  foreach(string groupMemberShipName in result.Properties["memberOf"])
                  {
                      Console.WriteLine("Member of - {0}", groupMemberShipName);
                  }
              
                  }
                  catch (Exception ex)
                  {
                  //failed to authenticate
                  throw new Exception(ex.ToString());
                  }
              

              希望这会有所帮助。 (记得参考 System.DirectoryServices)

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2014-09-20
                • 1970-01-01
                • 1970-01-01
                相关资源
                最近更新 更多