Execute code in another users context

血红的双手。 提交于 2019-12-05 02:59:35

take a look on A small C# Class for impersonating a User code project article. It implements an IDisposable class (that releases the authentication token after its use). I've seen .NET code leaking due to not releasing the impersonation tokens.

You can impersonate a user only for a block of code that will access the network resource you need to access as a different user. Your code will look like

using ( new Impersonator( "myUsername", "myDomainname", "myPassword" ) )
{
   /* code that executes under the new context */
   ...
}

I hope it helps.

First you need to obtain the user token that you want to start the app as, you can do this using WTSQueryUserToken. If the user is not yet logged on you can use LogonUser Win32 API to obtain a new one in a new session. To get all the sessions on your computer you can use WTSEnumerateSessions.

Then once you have the token you can use CreateProcessAsUser or else ImpersonateLoggedOnUser Win32 APIs.

Please make sure to call CloseHandle on the handles you obtain, they are especially bad leaks for this type of work.

Im not sure this is a way to do this without creating a new process, ImpersonateLoggedOnUser will only work from a service, and I dont want to provide credentials.

correct me if I am wrong

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!