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. 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开发者_如何学C the ID of the userType in the Form constructor and according to that, .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:
- By putting
AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
in your startup, you can useThread.CurrentPrincipal
to get the user's security principal. - You can use
WindowsIdentity.GetCurrent()
to get the current user's identity. You can then create a security principal usingnew 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.
Use the WindowsIdentity class for getting the users Identity, found under 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.
WindowsIdentity current = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(current);
if (principal.IsInRole("your_role_here")
{
Console.WriteLine("Is a member of your role");
}
精彩评论