2010-06-23 97 views
0

我有一個Windows窗體應用程序,用戶可以登錄。該應用程序是獨立的,不與任何人或任何人連接。獲取用戶登錄的價值的最佳方式是什麼?

除了創建一個全局變量,我怎麼能有一個容易訪問的變量來檢查當前用戶的權限?

一個不太明智的做事方式就是在Form構造函數中傳遞userType的ID,並根據它,.Enable = false;他們沒有權限使用的按鈕。

謝謝!

回答

3

如果你想的當前登錄的Windows用戶的ID(即應用程序運行時所使用的用戶),也有得到它的方法有兩種:

  1. 通過將AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);在啓動,您可以使用Thread.CurrentPrincipal來獲取用戶的安全主體。
  2. 您可以使用WindowsIdentity.GetCurrent()來獲取當前用戶的身份。然後您可以使用new WindowsPrincipal(identity)創建安全主體。

這些兩者是等價的,並且將讓你security principal有一個IsInRole方法可用於檢查權限。

0

使用WindowsIdentity類獲取System.Security.Principal.WindowsIdentity下的用戶標識。

WindowsIdentity current = WindowsIdentity.GetCurrent(); 
Console.WriteLine("Name:" + current.Name); 

使用WindowsPrincipal類獲取用戶角色,在System.Security.Principal.WindowsPrincipal下找到。

WindowsIdentity current = WindowsIdentity.GetCurrent(); 
WindowsPrincipal principal = new WindowsPrincipal(current); 

if (principal.IsInRole("your_role_here") 
{ 
Console.WriteLine("Is a member of your role"); 
} 
相關問題