C# Impersonation Class for Windows Application

Simple C# class for impersonation in windows application , start impersonation by passing domain name , user name and password. Level are at SecurityAnonymous, SecurityIdentification, SecurityImpersonation, SecurityDelegation

Download

Example Source Snippets -

Impersonator Class


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Diagnostics;
using System.IO;
using System.Security.Principal;
using System.Runtime.InteropServices;

public class Impersonator
    {
        [DllImport("advapi32.dll", SetLastError = true)]
        public static extern bool LogonUser(string pszUsername, string pszDomain, string pszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken);

        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        public static extern bool CloseHandle(IntPtr handle);

        [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        public static extern bool DuplicateToken(IntPtr ExistingTokenHandle, int SECURITY_IMPERSONATION_LEVEL, ref IntPtr DuplicateTokenHandle);

        private static WindowsImpersonationContext wImpersonCxt = (WindowsImpersonationContext)null;

        public static WindowsImpersonationContext ImpersonateStart(string sUsername, string sDomain, string sPassword)
        {
            IntPtr num1 = new IntPtr(0);
            IntPtr num2 = new IntPtr(0);
            IntPtr zero1 = IntPtr.Zero;
            IntPtr zero2 = IntPtr.Zero;
            if (sDomain == "")
                sDomain = Environment.MachineName;
            try
            {
                string str1 = (string)null;
                if (!Impersonator.LogonUser(sUsername, sDomain, sPassword, 2, 0, ref zero1))
                    str1 = "LogonUser() failed with error code: " + (object)Marshal.GetLastWin32Error() + "\r\n";
                string str2 = str1 + "Before impersonation: " + WindowsIdentity.GetCurrent().Name + "\r\n";
                string str3;
                if (!Impersonator.DuplicateToken(zero1, 2, ref zero2))
                {
                    int lastWin32Error = Marshal.GetLastWin32Error();
                    Impersonator.CloseHandle(zero1);
                    str3 = str2 + "DuplicateToken() failed with error code: " + (object)lastWin32Error + "\r\n";
                    return (WindowsImpersonationContext)null;
                }
                 wImpersonCxt = new WindowsIdentity(zero2).Impersonate();
                str3 = str2 + "After impersonation: " + WindowsIdentity.GetCurrent().Name + "\r\n";
                return wImpersonCxt;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (zero1 != IntPtr.Zero)
                    Impersonator.CloseHandle(zero1);
                if (zero2 != IntPtr.Zero)
                    Impersonator.CloseHandle(zero2);
            }
        }

        public static void ImpersonateStop()
        {
            try
            {
                wImpersonCxt.Undo();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        public enum SECURITY_IMPERSONATION_LEVEL
        {
            SecurityAnonymous,
            SecurityIdentification,
            SecurityImpersonation,
            SecurityDelegation,
        }       
    }
       

smartsnipps.ecomparefiles.com © 2019, All Rights Reserved | Disclaimer: smartsnipps.eCompareFiles.com is free to use any code snippets without guarantee