Page Level Impersonation

Sometimes, Global Impersonation in the website is not the right solution, 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

Page level scope‘ means, basically, 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. 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()

So, then, the final way the code would look is as follows:

Dim impersonationContext As System.Security.Principal.WindowsImpersonationContext Dim currentWindowsIdentity As System.Security.Principal.WindowsIdentity Sub Page_Load(Source as Object, E as EventArgs) Try currentWindowsIdentity = CType(User.Identity, System.Security.Principal.WindowsIdentity) impersonationContext = currentWindowsIdentity.Impersonate() ' Here, we get the file list, or whatever needs to be accomplished Catch ex as Exception ' your normal error trapping goes here Finally impersonationContext.Undo() End Try End Sub

Here, we’re putting the Undo for the ImpersonationContext in the ‘Finally’ section, so that, no matter what happens when the code runs (error or code completion), Impersonation is turned off.

Related Posts:

  • No Related Posts
Twitter Digg Delicious Stumbleupon Technorati Facebook Email

No comments yet... Be the first to leave a reply!