Friday, 12 April 2013

Use AppPool (Application Pool) credentials for Sharepoint integration

I had some fun today trying to work out how to use the AppPool Credentials for integration between our website and SharePoint.

So this is what I did.

using System.Security.Principal;

public class ImpersonateUser : IDisposable
{
  WindowsImpersonationContext ctx = null;
  WindowsImpersonationContext appPoolctx = null;

  public void ImpersonateAppPoolUser()
  {
     //RevertToSelf
     ctx = WindowsIdentity.Impersonate(IntPtr.Zero);
     // and call impersonate on the app pool user object
     appPoolctx = WindowsIdentity.GetCurrent().Impersonate();
  }

  public void UndoUserImpersonation()
  {
     if (ctx != null)
     {
        ctx.Undo();
        ctx = null;
     }

     if (appPoolctx != null)
     {
        appPoolctx.Undo();
        appPoolctx = null;
     }

  }

  public void Dispose()
  {
      UndoUserImpersonation();
  }
}

I used this class for SharePoint integration, as it seemed a quicker and simpler option than storing credential in the web.config and then encrypting.

using (ImpersonateUser ie = new ImpersonateUser())
{
    ie.ImpersonateAppPoolUser();

    using (ClientContext clientContext = new ClientContext(url))
    {
     //Get documents from SharePoint
    }
}

No comments:

Post a Comment