andrew4582

ImpersonationContext

Nov 14th, 2011
337
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 4.31 KB | None | 0 0
  1. using System;
  2. using System.Runtime.InteropServices;
  3. using System.Security.Principal;
  4.  
  5. namespace Core.Security {
  6.     /// <summary>
  7.     /// Impersonates a windows user within the context of a disposable pattern:
  8.     ///<example>
  9.     /// using(ImpersonationContext context = ImpersonationContext.ImpersonateUser("Joe","MyDomain","MyPasswrd")) {
  10.     ///     //Do stuff under impersonated user credentials
  11.     /// }
  12.     /// </example>
  13.     /// </summary>
  14.     public class ImpersonationContext:IDisposable {
  15.  
  16.         public static ImpersonationContext ImpersonateUser(String userName,String domain,String password) {
  17.             var context = new ImpersonationContext();
  18.             if(context.ImpersonateValidUser(userName,domain,password)) {
  19.                 return context;
  20.             }
  21.             return null;
  22.         }
  23.  
  24.         WindowsImpersonationContext _impersonationContext;
  25.         bool _impersonating;
  26.  
  27.         ImpersonationContext() {
  28.            
  29.         }
  30.  
  31.         const int LOGON32_LOGON_INTERACTIVE = 2;
  32.         const int LOGON32_PROVIDER_DEFAULT = 0;
  33.  
  34.         [DllImport("advapi32.dll")]
  35.         static extern int LogonUserA(String lpszUserName,
  36.             String lpszDomain,
  37.             String lpszPassword,
  38.             int dwLogonType,
  39.             int dwLogonProvider,
  40.             ref IntPtr phToken);
  41.  
  42.         [DllImport("advapi32.dll",CharSet = CharSet.Auto,SetLastError = true)]
  43.         static extern int DuplicateToken(IntPtr hToken,
  44.             int impersonationLevel,
  45.             ref IntPtr hNewToken);
  46.  
  47.         [DllImport("advapi32.dll",CharSet = CharSet.Auto,SetLastError = true)]
  48.         static extern bool RevertToSelf();
  49.  
  50.         [DllImport("kernel32.dll",CharSet = CharSet.Auto)]
  51.         static extern bool CloseHandle(IntPtr handle);
  52.  
  53.         bool ImpersonateValidUser(String userName,String domain,String password) {
  54.            
  55.             _impersonating = false;
  56.  
  57.             WindowsIdentity tempWindowsIdentity;
  58.             IntPtr token = IntPtr.Zero;
  59.             IntPtr tokenDuplicate = IntPtr.Zero;
  60.  
  61.             if(RevertToSelf()) {
  62.                 if(LogonUserA(userName,domain,password,LOGON32_LOGON_INTERACTIVE,
  63.                     LOGON32_PROVIDER_DEFAULT,ref token) != 0) {
  64.                     if(DuplicateToken(token,2,ref tokenDuplicate) != 0) {
  65.                         tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
  66.                         _impersonationContext = tempWindowsIdentity.Impersonate();
  67.                         if(_impersonationContext != null) {
  68.                             CloseHandle(token);
  69.                             CloseHandle(tokenDuplicate);
  70.                             _impersonating = true;
  71.                             return true;
  72.                         }
  73.                     }
  74.                 }
  75.             }
  76.             if(token != IntPtr.Zero)
  77.                 CloseHandle(token);
  78.             if(tokenDuplicate != IntPtr.Zero)
  79.                 CloseHandle(tokenDuplicate);
  80.             return false;
  81.         }
  82.  
  83.         void UndoImpersonation() {
  84.             if(_impersonationContext == null)
  85.                 return;
  86.             _impersonationContext.Undo();
  87.         }
  88.  
  89.         #region IDisposable Pattern
  90.  
  91.         protected bool IsDisposed { get; private set; }
  92.  
  93.         protected void EnsureNotDisposed() {
  94.             if(IsDisposed)
  95.                 throw new ObjectDisposedException(GetType().Name);
  96.         }
  97.  
  98.         public virtual void Dispose() {
  99.             if(IsDisposed)
  100.                 throw new ObjectDisposedException(this.GetType().Name);
  101.             try {
  102.                 this.Dispose(true);
  103.             }
  104.             finally {
  105.                 GC.SuppressFinalize(this);
  106.             }
  107.         }
  108.         protected virtual void Dispose(bool disposing) {
  109.  
  110.             if(disposing) {
  111.                 try {
  112.                     if(!IsDisposed) {
  113.                         if(_impersonating)
  114.                             UndoImpersonation();
  115.                     }
  116.                 }
  117.                 finally {
  118.                     IsDisposed = true;
  119.                 }
  120.             }
  121.  
  122.         }
  123.         //Only add Finalizer in you need to dispose of resources with out call Dispose() directly
  124.         ~ImpersonationContext() {
  125.             Dispose(!IsDisposed);
  126.         }
  127.         #endregion
  128.     }
  129. }
Advertisement
Add Comment
Please, Sign In to add comment