Sometimes, global Impersonation in the website may not be the correct solution for you. However, it is possible to provide Impersonation at the page level. To do this, you can provide Impersonation for the page, using the current logged in identity of the person viewing the page. One specific need in which this might be handy, is a situation in which your website has an ASPX page, using the System.IOnamespace, and you’re dynamically getting a file listing from another server.

To start, you need to provide/dimension a couple of variables, with a page level scope:

Dim impersonationContext As System.Security.Principal.WindowsImpersonationContext
Dim currentWindowsIdentity As System.Security.Principal.WindowsIdentity

Actually, ‘Page level scope‘ basically means that you do not include these statements within an event handler. They’re normally put at the top of the document. If you’re using a <script> tag, put them just inside the tag. If you’re using code-behind, put them inside the class signature, and outside the event handlers. Of course, you should put all your code inside a Try/Catch block, and, for the sake of this Tutorial, we’ll assume that you’ll be using Impersonation inside the Page_Load event. The next bit of code you’d need, would be the parts that actually do the Impersonation:

currentWindowsIdentity = CType(User.Identity, System.Security.Principal.WindowsIdentity)
impersonationContext = currentWindowsIdentity.Impersonate()

This uses User.Identity (the currently logged in user), and sets the Impersonation to that person. After impersonation is ‘turned on’, you then add your code which requires impersonation at that point.

The last thing we would want to do is to remove the Impersonation, immediately after the need has been removed. In this case, once the list of files has been received and displayed, we have no more need for setting Impersonation, so we’d need to remove it. To do this, it’s only one line of code:

impersonationContext.Undo()

What would be best, here, is to put the UNDO portion in the Finally section of a Try/Catch block so that, no matter what happens when the code runs, Impersonation is then turned off.