JordanBlackler
asked on
Reason why this Impersonator code doesn't work?
Hi All -
I'm using C#
I got this code over a year ago from here. It worked then, but when i added it into my new project it doesn't work. The code doesn't error out, i just get "access denied" when i try to update the list.
Thanks
I'm using C#
I got this code over a year ago from here. It worked then, but when i added it into my new project it doesn't work. The code doesn't error out, i just get "access denied" when i try to update the list.
Thanks
public class Impersonator
{
public static WindowsIdentity CreateIdentity(string User, string Domain, string Password)
{
// The Windows NT user token.
IntPtr tokenHandle = new IntPtr(0);
const int LOGON32_PROVIDER_DEFAULT = 0;
const int LOGON32_LOGON_NETWORK = 3;
tokenHandle = IntPtr.Zero;
// Call LogonUser to obtain a handle to an access token.
bool returnValue = LogonUser(User, Domain, Password,
LOGON32_LOGON_NETWORK, LOGON32_PROVIDER_DEFAULT,
ref tokenHandle);
if (false == returnValue)
{
int ret = Marshal.GetLastWin32Error();
throw new Exception("LogonUser failed with error code: " + ret);
}
//System.Diagnostics.Debug.WriteLine("Created user token: " + tokenHandle);
//The WindowsIdentity class makes a new copy of the token.
//It also handles calling CloseHandle for the copy.
WindowsIdentity id = new WindowsIdentity(tokenHandle);
CloseHandle(tokenHandle);
return id;
}
[DllImport("advapi32.dll", SetLastError=true)]
private static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword,
int dwLogonType, int dwLogonProvider, ref IntPtr phToken);
[DllImport("kernel32.dll", CharSet=CharSet.Auto)]
private extern static bool CloseHandle(IntPtr handle);
}
}
protected void btnSaveExit_Click(object sender, EventArgs e)
{
WindowsImpersonationContext wic = Impersonator.CreateIdentity("Admin User Name", "Domain where Admin resids", "Password").Impersonate();
SPSite site = SPControl.GetContextSite(Context);
//site.CatchAccessDeniedException = false;
SPWeb subSite = site.AllWebs["mysite"];
subSite.AllowUnsafeUpdates = true;
SPListCollection allSiteLists = subSite.Lists;
SPList list = subSite.Lists["mylist"];
SPListItemCollection listItems = list.Items;
SPListItem newItem = list.GetItemById(Convert.ToInt32(lblUnique.Text));
wic.Undo();
////
newItem["ApprovedBy"] = txtApprovedBy.Text;
newItem["ApprovedDate"] = txtApprovedDate.Text;
////
newItem.Update();
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
I did what your suggested and i also changed the way i got the site and list. Now it works.
ASKER