如何使用C#检查用户是否在Active Directory中具有写权限?

时间:2011-02-08 10:37:18

标签: c# .net active-directory directoryentry

在我的.NET 2.0 C#applcation中,我需要确定用户(带密码)是否具有在Active Directory中修改(写入)选项的能力。我希望有一种方法可以使用DirectoryEntry而无需在AD中创建然后删除新对象。

感谢您的帮助。

2 个答案:

答案 0 :(得分:8)

就像Olive说的那样,很难自己做到这一点。这很难做到正确,因为权限可以通过Active Directory组传递到您的用户帐户。因此,为了找出特定用户帐户的有效权限,您必须找出该用户所属的所有组。

幸运的是,Active Directory具有一种称为构造属性的特殊属性。默认情况下,如果使用AD Explorer或ADSI Edit浏览对象,则不会显示这些属性。在ADSI Edit中,您可以设置过滤器以包含这些构造的属性。这里有用的构造属性之一是 allowedAttributesEffective 。它是一个多值属性,它包含当前用户有权写入的所有属性。它由Active Directory即时计算。它负责所有继承,拒绝覆盖和组权限。如果您有权写入 cn 属性,则会将 cn 视为其中的一个值。

以下是检查特定用户对Active Directory上特定对象的特定属性集具有写权限的示例。

static bool CheckWritePermission(string path, string username, string password, string[] properties)
{
    using (DirectoryEntry de = new DirectoryEntry(path, username, password))
    {
        de.RefreshCache(new string[] {"allowedAttributesEffective"});
        return properties.All( property => de.Properties["allowedAttributesEffective"].Contains(property));
    }
}

是的,这不完全是你想要的。您要检查用户是否具有 WriteAllProperties 权限。实际上, WriteAllProperties 权限是对不同属性的写属性权限的集合。您可能需要做一些功课来找出您的应用程序真正关心的属性。然后,只需传递这些属性。

如果您真的不知道要检查哪些属性,那么这个属性应该足够

static bool CheckWritePermission(string path, string username, string password)
{
    using (DirectoryEntry de = new DirectoryEntry(path, username, password))
    {
        de.RefreshCache(new string[] { "allowedAttributesEffective" });
        return de.Properties["allowedAttributesEffective"].Value != null;
    }            
}

在这里,我正在检查返回的 allowedAttributesEffective 是否为null。如果为null,则表示它没有任何写入任何属性的权限。我假设您的管理员要么授予所有写属性权限,要么拒绝所有写属性。我认为在大多数情况下这是一个有效的假设。

答案 1 :(得分:0)

正如您在my question中所看到的,似乎无法简单地找出随机用户对AD内特定对象的权利。

如果有人知道简单方式,请告诉我。