Search code examples
c#.netwinforms

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 the ID of the userType in the Form constructor and according to that, .Enable = false; buttons they don't have permissions to use.


Solution

  • 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:

    1. By putting AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal); in your startup, you can use Thread.CurrentPrincipal to get the user's security principal.
    2. You can use WindowsIdentity.GetCurrent() to get the current user's identity. You can then create a security principal using 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.