2008-10-30 83 views
26

我正在寻找一种简单的方法来获取当前Windows用户帐户的SID。我知道我可以通过WMI来实现,但我不想走这条路。如何获取当前Windows帐户的SID?

向所有在C#中回答未指定C++的人道歉。 :-)

+0

编程语言/环境? – 2008-10-30 18:31:57

回答

43

在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); 

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

WindowsIdentity identity = WindowsIdentity.GetCurrent(); 
if (identity != null) 
    Console.WriteLine(identity.User); 
2

​​3210有几个不同的方法,你可以试试... ...你没有提到你想要的语言在溶液中。

如果你想通过一个批处理文件或东西来访问它,你可以看作为PsigetSid Sysinternals。它将SID转换为名称,反之亦然。

0

你没有指定你想要的语言。但是,如果您希望使用C#,本文将提供WMI方法以及使用Win32 API的更快(更详细)的方法。

http://www.codeproject.com/KB/cs/processownersid.aspx

我不认为有目前这样不使用WMI或在Win32 API的另一种方式。

6

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

using System.Security.Principal;

...

变种SID = WindowsIdentity.GetCurrent()用户。

的WindowsIdentity的用户属性返回SID,每MSDN Docs

2

在C#中,你可以使用

using Microsoft.Win32.Security;

...

string username = Environment.UserName + "@" + Environment.GetEnvironmentVariable("USERDNSDOMAIN");

Sid sidUser = new Sid (username);

或...

using System.Security.AccessControl;

using System.Security.Principal;

...

WindowsIdentity m_Self = WindowsIdentity.GetCurrent();

SecurityIdentifier m_SID = m_Self.Owner;");

1

我发现了另一种方式来获得SID:

System.Security.Principal.WindowsIdentity id = System.Security.Principal.WindowsIdentity.GetCurrent(); 
string sid = id.User.AccountDomainSid.ToString(); 
0

这是我认为最短的一个。

UserPrincipal.Current.Sid; 

可用.NET> = 3.5

5
ATL::CAccessToken accessToken; 
ATL::CSid currentUserSid; 
if (accessToken.GetProcessToken(TOKEN_READ | TOKEN_QUERY) && 
    accessToken.GetUser(&currentUserSid)) 
    return currentUserSid.Sid(); 
+0

这非常简洁。 – 2016-10-13 19:50:59

0

而且在本机代码:

function GetCurrentUserSid: string; 

    hAccessToken: THandle; 
    userToken: PTokenUser; 
    dwInfoBufferSize: DWORD; 
    dw: DWORD; 

    if not OpenThreadToken(GetCurrentThread, TOKEN_QUERY, True, ref hAccessToken) then 
     dw <- GetLastError; 
     if dw <> ERROR_NO_TOKEN then 
      RaiseLastOSError(dw); 

     if not OpenProcessToken(GetCurrentProcess, TOKEN_QUERY, ref hAccessToken) then 
      RaiseLastOSError; 
    try 
     userToken <- GetMemory(1024); 
     try 
      if not GetTokenInformation(hAccessToken, TokenUser, userToken, 1024, ref dwInfoBufferSize) then 
       RaiseLastOSError; 
      Result <- SidToString(userToken.User.Sid); 
     finally 
      FreeMemory(userToken); 
    finally 
     CloseHandle(hAccessToken);