Tags

,

Every time I executed the code, some error came up. Most of the time, it was either “Access Denied” or “The security validation for this page is invalid”.

I ran the code using RunWithElevatedPrivileges, but that didn’t help much. Neither did the SPWeb.AllowUnsafeUpdates property.
Now the below code to rescue me:

SPSite.WebApplication.FormDigestSettings.Enabled = false

But you will have to use it in RunWithElevatedPrivileges scope:

public void EditSecurity()

{

    SPSecurity.RunWithElevatedPrivileges(delegate()

    {

        using (SPSite site = new SPSite(url))

        {

            using (SPWeb web = site.OpenWeb())

            {

                SPWebApplication webApp = web.Site.WebApplication;

                webApp.FormDigestSettings.Enabled = false;

                web.AllowUnsafeUpdates = true;

 

                SPGroup group = web.SiteGroups["groupname"];

                SPRoleAssignment roleAssignment = new SPRoleAssignment((SPPrincipal)group);

 

                SPRoleDefinition roleDefinition;

                roleDefinition = web.RoleDefinitions.GetByType(SPRoleType.Contributor); // Gets a predefined role definition

                roleDefinition = web.RoleDefinitions["customRole"]; // Gets a custom defined role definition

 

                roleAssignment.RoleDefinitionBindings.Add(roleDefinition);

 

                web.RoleAssignments.Add(roleAssignment);

 

                web.Update();

                web.AllowUnsafeUpdates = false;

                webApp.FormDigestSettings.Enabled = true;

            }

        }

    });

}
Advertisements