JQuery Plugin to obtain FormDigest code in SharePoint 2013

Category: #SharePointDevSharePoint 2013 Comments: One comment

In SharePoint 2013 Microsoft has put back the FormDigest security during the execution of the code. That means that if you are in a standard application page or web part you will not have any problem to create your web sites, update items etc… You can take a look over here for the details.

But if you want to do something more, like for example create your own service (in my case with Service Stack) you will always get a COM Exception from your page “System.Exception: Microsoft.SharePoint.SPException: The security validation for this page is invalid. Click Back in your Web”

The problem is that the header X-RequestDigest header is not passed automatically in your request, meaning that – even if you put AllowUnsafeUpdate to true – the operation will generate an exception.

This is the reason with my colleague Leon we have decided to create a plugin to help developers to execute such operation, especially from JavaScript.

In SharePoint 2013 you can obtain all the information of your current context calling with POST method the URL /_api/contextinfo. The response will be an XML file with all the info necessary. Adding in your request the header as below you can obtain a JSON object as return value.

headers: { "Accept": "application/json; odata=verbose" }

The plugin you can download here will provide you these info and you will be able to obtain the FormDigest code and pass to your services

Here how to use it:

$(document).ready(function () {
$(document).SPContextInfo({ spUrl: "http://mysharepointurl" }, SPCallBack);
});
function SPCallBack(SPWebInfo)
{
 $('#mybutton').click(function () {
$.ajax({
type: "POST",
url: "/servicestack_api/myservice",
headers: { "X-RequestDigest": SPWebInfo.FormDigestValue },
success: function (data) {
     alert('yeah');
 },
error: function (data) {
     alert('ko');
 }
 });
 });
}

One comment to JQuery Plugin to obtain FormDigest code in SharePoint 2013

  • sbro  says:

    Very useful. Thanks!

Leave a reply

*


* 7 = forty two

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>