-1

I have an application that runs with the system user. I need that some code in the app runs on user context (with the user itself). For example i need to use the webclient in user context because that way my firewall recognize the username, but later i need to run some other code ex. Running a exe in system context (with system user) because i need the privileges.

Is there a way to do this?.

Thanks!!!

gustavosj
  • 3
  • 1
  • 2
  • What you are describing makes no sense. – Erik Philips Oct 25 '17 at 23:10
  • Sorry if is not well explained. In my work we have a proxy that authenticate with kerberos to let the user browse the internet, if the user system tries to access to internet the access is denied. So for that i need to run this in user context but later in the program i have a function that needs to run a exe with admin privileges (classic user is not admin in his own machine) so thats what i need to do. – gustavosj Oct 26 '17 at 00:07

1 Answers1

2

I have used this code to impersonate certain operations

using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Security.Principal;
using NLog;
namespace Core.Impersonation
{
    public class ImpersonatedUser : IDisposable
    {
        private static Logger logger = LogManager.GetCurrentClassLogger();
        IntPtr userHandle;
        WindowsImpersonationContext impersonationContext;
        public ImpersonatedUser(string user, string domain, string password)
        {
            logger.Debug("Impersonating user: " + domain + @"\" + user);
            userHandle = IntPtr.Zero;
            bool loggedOn = LogonUser(
                user,
                domain,
                password,
                LogonType.Interactive,
                LogonProvider.Default,
                out userHandle);

            if (!loggedOn)
                throw new Win32Exception(Marshal.GetLastWin32Error());

            // Begin impersonating the user
            impersonationContext = WindowsIdentity.Impersonate(userHandle);
        }

        public void Dispose()
        {
            if (userHandle != IntPtr.Zero)
            {
                CloseHandle(userHandle);
                userHandle = IntPtr.Zero;
                impersonationContext.Undo();
                logger.Debug("Finished Impersonating user");
            }
        }

        [DllImport("advapi32.dll", SetLastError = true)]
        static extern bool LogonUser(
            string lpszUsername,
            string lpszDomain,
            string lpszPassword,
            LogonType dwLogonType,
            LogonProvider dwLogonProvider,
            out IntPtr phToken
            );

        [DllImport("kernel32.dll", SetLastError = true)]
        static extern bool CloseHandle(IntPtr hHandle);

        enum LogonType : int
        {
            Interactive = 2,
            Network = 3,
            Batch = 4,
            Service = 5,
            NetworkCleartext = 8,
            NewCredentials = 9,
        }

        enum LogonProvider : int
        {
            Default = 0,
        }
    }
}

and then usage:

using (var i = new ImpersonatedUser("someLogin", "someDomain", "thePassword"))
{
    var u = System.Environment.UserName;
}
flyte
  • 1,242
  • 11
  • 18
  • Thanks! is there a way to use the user logged in context insted of send user credentials?. – gustavosj Oct 26 '17 at 12:31
  • if i use this: `using (var i = new ImpersonatedUser("user", "domain", "pass")) { Process startInfo = new Process(); startInfo.StartInfo.FileName = @"c:\windows\system32\cmd.exe"; startInfo.Start(); startInfo.WaitForExit(); var u = System.Environment.UserName; Dispose(); }` the CMD doesnt launch with the expected user. – gustavosj Oct 26 '17 at 13:30
  • If you want to start a process as a different user, then set the appropriate settings in the ProcessStartinfo. see [here](https://stackoverflow.com/questions/6413900/launch-a-process-under-another-users-credentials) for an example. – flyte Oct 26 '17 at 15:38
  • @flyte I don't know how something this useful gets to be the first hit on my search yet have only one upvote in 5 years - go figure. – AlanK Jan 12 '23 at 00:44
  • @AlanK Indeed a mystery! – flyte Jan 12 '23 at 03:29