Workaround for Double Hop issue

on Friday, November 13, 2009

public class UnImpersonator : IDisposable
    {
        [DllImport("advapi32.dll")]
        private static extern int RevertToSelf();

        private WindowsIdentity connectedUser = null;

        public UnImpersonator()
        {
            connectedUser = WindowsIdentity.GetCurrent();
            RevertToSelf();
        }

        void IDisposable.Dispose()
        {
            connectedUser.Impersonate();
        }
    }





//Sample Usage 




protected void Page_Load(object sender, EventArgs e)
        {
           
            if (!IsPostBack)
            {
                using (new UnImpersonator())
                {
                    SqlConnection cn = new SqlConnection("Data Source=servername;Initial Catalog=Employee;Integrated Security=true;");
                    SqlCommand cm = new SqlCommand("select empid,empname from employee", cn);
                    cn.Open();
                    ddlEmployee.DataSource = cm.ExecuteReader();
                    ddlEmployee.DataTextField = "empname";
                    ddlEmployee.DataValueField = "empid";
                    ddlEmployee.DataBind();
                    cn.Close();
                    cn.Dispose();
                }
            }

        }

0 comments: