Advertisement
Guest User

Untitled

a guest
Jul 12th, 2013
409
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 4.41 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Linq;
  5. using System.Net;
  6. using System.Runtime.InteropServices;
  7. using System.Security.Principal;
  8. using System.Text;
  9.  
  10. namespace DomainModel.Services
  11. {
  12.     //http://msdn.microsoft.com/en-us/library/windows/desktop/aa378184%28v=vs.85%29.aspx
  13.     public enum LogonType
  14.     {
  15.         LOGON32_LOGON_INTERACTIVE = 2,
  16.         LOGON32_LOGON_NETWORK = 3,
  17.         LOGON32_LOGON_BATCH = 4,
  18.         LOGON32_LOGON_SERVICE = 5,
  19.         LOGON32_LOGON_UNLOCK = 7,
  20.         LOGON32_LOGON_NETWORK_CLEARTEXT = 8, // Win2K or higher
  21.         LOGON32_LOGON_NEW_CREDENTIALS = 9 // Win2K or higher
  22.     };
  23.  
  24.     public enum LogonProvider
  25.     {
  26.         LOGON32_PROVIDER_DEFAULT = 0,
  27.         LOGON32_PROVIDER_WINNT35 = 1,
  28.         LOGON32_PROVIDER_WINNT40 = 2,
  29.         LOGON32_PROVIDER_WINNT50 = 3
  30.     };
  31.  
  32.     public enum ImpersonationLevel
  33.     {
  34.         SecurityAnonymous = 0,
  35.         SecurityIdentification = 1,
  36.         SecurityImpersonation = 2,
  37.         SecurityDelegation = 3
  38.     }
  39.  
  40.     class Win32NativeMethods
  41.     {
  42.         [DllImport("advapi32.dll", SetLastError = true)]
  43.         public static extern int LogonUser(string lpszUserName,
  44.              string lpszDomain,
  45.              string lpszPassword,
  46.              int dwLogonType,
  47.              int dwLogonProvider,
  48.              ref IntPtr phToken);
  49.  
  50.         [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
  51.         public static extern int DuplicateToken(IntPtr hToken,
  52.               int impersonationLevel,
  53.               ref IntPtr hNewToken);
  54.  
  55.         [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
  56.         public static extern bool RevertToSelf();
  57.  
  58.         [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
  59.         public static extern bool CloseHandle(IntPtr handle);
  60.     }
  61.  
  62.     /// <summary>
  63.     /// Allows code to be executed under the security context of a specified user account.
  64.     /// </summary>
  65.     /// <remarks>
  66.     ///
  67.     /// Implements IDispose, so can be used via a using-directive or method calls;
  68.     ///  ...
  69.     ///
  70.     ///  var imp = new Impersonator( "myUsername", "myDomainname", "myPassword" );
  71.     ///  imp.UndoImpersonation();
  72.     ///
  73.     ///  ...
  74.     ///
  75.     ///   var imp = new Impersonator();
  76.     ///  imp.Impersonate("myUsername", "myDomainname", "myPassword");
  77.     ///  imp.UndoImpersonation();
  78.     ///
  79.     ///  ...
  80.     ///
  81.     ///  using ( new Impersonator( "myUsername", "myDomainname", "myPassword" ) )
  82.     ///  {
  83.     ///   ...
  84.     ///   [code that executes under the new context]
  85.     ///   ...
  86.     ///  }
  87.     ///
  88.     ///  ...
  89.     /// </remarks>
  90.     public class Impersonator : IDisposable
  91.     {
  92.         private WindowsImpersonationContext _wic;
  93.                
  94.         public Impersonator(NetworkCredential credentials, LogonType logonType, LogonProvider logonProvider)
  95.         {
  96.             Impersonate(credentials, logonType, logonProvider);
  97.         }
  98.        
  99.         public Impersonator(NetworkCredential credentials)
  100.             : this(credentials, LogonType.LOGON32_LOGON_NEW_CREDENTIALS, LogonProvider.LOGON32_PROVIDER_WINNT50)
  101.         {          
  102.         }
  103.  
  104.         public Impersonator()
  105.         { }
  106.        
  107.         public void Dispose()
  108.         {
  109.             UndoImpersonation();
  110.         }      
  111.        
  112.         public void Impersonate(NetworkCredential credentials, LogonType logonType, LogonProvider logonProvider)
  113.         {
  114.             if (credentials == null) {
  115.                 return;
  116.             }
  117.  
  118.             UndoImpersonation();
  119.  
  120.             IntPtr logonToken = IntPtr.Zero;
  121.             IntPtr logonTokenDuplicate = IntPtr.Zero;
  122.             try {
  123.                 // revert to the application pool identity, saving the identity of the current requestor
  124.                 _wic = WindowsIdentity.Impersonate(IntPtr.Zero);
  125.  
  126.                 // do logon & impersonate
  127.                 if (Win32NativeMethods.LogonUser(
  128.                     credentials.UserName,
  129.                     credentials.Domain,
  130.                     credentials.Password,
  131.                     (int)logonType,
  132.                     (int)logonProvider,
  133.                     ref logonToken) != 0) {
  134.                     if (Win32NativeMethods.DuplicateToken(logonToken, (int)ImpersonationLevel.SecurityImpersonation, ref logonTokenDuplicate) != 0) {
  135.                         var wi = new WindowsIdentity(logonTokenDuplicate);
  136.                         wi.Impersonate(); // discard the returned identity context (which is the context of the application pool)
  137.                     } else
  138.                         throw new Win32Exception(Marshal.GetLastWin32Error());
  139.                 } else
  140.                     throw new Win32Exception(Marshal.GetLastWin32Error());
  141.             }
  142.             finally {
  143.                 if (logonToken != IntPtr.Zero)
  144.                     Win32NativeMethods.CloseHandle(logonToken);
  145.  
  146.                 if (logonTokenDuplicate != IntPtr.Zero)
  147.                     Win32NativeMethods.CloseHandle(logonTokenDuplicate);
  148.             }
  149.         }
  150.  
  151.         /// <summary>
  152.         /// Stops impersonation.
  153.         /// </summary>
  154.         private void UndoImpersonation()
  155.         {
  156.             // restore saved requestor identity
  157.             if (_wic != null)
  158.                 _wic.Undo();
  159.             _wic = null;
  160.         }
  161.     }
  162. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement