如何获取当前Windows帐户的SID?

Fra*_*nov 30 c++ windows sid

我正在寻找一种简单的方法来获取当前Windows用户帐户的SID.我知道我可以通过WMI做到这一点,但我不想走那条路.

向在C#中回答的所有人道歉,因为没有指定它的C++.:-)

Rog*_*mbe 50

在Win32中,调用GetTokenInformation,传递令牌句柄和TokenUser常量.它将为您填写TOKEN_USER结构.其中一个元素是用户的SID.它是BLOB(二进制),但您可以使用ConvertSidToStringSid将其转换为字符串.

要获取当前令牌句柄,请使用OpenThreadTokenOpenProcessToken.

如果你更喜欢ATL,它有CAccessToken类,里面有各种有趣的东西.

.NET具有Thread.CurrentPrinciple属性,该属性返回IPrincipal引用.你可以得到SID:

IPrincipal principal = Thread.CurrentPrincipal;
WindowsIdentity identity = principal.Identity as WindowsIdentity;
if (identity != null)
    Console.WriteLine(identity.User);
Run Code Online (Sandbox Code Playgroud)

同样在.NET中,您可以使用WindowsIdentity.GetCurrent(),它返回当前用户ID:

WindowsIdentity identity = WindowsIdentity.GetCurrent();
if (identity != null)
    Console.WriteLine(identity.User);
Run Code Online (Sandbox Code Playgroud)


dex*_*ack 8

ATL::CAccessToken accessToken;
ATL::CSid currentUserSid;
if (accessToken.GetProcessToken(TOKEN_READ | TOKEN_QUERY) &&
    accessToken.GetUser(&currentUserSid))
    return currentUserSid.Sid();
Run Code Online (Sandbox Code Playgroud)

  • 这非常简洁。 (3认同)

Jef*_*yer 7

这应该给你你需要的东西:

使用System.Security.Principal;

...

var sid = WindowsIdentity.GetCurrent().User;

WindowsIdentity的User属性返回每个MSDN Docs的SID