LdapDistinguishedNameEncode 如何与 C# DirectoryServices 库一起使用?

How does LdapDistinguishedNameEncode work with the C# DirectoryServices library?

我正在尝试清理用户为 C# 应用程序输入的 OU 名称。

AntiXSS 的 LdapDistinguishedNameEncode 似乎是为此定制的,但是当我尝试在 OU 的名称上使用它时,将它插入到一个可分辨的名称中,并将它传递到一个 PrincipalContextDirectoryEntry object 我收到无法找到该对象的异常。

当使用未净化的 OU 名称时,一切正常。

AD 库是否理解编码的专有名称?或者 LdapDistinguishedNameEncode 的预期是 运行 OU 创建之前以及以后引用它时?

示例代码,其中 ouName 是 "Bob-Marley" 或 "dlanod's company",破折号和撇号被编码:

        var distinguishedName = $"OU={Encoder.LdapDistinguishedNameEncode(ouName)},DC=sample,DC=net";

        try
        {
            // Create a context for the OU
            var context = new PrincipalContext(ContextType.Domain, _targetedUrl, distinguishedName, ContextOptions.Negotiate | ContextOptions.Signing | ContextOptions.Sealing);
        }
        catch (Exception e)
        {
            _logger.Error(e, "Organization {0} with definition {1} could not be found, exception occurred {2}", ouName, distinguishedName, e);
        }

我建议您尝试 LdapDistinguishedNameEncode(string, bool, bool) 重载。摘自 AntiXSS 4.0 Released:

LdapDistinguishedNameEncode(string, bool, bool) is also provided so you may turn off the initial or final character escaping rules, for example if you are concatenating the escaped distinguished name fragment into the midst of a complete distinguished name.

希望对您有所帮助!

我没有找到仍然让我使用 LdapDistinguishedNameEncode 的可行方法。

我采用的代码是:

        // Reject organization names with illegal or problematic characters (taken from RFC2253).
        // Used instead of Encoder.LdapDistinguishedNameEncode because of an expectation that
        // the creation passes through the same function.
        // https://social.technet.microsoft.com/wiki/contents/articles/5312.active-directory-characters-to-escape.aspx
        char[] illegalChars = {',', '\', '#', '+', '<', '>', ';', '"', '='};
        if (name.IndexOfAny(illegalChars) >= 0)
        {
            return false;
        }