I need to restrict access to my application to only one specific user account. I have found classes under WMI to find users accounts, but I don´t know how to recognize which one is running my app.
There are simpler ways to get the current username than using WMI.
WindowsIdentity.GetCurrent() . Name will get you the name of the current Windows user.
Environment.Username will get you the name of the currently logged on user.
The difference between these two is that WindowsIdentity.GetCurrent().Name
will also include the domain name as well as the username (ie. MYDOMAIN\\adrian
instead of adrian
). If you need the domain name from Environment
, you can use Environment.UserDomainName .
EDIT
If you really want to do it using WMI, you can do this:
ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT UserName FROM Win32_ComputerSystem");
ManagementObjectCollection collection = searcher.Get();
string username = (string) collection.Cast<ManagementBaseObject>().First()["UserName"];
Unfortunately, there is no indexer property on ManagementObjectCollection
so you have to enumerate it to get the first (and only) result.
You don't necessarily need to use WMI. Check out WindowsIdentity .
var identity = WindowsIdentity.GetCurrent();
var username = identity.Name;
The simplest approach is through the Environment class:
string user = Environment.UserDomainName + "\\" + Environment.UserName;
There also are several ways to restrict to a certain user (although checking for a role is more common).
Apart from the obvious
if (userName == "domain\\john")
{ }
You can also use the following attribute on an entire class or specific methods:
[PrincipalPermission(SecurityAction.Demand, Name = "domain\\john",
Authenticated = true)]
void MyMethod()
{
}
Which could be a bit more reliable for low-level, reusable methods.
Note that you could use both, checking for a user with if() as part of the normal flow of the program and the attribute as a safeguard on critical methods.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.