简体   繁体   English

获得所登录用户价值的最佳方法是什么?

[英]What is the best way to get the value of what user is logged in?

I have a Windows form application that users can log into. 我有一个Windows窗体应用程序,用户可以登录。 The application is alone and doesn't connect with anything or anyone. 该应用程序是单独的,无法与任何东西连接。

Besides creating a global variable, how could I have an easily accesible variable to check the current users permissions? 除了创建全局变量之外,我如何拥有一个易于访问的变量来检查当前用户的权限?

A not so kosher way of doing things is just pass the ID of the userType in the Form constructor and according to that, .Enable = false; 一种不太合理的处理方式是在Form构造函数中传递userType的ID,并据此实现.Enable = false;。 buttons they don't have permissions to use. 按钮,他们没有使用权限。

Thanks! 谢谢!

If you want the id of the currently logged on Windows user (ie. the user that the application is running as), there are two ways of getting it: 如果您想要当前登录的Windows用户(即应用程序运行所使用的用户)的ID,可以通过两种方式获取它:

  1. By putting AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal); 通过放置AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal); in your startup, you can use Thread.CurrentPrincipal to get the user's security principal. 在启动时,可以使用Thread.CurrentPrincipal来获取用户的安全主体。
  2. You can use WindowsIdentity.GetCurrent() to get the current user's identity. 您可以使用WindowsIdentity.GetCurrent()获取当前用户的身份。 You can then create a security principal using new WindowsPrincipal(identity) . 然后,您可以使用new WindowsPrincipal(identity)创建安全主体。

Both of these are equivalent, and will get you a security principal that has an IsInRole method that can be used to check permissions. 这两个都是等效的,它们将为您提供一个具有IsInRole方法的安全主体 ,该方法可用于检查权限。

Use the WindowsIdentity class for getting the users Identity, found under System.Security.Principal.WindowsIdentity. 使用WindowsIdentity类获取用户的身份,该类位于System.Security.Principal.WindowsIdentity下。

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

Use the WindowsPrincipal class for getting the users Roles, found under System.Security.Principal.WindowsPrincipal. 使用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");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM