There are often occasions when you would like to run a service or an application in the context of another account (farm administrator, site collection primary administrator etc.) on SharePoint. When you don’t have SharePoint object model at your disposal for using ElevatedPriveleges; impersonating a user account is still achieveable using WindowsIdentity and WindowsImpersonationContext references from System.Security.Principal class library.
Recently, I have taken a fancy to this handy utility that allow me to run a console application on SharePoint 2010 production server where as a developer my user account did not have enough permissions to tinker about with SharePoint sites let alone run anything against it.
Add the following references to your class
Imports System.Security.Principal Imports System.Security.Permissions Imports System.Runtime.InteropServices
The following is the method you can use
Module Module1 Sub Main() Dim tokenHandle As IntPtr = IntPtr.Zero Dim returnValue As Boolean = LogonUser("<USERNAME>", "<DOMAIN>", "<PASSWORD>", 2, 0, tokenHandle) Dim newId As New WindowsIdentity(tokenHandle) Using impersonateUser As WindowsImpersonationContext = newId.Impersonate RunUtility() End Using End Sub <DllImport("advapi32.dll", SetLastError:=True, CharSet:=CharSet.Unicode)> _ Public Function LogonUser(ByVal lpszUsername As [String], ByVal lpszDomain As [String], ByVal lpszPassword As [String], ByVal dwLogonType As Integer, ByVal dwLogonProvider As Integer, ByRef phToken As IntPtr) As Boolean End Function Private Sub RunUtility() ' add your business requirements here End Sub End Module
Fun isn’t it? Imperonating user accounts and run code in the context of a different user account. I have categorised this as a SharePoint 2010 post but this should work just as same on SharePoint 2007 envrionment as well.