I try to use information from this post: https://stackoverflow.com/a/251267/393087
And the code I came up with is:
HANDLE hToken;
OpenProcessToken(GetCurrentProcess(),TOKEN_ADJUST_PRIVILEGES, &hToken);
DWORD dwSize;
TOKEN_INFORMATION_CLASS tokenInformationClass;
GetTokenInformation(hToken, tokenInformationClass, NULL, sizeof(TOKEN_INFORMATION_CLASS), &dwSize);
Ok, so I got TOKEN_INFORMATION_CLASS
, but how to get from this to PSID
that ConvertSidToStringSid()
needs ? There is nowhere PSID
word in tic manual page ( http://msdn.microsoft.com/en-us/library/windows/desktop/aa379626(v=vs.85).aspx ).
Well actually this is trivial. Pick whatever token information class you want (my guess is you want TokenUser
) and then make sure you pass the matching TOKEN_USER
struct to GetTokenInformation
, then reach into the TOKEN_USER
struct to access TOKEN_USER::User::Sid
to get the PSID
.
Of course you may also want another token information class, but the principle is the same. Complete sample program (compiled as .cpp
file in MSVC):
#ifndef _WIN32_WINNT
#define _WIN32_WINNT 0x0500
#endif
#include <stdio.h>
#include <tchar.h>
#include <Windows.h>
#include <Sddl.h> // for ConvertSidToStringSid()
BOOL printTokenUserSid(HANDLE hToken)
{
PTOKEN_USER ptu = NULL;
DWORD dwSize = 0;
if(!GetTokenInformation(hToken, TokenUser, NULL, 0, &dwSize)
&& ERROR_INSUFFICIENT_BUFFER != GetLastError())
{
return FALSE;
}
if(NULL != (ptu = (PTOKEN_USER)LocalAlloc(LPTR, dwSize)))
{
LPTSTR StringSid = NULL;
if(!GetTokenInformation(hToken, TokenUser, ptu, dwSize, &dwSize))
{
LocalFree((HLOCAL)ptu);
return FALSE;
}
if(ConvertSidToStringSid(ptu->User.Sid, &StringSid))
{
_tprintf(_T("%s\n"), StringSid);
LocalFree((HLOCAL)StringSid);
LocalFree((HLOCAL)ptu);
return TRUE;
}
LocalFree((HLOCAL)ptu);
}
return FALSE;
}
int _tmain(int argc, _TCHAR* argv[])
{
HANDLE hToken = NULL;
if(OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, FALSE, &hToken)
|| OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken))
{
if(!printTokenUserSid(hToken))
{
_tprintf(_T("Something failed, Win32 error: %d\n"), GetLastError());
}
CloseHandle(hToken);
}
return 0;
}