SharePoint – Refresh Form Digest Value using AngularJS and REST

Background

When working with SharePoint 2013/online, REST, CRUD and SPA you will need the Form Digest token. This a unique key based on user and and site and it’s only valid for a limited time.
Wictor Wilén wrote a very good post about it here

Problem

We have an App that is not using a master-page which means that the Form Digest value won’t update nor exist as a hidden input element. This means that we can not retrieve it using $(‘#__REQUESTDIGEST’).val(). Also, I have not been able to update the Digest value using UpdateFormDigest(relativeUrl,interval) from init.js.

Solution

Now, let’s build a service in AngularJS that will handle the Form Digest value for us and automatically update it with the same refresh rate as it would in the master-page. If you check the js-variable  _spFormDigestRefreshInterval on a page based on a master-page, you will find the value 1440000 (ms), which means that the Form Digest key will update every 24 minutes.

Here’s how I created the refresh service. There are two services, one which will retrieve the Form Digest value and one that will set the retrieve interval.

This will work great, but how can we use this in our http request?

We can config the application to intercept all http requests and add the Form Digest value to the http header. And the $rootScope.formRequestDigest will be updated every 24 minutes.

Define your controller and start the Form Digest Interval Service. Pass the $rootScope to the service. By using the $rootScope we can access global properties in other modules.

 

About Tobias Eriksson