我需要檢查用戶是否是運行該應用程序的機器上的管理員。基本上,用戶可能會從另一臺機器提供用戶名,密碼和域名。這些通過WCF傳輸,在這個階段我需要驗證提供的用戶名,密碼和域是否具有該機器的管理權限。這意味着沒有必要使用WMI,因爲一切都是在本地發生的(用戶只需通過WCF發送用戶名,密碼,域作爲字符串)如何檢查用戶是否是該機器上的管理員
用戶可以位於域上,因此可以鏈接到Active Directory,但也可以是本地用戶,這意味着我無法回覆從Active Directory中查找它。
我設法模擬用戶,並可以驗證此用戶是本地組中的管理員。我使用下面的命令測試了這個:
net localgroup administrators
我現在正在用當前模擬用戶創建一個WindowsPrincipal。但是,在檢查此用戶是否爲管理員時,我收到了錯誤信息。這裏是重要的代碼:
// obtains user token
[DllImport("advapi32.dll", SetLastError=true)]
public static extern bool LogonUser(string pszUsername, string pszDomain, string pszPassword,
int dwLogonType, int dwLogonProvider, ref IntPtr phToken);
// closes open handes returned by LogonUser
[DllImport("kernel32.dll", CharSet=CharSet.Auto)]
public extern static bool CloseHandle(IntPtr handle);
// creates duplicate token handle
[DllImport("advapi32.dll", CharSet=CharSet.Auto, SetLastError=true)]
public extern static bool DuplicateToken(IntPtr ExistingTokenHandle,
int SECURITY_IMPERSONATION_LEVEL, ref IntPtr DuplicateTokenHandle);
bool bImpersonated = LogonUser(sUsername, sDomain, sPassword, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref pExistingTokenHandle);
bool bRetVal = DuplicateToken(pExistingTokenHandle, (int)SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, ref pDuplicateTokenHandle);
WindowsIdentity newId = new WindowsIdentity(pDuplicateTokenHandle);
WindowsImpersonationContext impersonatedUser = newId.Impersonate();
WindowsPrincipal wp = new WindowsPrincipal(WindowsIdentity.GetCurrent());
if (wp.IsInRole(WindowsBuiltInRole.Administrator))
{
//is admin
}
else
{
//is not an admin (I am still getting this when user is an admin)
}
bImpersonated返回true(因此模擬工作) bRetVal也會返回true。(因此令牌是有效的)
的模擬代碼是從here(除了管理員檢查)
任何幫助將不勝感激。
模仿用戶,然後獲取活動主體,再檢查'IsInRole'? – 2014-10-01 17:23:52
@PeterRitchie這看起來不錯,但由於某些原因,IsInRole(WindowsBuiltInRole.Administrator)總是返回false(對於本地帳戶和域帳戶)。有任何想法嗎? – seedg 2014-10-02 07:30:56
你有沒有試過[這](http://stackoverflow.com/questions/1089046/in-net-c-test-if-user-is-an-administrative-user)? – 2014-10-02 09:58:58