how to use Impersonation in .net core 3.1

0

I have a 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);
        }
    }
juan
asked 6 months ago220 views
No Answers

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions