我试图弄清楚当前的Windows用户是本地管理员还是可以使用UAC来“获得”该组成员身份。
到目前为止我看到的是这样的:
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转换为名称。应该有办法获得 DirectoryEntry直接使用SID。根据谷歌的说法,这应该有效:
string path = "LDAP://<SID=" + adminIdentifier.ToString() + ">";
但是,这似乎不起作用。知道语法应该是什么样的吗?
答案 0 :(得分:2)
您是否尝试过WindowsPrincipal.IsInRole?
WindowsPrincipal wp = new WindowsPrincipal(WindowsIdentity.GetCurrent());
wp.IsInRole(new SecurityIdentifier("S-1-5-32-544"));
wp.IsInRole(WindowsBuiltInRole.Administrator);
答案 1 :(得分:1)
您是否尝试在与当前用户对应的UserPrincipal对象上使用GetAuthorizationGroups?如果GetAuthorizationGroups不包含计算机本地组,则可能必须检查用户是否直接位于本地管理员组中,或者本地管理员组是否包含用户所在的任何授权组。我没有尝试使用机器上下文,所以我不确定如果在使用时不使用域/全局/通用组计算本地组成员身份,是否还需要搜索后一个匹配的域上下文机器背景。
答案 2 :(得分:0)
这应该是你想要的,除非我误解:
var groupName = adminIdentifier.Translate(typeof(NTAccount)).Value;