我正在尝试确定我的程序是由具有管理员权限的管理员还是由具有管理员权限的普通用户使用以下代码启动的:
private void Form1_Load(object sender, EventArgs e)
{
WindowsIdentity identity = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(identity);
bool isAdmin = principal.IsInRole(WindowsBuiltInRole.Administrator);
if (isAdmin)
{
ini();
MessageBox.Show("The user is an admin with admin rights");
}
else
{
MessageBox.Show("Error The user is a normal user with admin rights", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
Application.Exit();
}
}
但是当我使用具有管理员权限的普通用户帐户测试此代码时,它会失败,告诉我该用户是具有管理员权限的管理员。
我使用的是.Net 3.5,代码需要与Windows Vista兼容。
有人可以给我一些解决这个问题的想法吗?谢谢!!!
为了澄清一点,另一种看待此问题的方法是:如何确定我的程序(由管理员运行管理员权限)是否在标准用户帐户上下文中运行。
答案 0 :(得分:0)
mmm您需要知道连接到该计算机的用户是否具有管理员权限,但该用户是否属于域控件? (活动目录?)不是BuiltIn的?请澄清。,看一下这篇文章https://social.msdn.microsoft.com/Forums/vstudio/en-US/c2166023-fcfc-4c3c-ba8f-200977971c5d/how-to-check-if-given-user-have-admin-rights-in-c
答案 1 :(得分:0)
需要考虑更多变量,例如操作系统。您使用的是哪个版本的Microsoft Window?请记住,用户访问控制(UAC)是在更高版本中引入的,它可能会影响代码。另一个重要的影响因素是域策略,它通过 Active Directory 进行管理。
为了避免这些限制,我会做以下事情:
private static bool IsElevated()
{
var user = WindowsIdentity.GetCurrent();
var role = WindowsPrincipal(user);
if(Environment.OSVersion.Platform == PlatformID.Win32NT || Environment.OSVersion.Version.Major > 6)
if(user != null)
if(role.IsInRole(WindowsBuiltInRole.Administrator))
return true;
return false;
}
这是一个快速的重新开始,但您要测试代码以确保它正确地查询操作系统和用户。
答案 2 :(得分:0)
我确实解决了它!
解释
我意识到我需要的是会话ID(环境)以某种方式获取登录用户名 (上下文的所有者)。
获取会话ID非常简单:
int session = System.Diagnostics.Process.GetCurrentProcess()。SessionId;
此时,我的目标是将用户名链接到此会话,然后我找到了
Get Windows user name from SessionID
现在,使用用户名我认为很容易检查此用户名是否属于 到管理员组。我错了。我找到的最简单的方法是使用wmi和pinvoke。
主要问题是,为了进行查询,我必须知道当前操作系统中管理员组的名称,这取决于语言。
解决方案是:
http://www.pinvoke.net/default.aspx/advapi32.lookupaccountsid
我调整了代码,将所有部分放在一起,就是这样。
总结一下,我找到了sessionid,找到了链接到session的用户名,找到了OS Administrators组名,并做了一些Wmi查询来检查用户是否是管理员。
这个解决方案适合我,但我必须说运行缓慢。
如果有人可以改进此代码,或者对其他人有用,我就把它留在这里。
请记住添加对System.Management的引用;我使用的是Visual Studio C#Express 2010.该项目是一个Windows窗体应用程序。
快乐的编码!!!
//Make sure to add a reference to System.Management;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Management;
using System.Security.Principal;
using System.Collections;
using System.Runtime.InteropServices;
namespace RealUSer
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//Getting the session id
int session = System.Diagnostics.Process.GetCurrentProcess().SessionId;
//Getting the username related to the session id
string user = GetUsernameBySessionId(session, false);
try
{
//Cheching if the user belongs to the local admin group using wmi
if (CheckAdminRights(user))
{
MessageBox.Show("The logged in User "+user+" is an Admin");
}
else
{
MessageBox.Show("The logged in User " + user + " is not an Admin");
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
/// <summary>
/// This method checks if the context user, belongs to the local administrators group
/// </summary>
/// <param name="username"></param>
/// <returns></returns>
public bool CheckAdminRights(string username)
{
bool result = false;
List<string> admins = new List<string>();
//SelectQuery query = new SelectQuery("Select AccountType from Win32_UserAccount where Name=\"" + username + "\"");
SelectQuery query = new SelectQuery("SELECT * FROM win32_group WHERE Name=\"" + getAdministratorGroupName() + "\"");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
ManagementObjectCollection OC = searcher.Get();
IEnumerator enumerator = OC.GetEnumerator();
enumerator.MoveNext();
ManagementObject O = (ManagementObject)enumerator.Current;
ManagementObjectCollection adminusers = O.GetRelated("Win32_UserAccount");
foreach (ManagementObject envVar in adminusers)
{
admins.Add(envVar["Name"].ToString());
//Console.WriteLine("Username : {0}", envVar["Name"]);
//foreach (PropertyData pd in envVar.Properties)
// Console.WriteLine(string.Format(" {0,20}: {1}", pd.Name, pd.Value));
}
if (admins.Contains(username))
result = true;
return result;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///This code will find the administrators group name, independent of the OS language using the LookupAccountSid function with the BUILTIN\Administrators sid
#region
const int NO_ERROR = 0;
const int ERROR_INSUFFICIENT_BUFFER = 122;
enum SID_NAME_USE
{
SidTypeUser = 1,
SidTypeGroup,
SidTypeDomain,
SidTypeAlias,
SidTypeWellKnownGroup,
SidTypeDeletedAccount,
SidTypeInvalid,
SidTypeUnknown,
SidTypeComputer
}
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern bool LookupAccountSid(
string lpSystemName,
[MarshalAs(UnmanagedType.LPArray)] byte[] Sid,
StringBuilder lpName,
ref uint cchName,
StringBuilder ReferencedDomainName,
ref uint cchReferencedDomainName,
out SID_NAME_USE peUse);
public string getAdministratorGroupName()
{
String result = "";
StringBuilder name = new StringBuilder();
uint cchName = (uint)name.Capacity;
StringBuilder referencedDomainName = new StringBuilder();
uint cchReferencedDomainName = (uint)referencedDomainName.Capacity;
SID_NAME_USE sidUse;
// Sid for BUILTIN\Administrators
byte[] Sid = new byte[] { 1, 2, 0, 0, 0, 0, 0, 5, 32, 0, 0, 0, 32, 2 };
int err = NO_ERROR;
if (!LookupAccountSid(null, Sid, name, ref cchName, referencedDomainName, ref cchReferencedDomainName, out sidUse))
{
err = System.Runtime.InteropServices.Marshal.GetLastWin32Error();
if (err == ERROR_INSUFFICIENT_BUFFER)
{
name.EnsureCapacity((int)cchName);
referencedDomainName.EnsureCapacity((int)cchReferencedDomainName);
err = NO_ERROR;
if (!LookupAccountSid(null, Sid, name, ref cchName, referencedDomainName, ref cchReferencedDomainName, out sidUse))
err = System.Runtime.InteropServices.Marshal.GetLastWin32Error();
}
}
if (err == 0)
{
result = name.ToString();
}
return result;
}
#endregion
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
private void Form1_Load(object sender, EventArgs e)
{
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///This code will retrieve user name given the session id
#region
[DllImport("Wtsapi32.dll")]
private static extern bool WTSQuerySessionInformation(IntPtr hServer, int sessionId, WTS_INFO_CLASS wtsInfoClass, out System.IntPtr ppBuffer, out int pBytesReturned);
[DllImport("Wtsapi32.dll")]
private static extern void WTSFreeMemory(IntPtr pointer);
public static string GetUsernameBySessionId(int sessionId, bool prependDomain)
{
IntPtr buffer;
int strLen;
string username = "SYSTEM";
if (WTSQuerySessionInformation(IntPtr.Zero, sessionId, WTS_INFO_CLASS.WTSUserName, out buffer, out strLen) && strLen > 1)
{
username = Marshal.PtrToStringAnsi(buffer);
WTSFreeMemory(buffer);
if (prependDomain)
{
if (WTSQuerySessionInformation(IntPtr.Zero, sessionId, WTS_INFO_CLASS.WTSDomainName, out buffer, out strLen) && strLen > 1)
{
username = Marshal.PtrToStringAnsi(buffer) + "\\" + username;
WTSFreeMemory(buffer);
}
}
}
return username;
}
public enum WTS_INFO_CLASS
{
WTSInitialProgram,
WTSApplicationName,
WTSWorkingDirectory,
WTSOEMId,
WTSSessionId,
WTSUserName,
WTSWinStationName,
WTSDomainName,
WTSConnectState,
WTSClientBuildNumber,
WTSClientName,
WTSClientDirectory,
WTSClientProductId,
WTSClientHardwareId,
WTSClientAddress,
WTSClientDisplay,
WTSClientProtocolType
}
#endregion
}
}