How to get the logon SID in C#

后端 未结 4 586
醉梦人生
醉梦人生 2020-11-30 11:42

How does one retrieve the Windows Logon SID in C# .net? (not the user SID, but the unique new one for each session)

4条回答
  •  醉酒成梦
    2020-11-30 11:58

    I just spent a long time getting the SID using TOKEN_USER and so forth, then discovered a shortcut in C#. You still need to get the Process Handle (e.g. https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.process.handle?view=netcore-3.1) and then the token with P/invoke:

    OpenProcessToken(hProcess, TOKEN_READ, out IntPtr hToken))
    

    But once you have the token, you don't need to do any of the nasty GetTokenInformation(hToken, TOKEN_INFORMATION_CLASS.TokenUser... stuff you just use:

    var winId = System.Security.Principal.WindowsIdentity(hToken);
    

    ... and BOOM you can get all the info you want (inc SID) for the user out of winId.

    Don't forget to CloseHandle(hToken) and on hProcess afterwards!

提交回复
热议问题