Meet the SharePoint FormDigest

By | 2014-01-24

Even as we move “forward” as SharePoint Community with SharePoint Apps, there is also still great value in Farm Solutions and the development we can do there.

One of the scenario’s we all implement is probably something like this:

Client application (browser) -> POST JSON data -> Custom WCF REST Service 
located in /_layouts/
-> Do something withSPList/SPListItem/SPWeb etc.

If so, did you receive the “The security validation for this page is invalid” error when you called the Update() on your object?

And did you start adding code like:

  • SPSecurity.RunWithElevatedPrivileges (MSDN)
  • SPWeb.AllowUnsafeUpdates = true;(MSDN)

Well..

There is a much better and nicer solution.

Step 1

Add the following (if it is not already present in your (application) Page header where you want to call your Web Service from:

<Register Tagprefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c">

Step 2

Next we are going to add a WebControl, I add this to my¬†ContentPlaceHolderID=”PlaceHolderMain”:

<SharePoint:FormDigest runat="server" />

Step 3

As of now we have a hidden field in the html were SharePoint can store the FormDigest token. We then need to send this token with our ajax call to our Web Service:

// we find the FormDigest hidden form field value like so:
var formDigest = jQuery("[name='__REQUESTDIGEST']").val();

// call the webservice WITH the formDigest in the header of the post request like so:
jQuery.ajax(myServiceUrl, {
    type: "POST",
    headers: { "X-RequestDigest": formDigest },
    contentType: "application/json",
    dataType: "json",
    data: JSON.stringify(dummyData)
});

Step 4

And now we can check the FormDigest inside our WebService logic:

// Validate the form digest for POST security
if (SPUtility.ValidateFormDigest())
{
    // ... some code that fetches a list item and modifies it

    // Update list item
    item.Update();
}

Wrap-up or “uitsmijter”

I want to close with the reason to do this: to check if the call to our service is legit and not made through some XSS attack! If you do not do this properly SharePoint will throw the Exception “The security validation for this page is invalid.”

thanks for the info

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.