System.DirectoryServices.Protocol 从组中添加/删除用户

发布于 2024-12-04 05:30:58 字数 298 浏览 2 评论 0原文

我想从 System.DirectoryServices.Protocol 命名空间中的组中添加删除用户。

我有这里提到的示例:

链接到我的其他问题

但不能查找有关如何使用 S.DS.P 在组中添加和删除用户的示例。

有谁知道此操作的任何样本吗?

谢谢,

卡尔-

I want to Add remove a user from a group in System.DirectoryServices.Protocol namespace.

I have the samples mentioned here :

link to my other question

But can't find an exampel fo how to add and remove a user from a group using S.DS.P.

Does anyone know of any samples for this operation?

Thanks,

Cal-

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

-黛色若梦 2024-12-11 05:30:58

您只想使用 DirectoryAttributeOperation.Addmember 属性上发送 ModifyRequest。您应该传递的值是您要添加到组中的用户的 DN

You'd just want to send a ModifyRequest on the member attribute with a DirectoryAttributeOperation.Add. The value you should pass is the DN of the user you want to add to the group

无所谓啦 2024-12-11 05:30:58

这是将对象添加到组的示例。

    public static void AddObjectToGroup(string objectName, string groupName)
    {
        // var credential = new NetworkCredential();
        // var identifier = new LdapDirectoryIdentifier("");
        using (var connection = new LdapConnection("company.com"))
        {
            connection.SessionOptions.StartTransportLayerSecurity(null);
            connection.Bind();

            string objectDn = null;
            var request = new SearchRequest("DC=company,DC=com", $"Name={objectName}", SearchScope.Subtree, "distinguishedName");
            var response = (SearchResponse)connection.SendRequest(request);
            if (response != null)
            {
                var enumerator = response.Entries.GetEnumerator();
                enumerator.Reset();
                if (enumerator.MoveNext() && enumerator.Current is SearchResultEntry entry)
                {
                    objectDn = entry.Attributes["distinguishedName"].GetValues(typeof(string)).Select(x => (string)x).FirstOrDefault();
                }
            }
            Log.Information($"object DN: {objectDn}");

            string groupDn = null;
            request = new SearchRequest("DC=company,DC=com", $"Name={groupName}", SearchScope.Subtree, "distinguishedName"); 
            response = (SearchResponse)connection.SendRequest(request);
            if (response != null)
            {
                var enumerator = response.Entries.GetEnumerator();
                enumerator.Reset();
                if (enumerator.MoveNext() && enumerator.Current is SearchResultEntry entry)
                {
                    groupDn = entry.Attributes["distinguishedName"].GetValues(typeof(string)).Select(x => (string)x).FirstOrDefault();
                }
            }
            Log.Information($"group DN: {groupDn}");

            request = new SearchRequest("DC=company,DC=com", $"(&(objectCategory=Group)(distinguishedName={groupDn}))", SearchScope.Subtree);
            response = (SearchResponse)connection.SendRequest(request);
            if (response != null && !string.IsNullOrWhiteSpace(objectDn))
            {
                var members = response.Entries[0].Attributes["member"];

                var existing = new List<string>();
                for (int i = 0; i < members.Count; i++)
                {
                    existing.Add(members[i].ToString());
                }

                if (existing.Contains(objectDn)) return;
                
                var dam = new DirectoryAttributeModification { Name = "member" };
                dam.Add(objectDn);
                dam.Operation = DirectoryAttributeOperation.Add;

                var mr = new ModifyRequest(groupDn, dam);
                var dr = connection.SendRequest(mr);
                Log.Information($"Add Response: {dr.ResultCode.ToString()}");
            }
        }
    }

Here a example to add a object to a group.

    public static void AddObjectToGroup(string objectName, string groupName)
    {
        // var credential = new NetworkCredential();
        // var identifier = new LdapDirectoryIdentifier("");
        using (var connection = new LdapConnection("company.com"))
        {
            connection.SessionOptions.StartTransportLayerSecurity(null);
            connection.Bind();

            string objectDn = null;
            var request = new SearchRequest("DC=company,DC=com", 
quot;Name={objectName}", SearchScope.Subtree, "distinguishedName");
            var response = (SearchResponse)connection.SendRequest(request);
            if (response != null)
            {
                var enumerator = response.Entries.GetEnumerator();
                enumerator.Reset();
                if (enumerator.MoveNext() && enumerator.Current is SearchResultEntry entry)
                {
                    objectDn = entry.Attributes["distinguishedName"].GetValues(typeof(string)).Select(x => (string)x).FirstOrDefault();
                }
            }
            Log.Information(
quot;object DN: {objectDn}");

            string groupDn = null;
            request = new SearchRequest("DC=company,DC=com", 
quot;Name={groupName}", SearchScope.Subtree, "distinguishedName"); 
            response = (SearchResponse)connection.SendRequest(request);
            if (response != null)
            {
                var enumerator = response.Entries.GetEnumerator();
                enumerator.Reset();
                if (enumerator.MoveNext() && enumerator.Current is SearchResultEntry entry)
                {
                    groupDn = entry.Attributes["distinguishedName"].GetValues(typeof(string)).Select(x => (string)x).FirstOrDefault();
                }
            }
            Log.Information(
quot;group DN: {groupDn}");

            request = new SearchRequest("DC=company,DC=com", 
quot;(&(objectCategory=Group)(distinguishedName={groupDn}))", SearchScope.Subtree);
            response = (SearchResponse)connection.SendRequest(request);
            if (response != null && !string.IsNullOrWhiteSpace(objectDn))
            {
                var members = response.Entries[0].Attributes["member"];

                var existing = new List<string>();
                for (int i = 0; i < members.Count; i++)
                {
                    existing.Add(members[i].ToString());
                }

                if (existing.Contains(objectDn)) return;
                
                var dam = new DirectoryAttributeModification { Name = "member" };
                dam.Add(objectDn);
                dam.Operation = DirectoryAttributeOperation.Add;

                var mr = new ModifyRequest(groupDn, dam);
                var dr = connection.SendRequest(mr);
                Log.Information(
quot;Add Response: {dr.ResultCode.ToString()}");
            }
        }
    }
¢好甜 2024-12-11 05:30:58

对于那些关注的人,这是我如何使用 System.DirectoryServices.AccountManagement 实际解决问题的方法

string adServer = "";
            string adServerUser = "";
            string adServerPassword = "";
            string adServerContainer = "";

            GetSettings( ref adServer, ref adServerUser, ref adServerPassword, ref adServerContainer );

            if ( ((!string.IsNullOrEmpty(adServer) && !string.IsNullOrEmpty(adServerUser)) && !string.IsNullOrEmpty(adServerPassword)) && !string.IsNullOrEmpty(adServerContainer))
            {
                try
                {
                    using (PrincipalContext principalContext = new PrincipalContext(ContextType.Domain, adServer, adServerContainer, adServerUser, adServerPassword))
                    {
                        using (GroupPrincipal group = GroupPrincipal.FindByIdentity(principalContext, IdentityType.SamAccountName, this.textBox_GroupAdd.Text))
                        {
                            if (group == null)
                            {
                                FlexibleMessageBox.Show("group could not be found");
                                return;
                            }
                            PrincipalSearchResult<Principal> x = group.GetMembers();
                            using (UserPrincipal user = UserPrincipal.FindByIdentity(principalContext, IdentityType.SamAccountName, this.textBox_adName.Text))
                            {
                                string userSid = string.Format("<SID={0}>", ToSidString(user));
                                DirectoryEntry groupDirectoryEntry = (DirectoryEntry) group.GetUnderlyingObject();
                                groupDirectoryEntry.Properties["member"].Add(userSid);
                                groupDirectoryEntry.CommitChanges();
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    FlexibleMessageBox.Show(ex.ToString());
                }
                FlexibleMessageBox.Show("group add done");
            }

,这是从组中删除的内容

                    using (UserPrincipal user = UserPrincipal.FindByIdentity(principalContext, IdentityType.SamAccountName, this.textBox_adName.Text))
                    {
                        string userSid = string.Format("<SID={0}>", ToSidString(user));
                        DirectoryEntry groupDirectoryEntry = (DirectoryEntry) group.GetUnderlyingObject();
                        groupDirectoryEntry.Properties["member"].Remove(userSid);
                        groupDirectoryEntry.CommitChanges();
                    }

Just for those who follow, here is how I actually solved the problem using System.DirectoryServices.AccountManagement

string adServer = "";
            string adServerUser = "";
            string adServerPassword = "";
            string adServerContainer = "";

            GetSettings( ref adServer, ref adServerUser, ref adServerPassword, ref adServerContainer );

            if ( ((!string.IsNullOrEmpty(adServer) && !string.IsNullOrEmpty(adServerUser)) && !string.IsNullOrEmpty(adServerPassword)) && !string.IsNullOrEmpty(adServerContainer))
            {
                try
                {
                    using (PrincipalContext principalContext = new PrincipalContext(ContextType.Domain, adServer, adServerContainer, adServerUser, adServerPassword))
                    {
                        using (GroupPrincipal group = GroupPrincipal.FindByIdentity(principalContext, IdentityType.SamAccountName, this.textBox_GroupAdd.Text))
                        {
                            if (group == null)
                            {
                                FlexibleMessageBox.Show("group could not be found");
                                return;
                            }
                            PrincipalSearchResult<Principal> x = group.GetMembers();
                            using (UserPrincipal user = UserPrincipal.FindByIdentity(principalContext, IdentityType.SamAccountName, this.textBox_adName.Text))
                            {
                                string userSid = string.Format("<SID={0}>", ToSidString(user));
                                DirectoryEntry groupDirectoryEntry = (DirectoryEntry) group.GetUnderlyingObject();
                                groupDirectoryEntry.Properties["member"].Add(userSid);
                                groupDirectoryEntry.CommitChanges();
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    FlexibleMessageBox.Show(ex.ToString());
                }
                FlexibleMessageBox.Show("group add done");
            }

and here is the guts of the remove from group

                    using (UserPrincipal user = UserPrincipal.FindByIdentity(principalContext, IdentityType.SamAccountName, this.textBox_adName.Text))
                    {
                        string userSid = string.Format("<SID={0}>", ToSidString(user));
                        DirectoryEntry groupDirectoryEntry = (DirectoryEntry) group.GetUnderlyingObject();
                        groupDirectoryEntry.Properties["member"].Remove(userSid);
                        groupDirectoryEntry.CommitChanges();
                    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文