我有一个用户可以登录的Windows表单应用程序。该应用程序是单独的,不与任何人或任何人连接。
除了创建全局变量之外,我怎么能有一个易于访问的变量来检查当前用户的权限?
一种不那么犹豫的做事方式就是在Form构造函数中传递userType的ID,并根据它,.Enable = false;按钮,他们没有权限使用。
谢谢!
答案 0 :(得分:3)
如果您想要当前登录的Windows用户的ID(即运行该应用程序的用户),有两种方法可以获取它:
AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
,您可以使用Thread.CurrentPrincipal
来获取用户的安全主体。WindowsIdentity.GetCurrent()
获取当前用户的身份。然后,您可以使用new WindowsPrincipal(identity)
创建安全主体。这两个都是等效的,它会为您提供一个security principal,其IsInRole方法可用于检查权限。
答案 1 :(得分: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");
}