Creating Sites/Lists/List Items under Current User Context in SharePoint By Using SPUserToken



Creating Sites/Lists/List Items under Current User Context in SharePoint By Using SPUserToken



We might have come across the situation where we need to perform a certain action on a particular user context in MOSS 2007.

Usually we do this by performing the action under RunWithElevatedPrivileges method and updating the listitem using SPListItem.SystemUpdate() method (see here). but this approach has its own flaws like (RunWithElevatedPrivileges will run under system account, we cannot use SystemUpdate for SPSite,SPWeb,SPList, since it runs under system we will "CreatedBy" by as SystemAccount).

by using SPUserToken we can achive this without RunWithElevatedPrivileges method. All we need to do is create SPSite by passing SPUserToken of a particular user.

In below example i'm creating SPUserToken object by calling GetUserToken method.

Example:

string siteUrl = "Ur Site Url Goes Here";
string username = "YourUsername";
SPUserToken spusertoken = GetUserToken(siteUrl, username);
SPSite spsite = new SPSite(siteUrl, spusertoken);
SPWeb spweb = spsite.OpenWeb().Webs["WebName"];
SPList list = spweb.Lists["MyList"];
SPListItem item = list.Items.Add();
item["Title"] = "TestTitle";
item.Update();
spsite.OpenWeb().Dispose();
spweb.Dispose();
spsite.Dispose();

private static SPUserToken GetUserToken(string siteUrl, string userName)
{
SPUserToken userToken = null;
using (SPSite site = new SPSite(siteUrl))
{
foreach (SPUser user in site.RootWeb.AllUsers)
{
string siteUserName = user.LoginName;
if (user.LoginName.IndexOf(':') != -1)
{
string[] DomainAndUser = user.LoginName.Split(new char[] { ':' });
siteUserName = DomainAndUser[1];
}
else if (user.LoginName.IndexOf('\\') != -1)
{
string[] DomainAndUser = user.LoginName.Split(new char[] { '\\' });
siteUserName = DomainAndUser[1];
}
if (siteUserName == userName)
{
userToken = user.UserToken;
Console.WriteLine("User token found");
break;
}
}
}
return userToken;
}