Tuesday, 22 September 2015

Impersonation of Web Users in ASP.NET/SharePoint 2013 without a password

There seemed to be a lack of samples available to demonstrate how Windows impersonation can be done within the context of a web application (such as SharePoint 2013 or ASP.NET). Most of the examples use the "LogonUser" Windows API call to get a user token. e.g. https://msdn.microsoft.com/en-us/library/chf6fbt4.aspx. However - that call requires a password to work. You don't really want all your user passwords to have to sit in a secure store to enable impersonation!

In my scenario, I had to write to a file through an existing COM Component via a .NET COM Interop library. It depended on the write operation being done from the context of a valid user - otherwise the file wouldn't be stamped correctly with author metadata.

To do this, I had to use an overload of the WindowsIdentity constructor which accepts a UPN (User Principal Name). From there, you can impersonate users within your code at will.

NOTE: the account that is doing the impersonation (e.g. svcSP) will need to have the "Act as Part of the Operating System" right as defined in your Local User Policy for this to work.

Code Sample:


void Main()
{
 var userName = "LOCALDEV\\david.klein";
 PrincipalContext ctx = new PrincipalContext(ContextType.Domain);

 var user = UserPrincipal.FindByIdentity(ctx, userName);

 if (user != null)
 {
 var upn = user.UserPrincipalName;
 Debug.Print(upn); 
 WindowsIdentity id = new WindowsIdentity(upn);
 WindowsImpersonationContext wic = id.Impersonate();    
 try
  {
   // Do what you need here under the impersonation context.
   var currentId = WindowsIdentity.GetCurrent().Name; 
   Debug.Print(currentId);
  }
  finally
  {
   wic.Undo();
  }
 }
}