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 ![]()
Recent Comments