.net 快速获得组成员资格
我试图弄清楚当前的windows用户是本地管理员还是可以使用UAC“获得”该组成员资格 到目前为止,我得出的结论如下:.net 快速获得组成员资格,.net,windows,membership,active-directory-group,.net,Windows,Membership,Active Directory Group,我试图弄清楚当前的windows用户是本地管理员还是可以使用UAC“获得”该组成员资格 到目前为止,我得出的结论如下: var adminIdentifier = new SecurityIdentifier("S-1-5-32-544"); var current = WindowsIdentity.GetCurrent(); bool isAdmin = current.Groups.Contains(adminIdentifier); bool canBeAdmin = isAdmin;
var adminIdentifier = new SecurityIdentifier("S-1-5-32-544");
var current = WindowsIdentity.GetCurrent();
bool isAdmin = current.Groups.Contains(adminIdentifier);
bool canBeAdmin = isAdmin;
if (!isAdmin)
{
var adminGroupName = adminIdentifier.Translate(typeof(NTAccount)).Value;
adminGroupName = adminGroupName.Substring(adminGroupName.LastIndexOf('\\'));
string path = "WinNT://./" + adminGroupName + ",group";
using (DirectoryEntry groupEntry = new DirectoryEntry(path))
{
foreach (object member in (IEnumerable)groupEntry.Invoke("Members"))
{
using (DirectoryEntry memberEntry = new DirectoryEntry(member))
{
object obVal = memberEntry.Properties["objectSid"].Value;
SecurityIdentifier sid = null;
if (null != obVal)
{
sid = new SecurityIdentifier((Byte[])obVal,0);
}
canBeAdmin = Equals(current.User, sid);
if (canBeAdmin)
break;
}
}
}
}
Console.WriteLine(canBeAdmin +" "+isAdmin);
此解决方案需要几毫秒的计算时间。比我以前尝试的基于System.DirectoryServices.AccountManagement的方法快得多
不过,还有最后一件事困扰着我。我必须将管理员组的SecurityIdentifier转换为名称。应该有一种方法可以得到它
使用SID直接创建DirectoryEntry。根据谷歌的说法,这应该是可行的:
string path = "LDAP://<SID=" + adminIdentifier.ToString() + ">";
string path=“LDAP://”;
然而,这似乎不起作用。你知道语法应该是什么样子吗?你试过在与当前用户对应的UserPrincipal对象上使用吗?如果GetAuthorizationGroups不包括计算机本地组,您可能需要检查用户是否直接在本地administrators组中,或者本地administrators组是否包含用户所在的任何授权组。我没有在机器上下文中尝试过这一点,因此我不确定如果在使用机器上下文时没有使用域/全局/通用组计算本地组成员身份,是否还需要在域上下文中搜索后一个匹配项。这应该是您想要的,除非我误解了:
var groupName = adminIdentifier.Translate(typeof(NTAccount)).Value;
你试过了吗
GetAuthorizationGroups()会产生相同的结果,但遗憾的是性能相同(缺乏)。WindowsPrincipal.IsInRole()在非提升模式下运行时,对于管理员组返回false。这就是为什么我必须以另一种方式确定组成员身份。我的问题陈述可能不够清楚:-)我有:windows组的SecurityIdentifier。我需要:该组的DirectoryEntry当前,我必须将SID转换为名称。我想摆脱这种转换。在我可能给出另一个答案之前,先问几个问题。。。a) 您使用的是什么版本的Windows?b)您能否确认adminIdentifier.ToString()的计算结果为“S-1-5-32-544”,c)您在查询LDAP时是否遇到任何特定错误?a)Windows Vista Ultimate。b) 对。c) 错误表示找不到指定的域。我的电脑不在任何领域,所以这可能是一个线索。但是,我需要一个无论计算机是否在域中都能工作的解决方案。语法很好。。我知道它很有效,因为我也在使用它。我想这对KnownsID不起作用
WindowsPrincipal wp = new WindowsPrincipal(WindowsIdentity.GetCurrent());
wp.IsInRole(new SecurityIdentifier("S-1-5-32-544"));
wp.IsInRole(WindowsBuiltInRole.Administrator);