RunWithElevatedPrivileges() and Error “The security validation for this page is invalid …”

I’m posting this mostly for my own reference as the riddle has been solved already–see the External References section for details.

What I’m talking writing about is this: in your SharePoint component you call SPSecurity.RunWithElevatedPrivileges() and when trying to change anything SharePoint related you get this error message:

Microsoft.SharePoint.SPException: The security validation for this page is invalid. Click Back in your Web browser, refresh the page, and try your operation again. ---> System.Runtime.InteropServices.COMException (0x8102006D): The security validation for this page is invalid. Click Back in your Web browser, refresh the page, and try your operation again.

You get his error message because you had to create SPSite and SPWeb objects for use in your elevated code and this in turn caused a new SPContext object to be created with an unvalidated Form Digest. To remedy this simply call SPUtility.ValidateFormDigest() before using SPSecurity.RunWithElevatedPrivileges().

Additional take aways:

  • Setting the SPWeb’s AllowUnsafeUpdates property to true is only a crutch. Prefer SPUtility.ValidateFormDigest()–especially as the AllowUnsafeUpdates property will be reset on various occasions.
  • Never ever ever switch form validation off as it makes you vulnerable to attacks. This applies to using Central Administration as well as setting SPWebApplication.FormDigestSettings.Enabled to false.

External References

Advertisements
This entry was posted in Uncategorized and tagged . Bookmark the permalink.

One Response to RunWithElevatedPrivileges() and Error “The security validation for this page is invalid …”

  1. Thank you for this. Had exactly the same scenario and your solution helped.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s