During our execution of one of our engagements ,we've faced a problem of this error getting displayed “The security validation for this page is invalid”

what we were trying to do is to grant permissions in code running in elevated privilege for users dynamically using the following code:

SPSite siteColl = SPContext.Current.Site;

     SPWeb site = SPContext.Current.Web;

     //run with app pool identity

     SPSecurity.RunWithElevatedPrivileges(delegate()

{

using (SPSite ElevatedsiteColl = new SPSite(siteColl.ID))

      {

       using (SPWeb wb = ElevatedsiteColl.OpenWeb(site.ID))

        {

         try

         {

      code to assign permissions dynamically than runs in AppPool Identity…….

Issue were fixed by setting the following property to false,

SPWebApplication.FormDigestSettings.enabled

and SPSite.AllowUnsafeUpdates ,SPWeb.AllowUnsafeUpdates to true

 

 

by adding the following lines in our try block:

//To Fix security validation error

ElevatedsiteColl.WebApplication.FormDigestSettings.Enabled = false;

ElevatedsiteColl.AllowUnsafeUpdates = true;

wb.AllowUnsafeUpdates = true;

and in our finally block we reset the values to its initial state

}

finally

{

  ElevatedsiteColl.WebApplication.FormDigestSettings.Enabled = true;

  wb.AllowUnsafeUpdates = false;

  ElevatedsiteColl.AllowUnsafeUpdates = false;

}

there is another approach by disabling the security validation for the entire web using central administration which I think will cause additional risk for security in the whole web application to fix issue related to one piece of code!

image