【问题标题】:Adding Users to AD Universal Group from Different Domains C#从不同域 C# 将用户添加到 AD 通用组
【发布时间】:2015-03-12 11:07:29
【问题描述】:

我们在同一个林中有许多域(即 sw.main.company.com、nw.main.company.com、main.company.com),我控制 sw.main.company.com 中的一个 OU我在其中设置了一个通用 Active Directory 组。

在默认 AD 端口上使用 System.DirectoryServices.AccountManagement .NET 4.5 等将“sw”域用户添加到组中没有困难(c#),但是在添加来自其他域的用户时(nw , mw 等),我在设置新的 PrincipalContext(ContextType.Domain "sw .main.company.com:3268", "DC=main,DC=company,DC=com")。

所有域控制器也是全局目录服务器,调用端口 3268 允许来自其他域的用户正确解析,但我无法使用 GlobalPrincipal.Save() 命令提交添加而不抛出错误。

我已经包含了下面的相关代码以及详细的错误堆栈。我需要这方面的帮助。

public void SyncADUsers()
{
    AddUserToGroup("MW\\abc123user", "Universal_Group_1");
}

public void AddUserToGroup(string userId, string groupName)
{
    try
    {
        using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, "sw.main.company.com:3268", "DC=main,DC=company,DC=com"))
        {
            GroupPrincipal group = GroupPrincipal.FindByIdentity(pc, groupName);
            group.Members.Add(pc, IdentityType.SamAccountName, userId);
            group.Save();
        }
    }
    catch (System.DirectoryServices.DirectoryServicesCOMException E)
    {
        //doSomething with E.Message.ToString(); 
    }
}

System.InvalidOperationException 未处理 HResult=-2146233079 Message=服务器不愿意处理请求。 Source=System.DirectoryServices.AccountManagement StackTrace:位于 System.DirectoryServices.AccountManagement.ADStoreCtx System.DirectoryServices.AccountManagement.SDSUtils.ApplyChangesToDirectory(主体 p,StoreCtx storeCtx,GroupMembershipUpdater updateGroupMembership,NetCred 凭据,AuthenticationTypes authTypes)在 System.DirectoryServices.AccountManagement.ADStoreCtx 的 .UpdateGroupMembership(主体组,DirectoryEntry de,NetCred 凭据,AuthenticationTypes authTypes)。更新(主体 p)在 System.DirectoryServices.AccountManagement.Principal.Save() 在 ExampleUsers.SyncAD.AddUserToGroup(String userId, String groupName) 在 c:\SourceControl\ExampleUsers\ExampleUsers\SyncAD.cs:第 33 行在 ExampleUsers.SyncAD .SyncADUsers() 在 c:\SourceControl\ExampleUsers\ExampleUsers\SyncAD.cs:第 18 行,在 ExampleUsers.Program.Main(String[] a rgs)在 c:\SourceControl\ExampleUsers\ExampleUsers\Program.cs:System.AppDomain._nExecuteAssembly 的第 62 行(RuntimeAssembly 程序集,String[] args)在 System.AppDomain.ExecuteAssembly(字符串 assemblyFile,证据 assemblySecurity,String[] args ) 在 Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() 在 System.Threading.ThreadHelper.ThreadStart_Context(Object state) 在 System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) 在 System.Threading .ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.ThreadHelper.ThreadStart() InnerException: System.DirectoryServices .DirectoryServicesCOMException HResult=-2147016651 Message=服务器不愿意处理请求。 Source=System.DirectoryServices ErrorCode=-2147016651 ExtendedError=8245 ExtendedErrorMessage=00002035: LdapErr: DSID-0C090B3E, 注释: Operation not allowed through GC port, data 0, v1db1 StackTrace: at System.DirectoryServices.DirectoryEntry.CommitChanges( ) 在 System.DirectoryServices.AccountManagement.ADStoreCtx.UpdateGroupMembership(主体组,DirectoryEntry de,NetCred 凭据,AuthenticationTypes authTypes)InnerException:

【问题讨论】:

    标签: c# dns active-directory groupprincipal


    【解决方案1】:

    参考 BaldPate 的回复,如果 Global Catalog 是只读的,我们需要使用 3268 端口读取并解析不同域中的用户,然后将使用 389 端口的用户全部保存在同一上下文中。这可以通过以下代码完成(注意分别调用 3268 和默认 389 端口),感谢 BaldPate 明确说明:

    using System;
    using System.Collections;
    using System.Data;
    using System.Data.SqlClient;
    using System.Collections.Generic;
    using System.DirectoryServices.AccountManagement;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Configuration;
    
    namespace OurUsers
    {
    class SyncAD
    {
        #region Variables
    
        private string sDomain = "sw.main.company.com";
        private string sDomainGC = "sw.main.company.com:3268";
        private string sDefaultOU = "DC=sw,DC=main,DC=company,DC=com";
        private string sDefaultRootOU = "DC=main,DC=company,DC=com";
        private string sGroupName = "Production_Universal_AD_Group";
        private string connectionString = "Server=OurServerName\\PROD; Integrated Security=True; Initial Catalog=OurUsers";
        private string sqlAdd = "SELECT FullID FROM ViewFolkstoAdd";
        private string sqlRemove = "SELECT FullID FROM ViewFolkstoRemove";
    
        #endregion
        public void SyncADUsers()
        {
            // Get Database Ready and Remove Users
            SqlConnection connectionRemove = new SqlConnection(connectionString);
            SqlCommand commandRemove = new SqlCommand(sqlRemove, connectionRemove);
            connectionRemove.Open();
            SqlDataReader readerRemove = commandRemove.ExecuteReader();
    
            if (readerRemove.HasRows)
            {
                int i = 0;
                while (readerRemove.Read())
                {
                    string sUserName = readerRemove.GetString(0);
                    RemoveUserFromGroup(sUserName, sGroupName);
                    i = i + 1;
                    Console.WriteLine("{0} {1}", i, sUserName);
                }
            }
            else
            {
                Console.WriteLine("No rows found.");
            }
            readerRemove.Close();
    
            // Get Database Ready and Add Users
            SqlConnection connectionAdd = new SqlConnection(connectionString);
            SqlCommand commandAdd = new SqlCommand(sqlAdd, connectionAdd);
            connectionAdd.Open();
            SqlDataReader readerAdd = commandAdd.ExecuteReader();
    
            if (readerAdd.HasRows)
            {
                int i = 0;
                while (readerAdd.Read())
                {
                    string sUserName = readerAdd.GetString(0);
                    AddUserToGroup(sUserName, sGroupName);
                    i = i + 1;
                    Console.WriteLine("{0} {1}", i, sUserName);
                }
            }
            else
            {
                Console.WriteLine("No rows found.");
            }
            readerAdd.Close();
        }
    
        /// Gets a certain user on Active Directory
        /// Returns the UserPrincipal Object
        public UserPrincipal GetUser(string sUserName)
        {
            PrincipalContext oPrincipalContext = GetPrincipalContextGC();
            UserPrincipal oUserPrincipal = UserPrincipal.FindByIdentity(oPrincipalContext, sUserName);
            return oUserPrincipal;
        }
    
        /// Adds the user for a given group
        /// Returns true if successful
        public bool AddUserToGroup(string sUserName, string sGroupName)
        {
            try
            {
                UserPrincipal oUserPrincipal = GetUser(sUserName);
                GroupPrincipal oGroupPrincipal = GetGroup(sGroupName);
                if (oUserPrincipal != null && oGroupPrincipal != null)
                {
                    oGroupPrincipal.Members.Add(oUserPrincipal);
                    oGroupPrincipal.Save();
                }
                return true;
            }
            catch
            {
                return false;
            }
        }
    
        /// Removes user from a given group
        /// Returns true if successful
        public bool RemoveUserFromGroup(string sUserName, string sGroupName)
        {
            try
            {
                UserPrincipal oUserPrincipal = GetUser(sUserName);
                GroupPrincipal oGroupPrincipal = GetGroup(sGroupName);
                if (oUserPrincipal != null && oGroupPrincipal != null)
                {
                    oGroupPrincipal.Members.Remove(oUserPrincipal);
                    oGroupPrincipal.Save();
                }
                return true;
            }
            catch
            {
                return false;
            }
        }
    
        /// Gets PrincipalContext from the Local Domain
        /// Returns the PrincipalContext
        public PrincipalContext GetPrincipalContext()
        {
            PrincipalContext oPrincipalContext = new PrincipalContext(ContextType.Domain, sDomain, sDefaultOU, ContextOptions.Negotiate);
            return oPrincipalContext;
        }
    
        /// Gets PrincipalContext from the Global Catalog
        /// Returns the PrincipalContext
        public PrincipalContext GetPrincipalContextGC()
        {
            PrincipalContext oPrincipalContext = new PrincipalContext(ContextType.Domain, sDomainGC, sDefaultRootOU, ContextOptions.Negotiate);
            return oPrincipalContext;
        }
    
        /// Gets a certain group on Active Directory
        /// Returns the GroupPrincipal Object
        public GroupPrincipal GetGroup(string sGroupName)
        {
            PrincipalContext oPrincipalContext = GetPrincipalContext();
            GroupPrincipal oGroupPrincipal = GroupPrincipal.FindByIdentity(oPrincipalContext, sGroupName);
            return oGroupPrincipal;
        }
    }
    }
    

    【讨论】:

      【解决方案2】:

      全局目录是只读的。

      请连接到 LDAP 端口(默认 389)以更新组。

      【讨论】:

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