Chapter 32. How to Impersonate a User Given Her Token

If you have a token for a user, it will be represented in the .NET Framework as a WindowsPrincipal (Item 24). You can impersonate that user by telling Windows to attach the token to your thread (Item 31). Here's an example from an ASP.NET Web application.

 <%@page language='c#'%> <%@import namespace='System.Security.Principal'%> <script runat='server'> void Page_Load(object sender, EventArgs args) { IPrincipal p = this.User; WindowsIdentity id = (WindowsIdentity)p.Identity; Response.Output.Write("<h2>Process running as {0}</h2>", WindowsIdentity.GetCurrent().Name); // impersonate temporarily WindowsImpersonationContext wic = id.Impersonate(); try { // do some work while impersonating the client ...

Get The .NET Developer's Guide to Windows Security now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.