如何以编程方式从 SQL 更新和删除 LDAP 用户?

发布于 2024-12-19 05:18:38 字数 3540 浏览 0 评论 0原文

所以我希望获取一些 ldap 值,并将它们插入加密的数据库中。我已经使插入工作正常,但我需要检查用户是否仍然是该组的一部分,如果不是,则将其从数据库中删除,如果添加了新用户,则插入它们而不是插入现有用户。您能给我一些有关最佳实践的指导吗?我不想截断表并重新插入所有内容。

        try
        {
            /* Connection to Active Directory */
            DirectoryEntry deBase = new DirectoryEntry("LDAP://" + txtLDAP.Text + ":" + txtLDapPort.Text + "/" + txtBadeDN.Text, txtUsername.Text, txtPassword.Text, AuthenticationTypes.Secure);

            /* Directory Search*/
            DirectorySearcher dsLookForGrp = new DirectorySearcher(deBase);
            dsLookForGrp.Filter = String.Format("(cn={0})", txtGroup.Text);
            dsLookForGrp.SearchScope = SearchScope.Subtree;
            dsLookForGrp.PropertiesToLoad.Add("distinguishedName");
            SearchResult srcGrp = dsLookForGrp.FindOne();

            /* Directory Search
             */
            DirectorySearcher dsLookForUsers = new DirectorySearcher(deBase);
            dsLookForUsers.Filter = String.Format("(&(objectCategory=person)(memberOf={0}))", srcGrp.Properties["distinguishedName"][0]);
            dsLookForUsers.SearchScope = SearchScope.Subtree;
            dsLookForUsers.PropertiesToLoad.Add("objectSid");
            dsLookForUsers.PropertiesToLoad.Add("sAMAccountName");
            SearchResultCollection srcLstUsers = dsLookForUsers.FindAll();

            StringBuilder sbUsers = new StringBuilder();

            foreach (SearchResult sruser in srcLstUsers)
            {
                SecurityIdentifier sid = new SecurityIdentifier((byte[])sruser.Properties["objectSid"][0], 0);
                string ConnString = "ConnectionString Removed";
                string SqlString = "spInsertADAuthorization";
                using (OleDbConnection conn = new OleDbConnection(ConnString))
                {
                    using (OleDbCommand cmd = new OleDbCommand(SqlString, conn))
                    {
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.Parameters.AddWithValue("AD_Account", SpartaCrypto.SpartaEncryptAES(sruser.Properties["sAMAccountName"][0].ToString(), "thisisasharedsecret"));
                        cmd.Parameters.AddWithValue("AD_SID", SpartaCrypto.SpartaEncryptAES(sid.ToString(), "thisisasharedsecret"));
                        cmd.Parameters.AddWithValue("AD_EmailAddress", "[email protected]");
                        cmd.Parameters.AddWithValue("DateImported", DateTime.Now.ToString());
                        cmd.Parameters.AddWithValue("Active", 1);
                        conn.Open();
                        cmd.ExecuteNonQuery();
                        conn.Close();
                    }
                }
                lblResults.Text = srcLstUsers.Count + " Users granted access.";
            }
        }

        catch (Exception ex)
        {
            if (ex.Message.Contains("Logon failure"))
            {
                lblResults.Text = "Logon Failure.  Check your username or password.";
            }

            if (ex.Message.Contains("The server is not operational"))
            {
                lblResults.Text = "LDAP Error.  Check your hostname or port.";
            }
            if (ex.Message.Contains("Object reference not set to an instance of an object"))
            {
                lblResults.Text = "LDAP Error.  Check your hostname, port, or group name and try again.";
            }


        }

So i'm looking to grab some ldap values, and insert them into a database with encryption. I've got the insert working but i need to check if the user is still part of the group and if not remove them from the DB, and if there was a new user added it inserts them instead of inserting existing users. Can you give me some direction on best practices for this? I'd prefer not to truncate the table and re-insert all.

        try
        {
            /* Connection to Active Directory */
            DirectoryEntry deBase = new DirectoryEntry("LDAP://" + txtLDAP.Text + ":" + txtLDapPort.Text + "/" + txtBadeDN.Text, txtUsername.Text, txtPassword.Text, AuthenticationTypes.Secure);

            /* Directory Search*/
            DirectorySearcher dsLookForGrp = new DirectorySearcher(deBase);
            dsLookForGrp.Filter = String.Format("(cn={0})", txtGroup.Text);
            dsLookForGrp.SearchScope = SearchScope.Subtree;
            dsLookForGrp.PropertiesToLoad.Add("distinguishedName");
            SearchResult srcGrp = dsLookForGrp.FindOne();

            /* Directory Search
             */
            DirectorySearcher dsLookForUsers = new DirectorySearcher(deBase);
            dsLookForUsers.Filter = String.Format("(&(objectCategory=person)(memberOf={0}))", srcGrp.Properties["distinguishedName"][0]);
            dsLookForUsers.SearchScope = SearchScope.Subtree;
            dsLookForUsers.PropertiesToLoad.Add("objectSid");
            dsLookForUsers.PropertiesToLoad.Add("sAMAccountName");
            SearchResultCollection srcLstUsers = dsLookForUsers.FindAll();

            StringBuilder sbUsers = new StringBuilder();

            foreach (SearchResult sruser in srcLstUsers)
            {
                SecurityIdentifier sid = new SecurityIdentifier((byte[])sruser.Properties["objectSid"][0], 0);
                string ConnString = "ConnectionString Removed";
                string SqlString = "spInsertADAuthorization";
                using (OleDbConnection conn = new OleDbConnection(ConnString))
                {
                    using (OleDbCommand cmd = new OleDbCommand(SqlString, conn))
                    {
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.Parameters.AddWithValue("AD_Account", SpartaCrypto.SpartaEncryptAES(sruser.Properties["sAMAccountName"][0].ToString(), "thisisasharedsecret"));
                        cmd.Parameters.AddWithValue("AD_SID", SpartaCrypto.SpartaEncryptAES(sid.ToString(), "thisisasharedsecret"));
                        cmd.Parameters.AddWithValue("AD_EmailAddress", "[email protected]");
                        cmd.Parameters.AddWithValue("DateImported", DateTime.Now.ToString());
                        cmd.Parameters.AddWithValue("Active", 1);
                        conn.Open();
                        cmd.ExecuteNonQuery();
                        conn.Close();
                    }
                }
                lblResults.Text = srcLstUsers.Count + " Users granted access.";
            }
        }

        catch (Exception ex)
        {
            if (ex.Message.Contains("Logon failure"))
            {
                lblResults.Text = "Logon Failure.  Check your username or password.";
            }

            if (ex.Message.Contains("The server is not operational"))
            {
                lblResults.Text = "LDAP Error.  Check your hostname or port.";
            }
            if (ex.Message.Contains("Object reference not set to an instance of an object"))
            {
                lblResults.Text = "LDAP Error.  Check your hostname, port, or group name and try again.";
            }


        }

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

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

发布评论

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

评论(1

强者自强 2024-12-26 05:18:38

由于您使用的是 .NET 3.5 及更高版本,因此您应该检查 System.DirectoryServices.AccountManagement (S.DS.AM) 命名空间。在这里阅读所有相关内容:

您可以使用 PrincipalSearcher 和“按示例查询”主体进行搜索:

// create your domain context
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);

// define a "query-by-example" principal - here, we search for a UserPrincipal 
// and with the first name (GivenName) of "Bruce"
UserPrincipal qbeUser = new UserPrincipal(ctx);
qbeUser.GivenName = "Bruce";

// create your principal searcher passing in the QBE principal    
PrincipalSearcher srch = new PrincipalSearcher(qbeUser);

// find all matches
foreach(var found in srch.FindAll())
{
    // do whatever here - "found" is of type "Principal" - it could be user, group, computer.....          
}

对于使用单个主体,编程界面也更好:

// find a user
UserPrincipal user = UserPrincipal.FindByIdentity(ctx, "SomeUserName");

if(user != null)
{
   // do something here... you can access most of the commonly used properties easily
   user.GivenName = "....";
   user.Surname = "......";
   user.SamAccountName = ".....";
}

// find the group in question
GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, "YourGroupNameHere");

// if found....
if (group != null)
{
   // iterate over members
   foreach (Principal p in group.GetMembers())
   {
      Console.WriteLine("{0}: {1}", p.StructuralObjectClass, p.DisplayName);
      // do whatever you need to do to those members
   }
}

新的 S.DS.AM 使在 AD 中与用户和组进行交互变得更加容易

Since you're on .NET 3.5 and up, you should check out the System.DirectoryServices.AccountManagement (S.DS.AM) namespace. Read all about it here:

You can use a PrincipalSearcher and a "query-by-example" principal to do your searching:

// create your domain context
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);

// define a "query-by-example" principal - here, we search for a UserPrincipal 
// and with the first name (GivenName) of "Bruce"
UserPrincipal qbeUser = new UserPrincipal(ctx);
qbeUser.GivenName = "Bruce";

// create your principal searcher passing in the QBE principal    
PrincipalSearcher srch = new PrincipalSearcher(qbeUser);

// find all matches
foreach(var found in srch.FindAll())
{
    // do whatever here - "found" is of type "Principal" - it could be user, group, computer.....          
}

For working with a single principal, the programming interface is also much nicer:

// find a user
UserPrincipal user = UserPrincipal.FindByIdentity(ctx, "SomeUserName");

if(user != null)
{
   // do something here... you can access most of the commonly used properties easily
   user.GivenName = "....";
   user.Surname = "......";
   user.SamAccountName = ".....";
}

// find the group in question
GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, "YourGroupNameHere");

// if found....
if (group != null)
{
   // iterate over members
   foreach (Principal p in group.GetMembers())
   {
      Console.WriteLine("{0}: {1}", p.StructuralObjectClass, p.DisplayName);
      // do whatever you need to do to those members
   }
}

The new S.DS.AM makes it really much easier to play around with users and groups in AD!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文