检查给定的用户是否在给定路径的安全组中
问题描述:
我有一个简单的工作,我不知道该如何完成,而当我搜索到更深的工作时,我的工作更加深入。检查给定的用户是否在给定路径的安全组中
我需要编写一个方法,它返回指定文件夹路径上给定用户(我给他的samAccountName,objectGUID)的FileSystemAccessRule
。
我已经做了添加或前一路径移除FileSystemAccessRule
的是这样的:
var fSecurity = Directory.GetAccessControl(physicalPath);
fSecurity.AddAccessRule(new FileSystemAccessRule(samAccountName, FileSystemRights.FullControl, AccessControlType.Allow));
fSecurity.RemoveAccessRule(new FileSystemAccessRule(samAccountName, FileSystemRights.FullControl, AccessControlType.Allow));
Directory.SetAccessControl(physicalPath, fSecurity);
检查,如果给定用户在路径一个类似的工作有一定的访问权限?或者应该去另一种方式?像DirectoryEntry
或LDAP
或Active Directory
左右?
我要的是这可能看起来像这样的方法:
FileSystemAccessRule[] GetAccessRulesOfTheUserOverPath(string samAccountName, string folderPath)
{
/// how?
}
答
2009年,由于SO一些答案,我想出了一个答案。虽然这不是我的问题的确切答案,但它满足了我的需求。在this question的答案我找到了解决方案。此解决方案告诉我给定文件夹的给定FileSystemRights
是否绑定到acl(AuthorizationRuleCollection
)上的当前Windows用户。
在我提到的问题中,几乎所有的答案都给出了结果,在我看来,最准确的答案是@Olivier Jacot-Descombes的答案,因为它计算允许规则,拒绝规则和每个规则的继承规则优先级其他。
因此,我所做的是:
WindowsIdentity _currentUser;
WindowsPrincipal _currentPrincipal;
using (new Impersonator(userName, passwordOfTheUser))
{
_currentUser = WindowsIdentity.GetCurrent();
_currentPrincipal = new WindowsPrincipal(WindowsIdentity.GetCurrent());
}
if (!Directory.Exists(path)) throw new Exception("Directory does not exist");
var di = new DirectoryInfo(path);
var directoryACLs = di.GetAccessControl().GetAccessRules(true, true, typeof(SecurityIdentifier));
///rw_accessRules list consists of the rules for ReadWrite permissons.
bool auth_RW = rw_accessRules.All(aR => HasFileOrDirectoryAccess(_currentUser, _currentPrincipal, aR, directoryACLs));
这里是``HasFileOrDirectoryAccess`方法:
bool HasFileOrDirectoryAccess (WindowsIdentity _currentUser, WindowsPrincipal _currentPrincipal, FileSystemRights right, AuthorizationRuleCollection acl)
{
bool allow = false;
bool inheritedAllow = false;
bool inheritedDeny = false;
foreach (FileSystemAccessRule currentRule in acl)
{
// If the current rule applies to the current user.
if (_currentUser.User.Equals(currentRule.IdentityReference) || _currentPrincipal.IsInRole((SecurityIdentifier)currentRule.IdentityReference))
{
if (currentRule.AccessControlType.Equals(AccessControlType.Deny))
{
if ((currentRule.FileSystemRights & right) == right)
{
if (currentRule.IsInherited)
{
inheritedDeny = true;
}
else
{ // Non inherited "deny" takes overall precedence.
return false;
}
}
}
else if (currentRule.AccessControlType.Equals(AccessControlType.Allow))
{
if ((currentRule.FileSystemRights & right) == right)
{
if (currentRule.IsInherited)
{
inheritedAllow = true;
}
else
{
allow = true;
}
}
}
}
}
if (allow)
{ // Non inherited "allow" takes precedence over inherited rules.
return true;
}
return inheritedAllow && !inheritedDeny;
}
我第一次模拟所给用户,让他的本金和身份,那么检查他是否具有给定规则集的权限。
这一个适用于我的情况,但你会注意到,我们需要用户的密码,我们要检查的权限。如果有什么方法可以在没有密码的情况下做到这一点,那将会很棒。