This simple code excerpt can only be run under SYSTEM account (say in a service). It retrieves the token from the logged on user – especially the user at the physical console. Or in other words the user data of the person that sits in front of the computer. The main code which does the task above can be seen here.

UserToken := TJwSecurityToken.CreateWTSQueryUserToken(WTS_CURRENT_SESSION);

CreateWTSQueryUserToken is only applicable in Windows XP or newer. Use CreateWTSQueryUserTokenEx if you need Windows 2000 support.
WTS_CURRENT_SESSION (-1) defines the console session to be retrieved. Any existing session ID (starting from zero (0) ) can be used instead. If a problems occurs (e.g. session does not exist) you get an exception (see documentation)

uses
  JwaWindows,
  JwsclToken,
  JwsclSid,
  JwsclStrings,
  SysUtils;


var
  UserToken : TJwSecurityToken;
  ConsoleUser : TJwSecurityId;
  UserSidString,
  UserName : TJwString;
begin
  //erst ab Windows XP
  UserToken := TJwSecurityToken.CreateWTSQueryUserToken(WTS_CURRENT_SESSION);
  try
    ConsoleUser := UserToken.TokenUser;
    try
      UserSidString := ConsoleUser.StringSID;
      UserName := ConsoleUser.GetAccountName();
      //Writeln(UserSidString);
      //Writeln(UserName);
    finally
      FreeAndNil(ConsoleUser);
    end;
    //User personifizieren
    UserToken.ImpersonateLoggedOnUser;

    ***

    UserToken.RevertToSelf;

  finally
    FreeAndNil(UserToken);
  end;
end;

***) Place functions and do stuff here that needs to be run under the user’s context. Functions like SHGetSpecialFolder use the impersonated token to get the (correct) user folder. Additionally all security checks are made with the user’s token. This comes very handy because a service has (almost) always access to everything (files, reg keys, …) which means a security hole.

[UPDATE]
Fixed some minor mistakes.