I'm trying to get this result: i want me to impersonate an user X, write down a file in a List (in which X has contribute rights), and change the privileges so that noone else can modify that..
So i decide..
1. Elevate Privilage
2. Open SC as User (by Token)
3. Add item
4. Add User as Contributor
5. Remove the group of User from the Contribution
Is there something wrong?
Here's my code:
string fullsite = SPContext.Current.Web.Url + "/sites/ReplyCorp";
SPUserToken myToken = TokenManager.GetToken(addContentObj.userId);
Microsoft.SharePoint.SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite scSite = new SPSite(fullsite, myToken))
{
using (SPWeb scWebAllReplyers = scSite.OpenWeb("AllReplyers"))
{
scWebAllReplyers.AllowUnsafeUpdates = true;
scWeb.AllowUnsafeUpdates = true;
SPList listContenuti = scWebAllReplyers.Lists["Contenuti"];
SPListItem nuovoElemento = listContenuti.AddItem();
nuovoElemento["Title"] = addContentObj.contentTitle;
nuovoElemento.Update();
var allreplyers = scWebAllReplyers.Groups["AllReplyers"];
AssignPermissionsToItem(nuovoElemento, (SPPrincipal)scWebAllReplyers.AllUsers[addContentObj.userId], SPRoleType.Contributor);
AssignPermissionsToItem(nuovoElemento, (SPPrincipal)allreplyers, SPRoleType.Readern);
}
}
}
}
public static void AssignPermissionsToItem(SPListItem item, SPPrincipal obj, SPRoleType roleType)
{
if (!item.HasUniqueRoleAssignments)
{
item.BreakRoleInheritance(false, true);
item.Update();
}
SPRoleAssignment roleAssignment = new SPRoleAssignment(obj);
SPRoleDefinition roleDefinition = item.Web.RoleDefinitions.GetByType(roleType);
roleAssignment.RoleDefinitionBindings.Add(roleDefinition);
item.RoleAssignments.Add(roleAssignment);
}
The problem I get is "Unauthorized User", even if my user is Admin and the other user is contributor and owner of the file (running withelevated Privileges!)
Thank you very much!