How to use impersonation in .NET Core 3.1?

88 views Asked by At

I have code for a dll in C# in .NET Core 3.1, which is inside an EC2 Windows instance connected to a vpc and which connects to a client's fileserver, the ec2 is already connected to that fileserver with a username and password and with a host. How can I use impersonation in .NET Core 3.1 to execute that dll and save a txt in a fileserver path, having the username, password and host of the fileserver.

Code:

using System; 
using System.DirectoryServices.AccountManagement; 
using System.Globalization; 
using System.IO; 
using System.Linq; 
using System.Reflection.Metadata; 
using System.Runtime.InteropServices; 
using System.Security.Principal; 
using System.Text.RegularExpressions; 
using ConsultarCorreosConinsa.Utils; 
using Microsoft.Win32.SafeHandles; 
using SystemWrapper.Security;

namespace ConsultarCorreosConinsa 
{
    class Program 
    {
        [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)] 
        public static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, out SafeAccessTokenHandle phToken);

        static void Main(string[] args)
        {
            try
            {
                // Supongamos que ya tienes las credenciales del usuario al que deseas impersonar
                string username = "usuario";
                string password = "@dsfS*";
                string domain = "5.6.1.5";
                string docPath = "\\\\5.6.1.5\\\\result";

                // Get the user token for the specified user, domain, and password using the   
                // unmanaged LogonUser method.   
                // The local machine name can be used for the domain name to impersonate a user on this machine.  
                Console.Write("Enter the name of the domain on which to log on: ");
                string domainName = domain;// Console.ReadLine();

                Console.Write("Enter the login of a user on {0} that you wish to impersonate: ", domainName);
                string userName = username;//Console.ReadLine();

                Console.Write("Enter the password for {0}: ", userName);

                const int LOGON32_PROVIDER_DEFAULT = 0;
                // This parameter causes LogonUser to create a primary token.   
                const int LOGON32_LOGON_INTERACTIVE = 2;

                // Call LogonUser to obtain a handle to an access token.   
                SafeAccessTokenHandle safeAccessTokenHandle;
                bool returnValue = LogonUser(userName, domainName, password,
                                             LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT,
                                             out safeAccessTokenHandle);

                if (false == returnValue)
                {
                    int ret = Marshal.GetLastWin32Error();
                    Console.WriteLine("LogonUser failed with error code : {0}", ret);
                    throw new System.ComponentModel.Win32Exception(ret);
                }

                Console.WriteLine("Did LogonUser Succeed? " + (returnValue ? "Yes" : "No"));
                // Check the identity.  
                Console.WriteLine("Before impersonation: " + WindowsIdentity.GetCurrent().Name);

                // Note: if you want to run as unimpersonated, pass  
                //       'SafeAccessTokenHandle.InvalidHandle' instead of variable 'safeAccessTokenHandle'  
                WindowsIdentity.RunImpersonated(safeAccessTokenHandle,
                     // User action  
                     () =>
                           {
                               // Escritura del txt con el  resultado
                               Console.WriteLine("\nEscritura del txt con el resultado...");

                               using (StreamWriter outputFile = new StreamWriter(Path.Combine(docPath, "data.txt")))
                               {
                                   outputFile.WriteLine(result);
                               }

                               // Check the identity.  
                               Console.WriteLine("During impersonation: " + WindowsIdentity.GetCurrent().Name);
                        });

                // Check the identity again.  
                Console.WriteLine("After impersonation: " + WindowsIdentity.GetCurrent().Name);
                Console.WriteLine("\nFinalizado: " + DateTime.Now);
            }
            catch (Exception ex)
            {
                 Console.WriteLine("Error: " + ex.Message);
            }
        }
    }
}

I hope for a solution in .NET Core 3.1 with C#

0

There are 0 answers