9/29/18

Enable a SharePoint REST API Post with RequestDigest Token

 SharePoint provides a very detailed set of RESTful API which allows us to interact with SharePoint data lists. When sending GET API calls, there is no need for additional security validation. When sending a PATCH (update) or POST (create), SharePoint requires that the request headers have an additional header with an authorization token. In this article, we take a look at getting this authorization token, and sending a request using an Angular application.

How to Get the Token

Before sending a POST requests via the APIs, we need to first get a fresh (valid) token.  Lucky for us, the SharePoint APIs also provide an end-point which can be used to get it.  Let’s take a look at the code below to see how this is done:

Note: This snippet runs under the SharePoint site context. The API URL is relative to the site location. For example if your site URL is https://mysp.com/sites/mysite, the API URL should be https://mysp.com/sites/mysite/_api/


function token() {
                     
    var url = "../_api/contextinfo";

    $http({
        method: 'POST',
        url: url,
        headers: {
            'Content-Type': 'application/json;odata=verbose',
            'Accept': 'application/json;odata=verbose'
        }
    }).then(function success(resp) {
        var data = resp.data.d.GetContextWebInformation;               
        authToken = {};
        authToken.name = 'X-RequestDigest';
        authToken.value = data['FormDigestValue'];
               
    }, function error(resp) {
        console.log(resp);
    });           
           
}


In this function, we use the API _api/contextinfo which returns a base64 encoded string.  The token also has an expiration of usually about ten minutes which depends on the SharePoint configuration.  Once the promise is resolved, we capture the X-RequestDigest JSON value, and we set it to a variable which can enable us to use it when making other API calls.

The JSON from the API call should look like this:


{
    "d": {
        "GetContextWebInformation": {
            "__metadata": {
                "type": "SP.ContextWebInformation"
            },
            "FormDigestTimeoutSeconds": 1800,
            "FormDigestValue": "",          
            "SiteFullUrl": "",           
            "WebFullUrl": ""
        }
    }
}


Once the authorization/digest token is available, we can send a POST API call with the token value in the request header. This is done in the following code snippet:


function addItem(item) {

    var data = {
        "__metadata": {
            "type": "SP.Data.TodoItemsListItem"
        },
        "Title": item.title,
        "OData__Comments": item.comments
    }

    var request = $http({
        method: 'POST',
        url: url,
        headers: {
            'Content-Type': 'application/json;odata=verbose',
            'Accept': 'application/json;odata=verbose',
            'X-RequestDigest': authToken.value
        },
        data: JSON.stringify(data)
    });

    return request;
}


When creating or updating information on the data lists, we need to send the item values as well as the metadata information for the list. Without the metadata, the request will fail.   We can identify the metadata information by first sending a GET request. The returning payload provides the data with the corresponding metadata.

In the rest of the code, we set the title and comments properties of the JSON payload. We then use the HTTP service to send a POST request with the header information. We should notice that there is an X-RequestDigest header entry which matches the name that we received when we initially get the token in the previous snippet. In this header, we can then set the security token value and send the request.

By adding the digest token to the header, the PATCH and POST API calls should be successful. We do need to remember that these tokens have an expiration window, so we should check for this and refresh the token when it is about to expire.

I hope this is able to help you resolve the authorization token requirements when creating and updating a SharePoint data list.

You can get a sample project here:  https://github.com/ozkary/sp-addin-todo


Originally published by ozkary.com

0 comments :

Post a Comment

What do you think?