Friday, September 30, 2011

Explanation - Microsoft.SharePoint.SPException: The security validation for this page is invalid.

 

SharePoint applies a security check whenever you change data through the Server Object Model during HTTP requests. In fact, by default, SharePoint web forms use a form digest control to enforce security. The form digest is a hidden field POSTed by SharePoint webforms and checked by the security infrastructure on the server. When you make changes to objects by using the Server Object Model during an HTTP GET request, this input field will be missing, so by default SharePoint will throw an exception that looks like this excerpt:


Microsoft.SharePoint.SPException: The security validation for this page is invalid.


Similarly, if you send an HTTP POST request with a missing or invalid form digest value, you will receive the same error. This behavior applies only during HTTP requests. Therefore, when you reference the Server Object Model in a class library or a batch tool that runs outside of the ASP.NET pipeline, the security check will not occur. In fact, the check process looks for the
HttpContext.Current variable; if it is null the digest validation will not occur.


With that in mind, if you are developing a webpage that will respond to HTTP GET requests, or a custom web form page that doesn’t inherit from the WebPartPage type and doesn’t use the Form Digest control, you will need to instruct SharePoint to skip the digest validation;otherwise, your code will not work.


To instruct SharePoint to skip the validation, set the Boolean AllowUnsafeUpdates property of the current SPSite or SPWeb to true.

Conversely, when you develop a custom ASPX page, and you want to exploit the security environment provided by SharePoint, you have a couple of choices: you can inherit from WebPartPage, or manually include a FormDigest control in your page.

In the first case you simply need to inherit from the Microsoft.SharePoint.WebPartPages.WebPartPage base class, which internally renders a FormDigest control. Then, in your code, you call the utility method SPUtility.ValidateFormDigest() to check the digest when you POST the page back to the server.

In the latter case you need to include the Microsoft.SharePoint.WebControls.FormDigest control in your page(s), and you still need to invoke the SPUtility.ValidateFormDigest() method to check the digest.