Scott Hanselman

DPAPI and WindowsImpersonationContext and the one that got away...

July 30, 2003 Comment on this post [3] Posted in Web Services | ASP.NET | XML
Sponsored By

I’ve got a small C# Security Application that I’m writing an Editor for.  I was hoping to let the user run the application as whoever they choose to, and then use LogonUser to create a WindowsImpersonationContext and log them in as SOMEONE ELSE to do the DPAPI Encryption (because it will be that other use that will be decrypting the data.)

 

I’m using DPAPI with a User Store, not a Machine Store.  I’ve got a managed wrapper for DPAPI that works fine.  I’ve got a Managed “ImpersonateUser” function that returns a WindowsImpersonationContext and internally users LogonUser and also works fine.  

 

The psuedocode/gist is be basically:

 

Load App

            Do some stuff

            Load XML File

            Call ImpersonateUser (someotherguy) [succeeds and WindowsIdentity.GetCurrent().Name changes to reflect the change

            Call DPAPI to Encrypt Element Context (this works fine if I DON’T IMPERSONATE...)

                        ERROR: Win32 Marshal.GetLastWin32Error() reports “The System couldn’t find the file specified”

            Save File

            Call ImpersonationContext.Undo

Exit App

 

Apparently this is either utterly stupid of me, or noone has ever tried it.   All the doc on DPAPI is either highly theoretical “how it works internally” or very trivial “here’s how I used the Machine Store from ASP.NET  The doc on WindowsImpersonationContext is even worse.

 

Am I going to just make the user to a “RunAs” to launch my app? (which works fine, BTW)  It just would have been so nice to have a "Run As" menu item...thoughts anyone?

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.

facebook twitter subscribe
About   Newsletter
Hosting By
Hosted in an Azure App Service
July 30, 2003 7:50
Might not ideal for you, but we ended up using UserStore/DAPI via a Windows Service, and then just set up the login user for that.
July 30, 2003 18:45
July 30, 2003 19:04
Did you load the user's profile? As I recall (it's been a little while, alas), you need to either LogonUser(Ex) with interactive (which loads the profile implicitly) or call LoadUserProfile to make sure it's loaded or, you'll have some issues, since the store that DPAPI's looking for won't be available.

Comments are closed.

Disclaimer: The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.