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;
}