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;
 WindowsIdentity id = new WindowsIdentity(upn);
 WindowsImpersonationContext wic = id.Impersonate();    
   // Do what you need here under the impersonation context.
   var currentId = WindowsIdentity.GetCurrent().Name; 


Tweety P said...

Your content is awesome . You have done a great job and its very useful for me . I appreciate your effort and I hope that you will get more positive comments from the web users.
SMO Services Chennai

Giri Mani 2 said...

Got a creative information. Understand well in this. This gives the easy technique of experiment. New technologies are developed more. so techniques are also improved. Thank you for this information.
Digital Marketing Company in Chennai

Xplorant Seo said...

Wonderful blog.. Thanks for sharing informative blog.. its very useful to me..

iOS Training in Chennai