获取用户登录值的最佳方法是什么?

时间:2010-06-23 23:19:46

标签: c# .net winforms

我有一个用户可以登录的Windows表单应用程序。该应用程序是单独的,不与任何人或任何人连接。

除了创建全局变量之外,我怎么能有一个易于访问的变量来检查当前用户的权限?

一种不那么犹豫的做事方式就是在Form构造函数中传递userType的ID,并根据它,.Enable = false;按钮,他们没有权限使用。

谢谢!

2 个答案:

答案 0 :(得分:3)

如果您想要当前登录的Windows用户的ID(即运行该应用程序的用户),有两种方法可以获取它:

  1. 通过在您的启动中添加AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);,您可以使用Thread.CurrentPrincipal来获取用户的安全主体。
  2. 您可以使用WindowsIdentity.GetCurrent()获取当前用户的身份。然后,您可以使用new WindowsPrincipal(identity)创建安全主体。
  3. 这两个都是等效的,它会为您提供一个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");
}
相关问题