0

How can c# service get the identity (logon name) of a terminal server user that calls it?

I wrote a c# service that listens for http request and return the current logon user. The request is initialized by a javascript that runs in the browser. That worked well so far, but it doesn't work on terminal server where there can be multiple users that are connected simultaneously. What I'm currently doing is query for the processId of "explorer" and then use "GetOwner" to get the user logon name.

Is there a way for the service to identify the user that generated the http request for it? Can I somehow get the http session and identify the user that owns it? I need to return as response the user identity.

Thanks, JJ

seva titov
  • 11,720
  • 2
  • 35
  • 54
user1283002
  • 391
  • 1
  • 4
  • 12

1 Answers1

0

You'd need to get the port that the HTTP request is using on the client side, match that against the list of active outbound TCP connections on the machine and identify the process ID of the browser (e.g. via GetExtendedTcpTable). From there you could get the session ID of the process (e.g. by using Process.SessionId) and then look up the username associated with the session (e.g. by using WTSQuerySessionInformation or Cassia). Or you could call OpenProcess and GetSecurityInfo to get the user's SID from the process ID as this answer explains. This latter approach is probably better since there could be processes running as different users in a single session (e.g. using Run As).

That all seems like a real pain, though. Couldn't you just use Windows authentication in the browser?

Community
  • 1
  • 1
Dan Ports
  • 1,421
  • 9
  • 7
  • Thank you for the thorough answer (and comment on Cassia forum). – user1283002 Jan 20 '13 at 15:29
  • Thank you so much for your thorough answer (and comment on Cassia forum). This is indeed a big pain, but I need it since I need to automatically get the user name without any action on his behalf. Any chance you can point me to code samples? I'm a novice C# developer. – user1283002 Jan 20 '13 at 15:36
  • Sure -- here's a [GetExtendedTcpTable sample](http://www.timvw.be/2007/09/09/build-your-own-netstatexe-with-c/) and a [sample showing how to get a process's owner's name](http://msmvps.com/blogs/siva/archive/2006/10/02/Getting-Windows-Process-Owner-Name.aspx). – Dan Ports Jan 26 '13 at 20:16