Miscellaneous Debris

Avner Kashtan's Frustrations and Exultations
Disposable Unimpersonation

A while ago, I discussed the possibility of using RevertToSelf() to avoid Double Hop problems. I suggested this pattern can be wrapped inside a class implementing IDisposable to easily use it.

This is the implementation of this Unimpersonator class:

Code:

using System;
using System.Runtime.InteropServices;
using System.Security.Principal;
namespace Strawjackal.Utils
{
   public class Unimpersonator : IDisposable
   {
      private WindowsIdentity m_CurrentUser;
     
      public Unimpersonator()
      {
         m_CurrentUser = WindowsIdentity.GetCurrent();
         RevertToSelf();
      }

      public void Dispose()
      {
         if (m_CurrentUser != null)
         m_CurrentUser.Impersonate();
      }

      [DllImport("advapi32.dll")]
      private static extern int RevertToSelf();

   }
}

Usage:

using (new Unimpersonator())
{
   // Perform network access
}

Published Thursday, November 10, 2005 9:40 AM by AvnerK

Filed under: ,

Comments

No Comments

Leave a Comment

(required) 
(required) 
(optional)
(required)