Get Help:Ask a Question in our Forums|Report a Bug|More Help Resources
Last post Mar 19, 2012 06:24 AM by Steven Cheng - MSFT
Mar 11, 2012 11:11 AM|LINK
I have code running and in the web.config I have "identity impersonate = true". But I have noticed that part of my code fails when that settings is on.
Can I somehow encapsulate part of my code to be run not impersonated?
Replacing the code so, that in the code I define the impersonate and change in the web.config setting to "false" will is a bit harder work :(
Mar 11, 2012 02:06 PM|LINK
You can write code to impersonate for specific actions (which is a better way to do impersonation):
public void DoWorkWithClientCreds()
// grab client identity
WindowsIdentity id =
// impersonation is automatically undone by
using (WindowsImpersonationContext wic = id.Impersonate())
// access resource using client credentials
using (TextReader tr = File.OpenText("foo.txt"))
Mar 13, 2012 08:47 PM|LINK
So far it has been easier for me to use the global impersonate all around my application. So I tried to disable the impersonate like the following shows "http://msdn.microsoft.com/en-us/library/ff647404.aspx
// Stop impersonation
WindowsImpersonationContext ctx = WindowsIdentity.Impersonate(IntPtr.Zero);
// Thread is now running under the process identity.
// Any resource access here uses the process identity.
// Resume impersonation
But by some reason I couldn't make it work.
Mar 14, 2012 03:52 AM|LINK
I agree to Allen's suggestion that you can switch the impersonation of your web application to programmtic way so that you can only execute code with impersonated user context when it is necessary.
Another possible means is to call the "RevertToSelf" windows API function(use .NET PInvoke interop). This function will help stop the impersation in the current thread(and make the thread execute under the original security identity inherited from parent process).
the followigng KB article includes the usage of "RevertToSelf" API:
#How to implement impersonation in an ASP.NET application
Mar 19, 2012 06:24 AM|LINK
Have you tried manually call the "RevertToSelf" API(with Pinvoke) to see if it works?