Impersonator

by Marcel Wijnands 8. August 2008 23:49

As an addition to my previous post, I wrote a little Class that makes it very easy and safe to execute a piece of code as a different user in ASP.NET (of course it works in Forms as well). Because it implements the IDisposable interface, you can use a Using block in which the code is executed as the supplied user like this;

Using (New Impersonator("DOMAIN", "UserName", "Password"))

    For Each file As String In System.IO.Directory.GetFiles("\\SOMESERVER\SomeShare")

        Response.Write(file)
        Response.Write("<br />")

    Next

End Using

If you need to do this often in your application, and decide to keep a WindowsIdentity somewhere like I demonstrated in my previous post (to increase performance), you can use the other Constructor of the Impersonator Class.

First you can use the Shared Function of the Impersonation Class to get a WindowsIdentity;

Application("FixedIdentity") = Impersonator.GetFixedIdentity("DOMAIN", "UserName", "Password")

Now use the other Constructor;

' Get the WindowsIdentity from where you keep it (in this case the Application Class).
Dim FixedIdentity As WindowsIdentity = Application("FixedIdentity")

Using (New Impersonator(FixedIdentity))

    For Each file As String In System.IO.Directory.GetFiles("\\SOMESERVER\SomeShare")

        Response.Write(file)
        Response.Write("<br />")

    Next

End Using

Nice and simple! Download it below:

Impersonator.zip (1.06 kb)

The idea is based on the C# Impersonator Class written by Uwe Keim.

Tags:

ASP.NET | VB.NET

Comments

10/3/2009 1:03:24 AM #

shyNET|Reviews

..

shyNET|Reviews United Kingdom

11/10/2009 9:56:53 PM #

Scott

This is a great class.

The using block works really well.

Saved me some time.

Thanks

Scott United States

5/23/2012 4:47:05 PM #

pingback

Pingback from dkphp.com

Calling WindowsIdentity.Impersonate does nothing | PHP Developer Resource

dkphp.com

Comments are closed

Powered by BlogEngine.NET 1.5.0.7
Theme by Mads Kristensen | Modified by Mooglegiant