Run code in a different user context

I have an application with a manifest that requires it to run as an administrator, but part of the application is to map the drive using WNetAddConnection2, which, in my opinion, requires it to run in the normal user context due to credentials, etc. . Is there a way to execute this bit of code in a normal user context without creating a separate process.

EDIT

From the comments I got this far, but it does not work. I expected this to not be the case, as I really do not understand how I should use it. Perhaps it is better if I open a new question?

class Program { [DllImport("advapi32.DLL")] public static extern bool ImpersonateLoggedOnUser(IntPtr hToken); [DllImport("advapi32.DLL")] public static extern bool RevertToSelf(); static void Main(string[] args) { IntPtr phToken = IntPtr.Zero; ImpersonateLoggedOnUser(phToken); MapDrives(); RevertToSelf(); } } 

EDIT

If the current user has administrator privileges, then the main process is promoted with a manifest, in the promoted code I want to run the command in a non-expert user space, since it has different environment variables, etc. I believe that when a thread is started, it cannot change itself, it needs to start a new one.

+7
c # winapi uac pinvoke
source share
3 answers

I'm not sure if this is the way to do this without creating a new process, ImpersonateLoggedOnUser will only work from the service, and I don't want to provide credentials.

correct me if i'm wrong

0
source share

take a look at the C # Small Class to personify a user project project article . It implements the IDisposable class (which frees the authentication token after using it). I have seen a .NET code leak due to the impersonation tokens not being released.

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

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

Hope this helps.

+4
source share

First you need to get the token of the user you want to run as an application, you can do this using WTSQueryUserToken . If the user is not logged in yet, you can use the LogonUser Win32 API to get 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 the CreateProcessAsUser or the ImpersonateLoggedOnUser Win32 API.

Please remember to call CloseHandle on the pens you receive, they are especially bad leaks for this type of work.

+1
source share

All Articles