简体   繁体   中英

Getting the current logged in user (FullToken Context)

I have a Problem, which is... i start a programm with right click -> run as administrator. Which means the programm is running in an administrative context.

WindowsIdentity.GetCurrent().Name;

if i try to get the user name that way i will get the user that started the programm as admin.. for example "administrator", but what i need is the name of the current logged in user which is for example: bob

Can anybody help me out? :)

You could try using WMI (System.Management.dll) to get the owner of the explorer.exe process.

string GetExplorerUser()
{
    var query = new ObjectQuery(
        "SELECT * FROM Win32_Process WHERE Name = 'explorer.exe'");

    var explorerProcesses = new ManagementObjectSearcher(query).Get();

    foreach (ManagementObject mo in explorerProcesses)
    {
        string[] ownerInfo = new string[2];
        mo.InvokeMethod("GetOwner", (object[])ownerInfo);

        return String.Concat(ownerInfo[1], @"\", ownerInfo[0]);
    }

    return string.Empty;
}

This relies on the fact that the explorer process is single instance an so you don't end up with the possibility of having several explorer processes running with different user credentials.

1) Cassia should be able to give you a list of currently logged in users including RDC.

foreach (ITerminalServicesSession sess in new TerminalServicesManager().GetSessions())
{
    // sess.SessionId
    // sess.UserName
}

2) WMI (SO answer )

Select * from Win32_LogonSession

3) PInvoke to WTSEnumerateSessions

4) Enumerate all instances of "explorer.exe" and get the owner using PInvoke ( OpenProcessHandle ).

Process[] processes = Process.GetProcessesByName("explorer");

This is a bit hacky. WMI can also be used for this.

It might be a good idea to set winmgmt as a dependency for your service if you decided to go with solution that uses WMI.

You will probably need to use win32 API for that. Read about Window Station and Desktop functions here: http://msdn.microsoft.com/en-us/library/ms687107%28v=vs.85%29.aspx

Also see this question: Get the logged in Windows user name associated with a desktop

Maybe you could start as normal user, save user name, then programmatically request elevation :

Windows 7 and Vista UAC - Programmatically requesting elevation in C#

All .NET libraries will give you the user from the current context ('Administrator' in your case).

If you are trying to secure your code, you might consider reading about: Security in the .NET framework

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.

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