title: How can I get the current user token for the physical session?
body: <p>I have some code, with which I'm trying to get the current session user token:</p>
  
  <pre><code>#include &lt;Wtsapi32.h&gt;
  
  DWORD activeSessionId = WTSGetActiveConsoleSessionId();
  
  HANDLE currentToken;
  BOOL queryRet = WTSQueryUserToken(activeSessionId, &amp;currentToken);
  
  if (!queryRet) {
      DWORD err = GetLastError();
      return 0;
  }
  </code></pre>
  
  <p>Value of err is 1314.</p>
  
  <h1>Update 1</h1>
  
  <p>No luck so far, tried to grant the current process SE_TCB_NAME - but still get same error from WTSQueryUserToken (1314).</p>
  
  <pre><code>HANDLE process = GetCurrentProcess();
  
  HANDLE processToken;
  BOOL openTokenRet = OpenProcessToken(
      process, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &amp;processToken);
  
  if (!openTokenRet)
  {
      DWORD err = GetLastError();
      return 0;
  }
  
  TOKEN_PRIVILEGES tokenPrivs;
  BOOL lookupRet = LookupPrivilegeValue(
      NULL, SE_TCB_NAME, &amp;tokenPrivs.Privileges[0].Luid);
  
  if (!lookupRet)
  {
      DWORD err = GetLastError();
      return 0;
  }
  
  tokenPrivs.PrivilegeCount = 1;
  tokenPrivs.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
  
  BOOL adjustRet = AdjustTokenPrivileges(
      processToken, FALSE, &amp;tokenPrivs, 0, (PTOKEN_PRIVILEGES)NULL, 0);
  
  if (!adjustRet)
  {
      DWORD err = GetLastError();
      return 0;
  }
  
  // get the user in the active session
  HANDLE currentToken;
  BOOL queryRet = WTSQueryUserToken(activeSessionId, &amp;currentToken);
  
  if (!queryRet) {
      DWORD err = GetLastError();
      return 0;
  }
  </code></pre>
  
  <h1>Update 2:</h1>
  
  <p>Added some more debug info, but prevState.PrivilegeCount is 0...</p>
  
  <pre><code>TOKEN_PRIVILEGES prevState;
  DWORD prevStateLen = 0;
  
  BOOL adjustRet = AdjustTokenPrivileges(
      processToken, FALSE, &amp;tokenPrivs, 
      sizeof(TOKEN_PRIVILEGES), &amp;prevState, &amp;prevStateLen);
  
  DWORD adjustErr = GetLastError();
  if (!adjustRet)
  {
      return 0;
  }
  </code></pre>
  
  <h1>Solution:</h1>
  
  <p>Looks like WTSQueryUserToken can only be used when running as LocalSystem, which means I'll have to run as a service and debug from there... Doh!</p>