David Kitchen

Avatar

Just another SharePoint developer blogging

Impersonating a user in C#

A random tech post, I just know I’m going to need this again sometime and this is my web notepad.

This is some code, to impersonate another user using calls to unmanaged code, and then to loop some Sharepoint lists as the impersonated user and then go back to the user of the process.

using System;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Text;

using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;

namespace ConsoleApplication1
{
  class Class1
  {
    [STAThread]
    static void Main(string[] args)
    {
      Console.WriteLine(WindowsIdentity.GetCurrent().Name);

      string siteUrl = "http://ukserver/sites/projectserver_101/";

      string user = "username";
      string userDomain = "domain";
      string password = "pass@word1";

      bool impersonate = true;
      IntPtr userHandle = new IntPtr(0);
      WindowsImpersonationContext impersonatedUser = null;

      if (impersonate)
      {
        bool returnValue = LogonUser(
          user,
          userDomain,
          password,
          LOGON32_LOGON_INTERACTIVE,
          LOGON32_PROVIDER_DEFAULT,
          ref userHandle
          );

        if (!returnValue)
        {
          throw new Exception("Invalid Username");
        }
        WindowsIdentity newId = new WindowsIdentity(userHandle);
        impersonatedUser = newId.Impersonate();
        Console.WriteLine(WindowsIdentity.GetCurrent().Name);
      }

      StringBuilder viewField = new StringBuilder();

      SPSite siteCollection = new SPSite(siteUrl);

      SPWeb spWeb = siteCollection.OpenWeb();

      foreach (SPList currentList in spWeb.Lists)
      {

        if (!currentList.BaseType.Equals(SPBaseType.DocumentLibrary))
        {
          viewField.AppendFormat(
            "<list Name='{0}' Type='{1}' />",
            SPEncode.HtmlEncode(currentList.Title),
            SPEncode.HtmlEncode(currentList.GetType().ToString())
            );
        }
      }
      Console.WriteLine(viewField.ToString());

      if (impersonate)
      {
        //
        // Clean up the impersonated user, returning to our process owner.
        //
        impersonatedUser.Undo();
        CloseHandle(userHandle);
      }

      Console.WriteLine(WindowsIdentity.GetCurrent().Name);
    }

    //
    // This stuff required for impersonation
    //
    public const int LOGON32_LOGON_INTERACTIVE = 2;
    public const int LOGON32_LOGON_SERVICE = 3;
    public const int LOGON32_PROVIDER_DEFAULT = 0;

    [DllImport("advapi32.dll", CharSet=CharSet.Auto)]
    public static extern bool LogonUser(
      String lpszUserName,
      String lpszDomain,
      String lpszPassword,
      int dwLogonType,
      int dwLogonProvider,
      ref IntPtr phToken
    );

    [DllImport("kernel32.dll", CharSet=CharSet.Auto)]
    public extern static bool CloseHandle(IntPtr handle);

  }
}

You can use that impersonation stuff anywhere… just take out the Sharepoint stuff :)

4 Comments, Comment or Ping

  1. Leon

    Thanks, this helps me a lot!

  2. Pulkit

    This is great. But i dont wanna inport any external dll like “advapi32.dll” or “kernel32.dll”. So can you provide me some code for impersonating a user without use of these dlls

  3. ShWaYzE

    You have to use com interop because .Net doesn’t have fully managed code to impersonate a user. Don’t be a wimp…

  4. Loosu

    Thanks a lot. Your post was very helpful. :)

Reply to “Impersonating a user in C#”