Monday, February 8, 2016

Using javascript and REST API to create a sub-site cross site collection

The most important thing is to impersonate the current logged user to create a sub-site in another site collection. And that is also a limitation of REST API when execute the code outside the context. In this article, I create a sample code to create a sub-site in another site collection with the same context and using currently digest to authenticate.

Step 1: get context info

If you are using JSOM, you don't need to get this digest because JSOM is already authenticated to the site and just execute the code in the current context. Only if execute the code outside the context and perform cross-domain or outside SharePoint context, this step is required.

$.ajax({
url: me.rootUrl + "/_api/contextinfo",
method: "POST",
headers: {
 "Accept": "application/json; odata=verbose"
},
success: function(data) {
 __REQUESTDIGEST = data.d.GetContextWebInformation.FormDigestValue;
                        },
                        error: function(e) {
                        }
               });

Step 2: create a sub-site

$.ajax({
 url: rootUrl + "/_api/web/webinfos/add",
 type: "POST",
 headers: {
"Authorization" : "BEARER " + __REQUESTDIGEST,
"Accept": "application/json;odata=verbose",
"Content-Type": "application/json;odata=verbose",
"X-RequestDigest": __REQUESTDIGEST
 },
 data: JSON.stringify({
'parameters': {
 '__metadata': {
'type': 'SP.WebInfoCreationInformation'
 },
 'Url': "YOUR_URL",
 'Title': "YOUR_TITLE",
 'Description': "YOUR_DESCRIPTION",
 'Language': 1033,
 'WebTemplate': "YOUR_SITETEMPLATE",
 'UseUniquePermissions': true|fale
}
 }),
 success: function(data) {

 },
error: function(data, errorCode, errorMessage) {

}
});

With JavaScript, you must define the key "Authorization" : "BEARER " + __REQUESTDIGEST to authenticate the validation logged. If you work with SharePoint Designer, it should be "Authorization" : "BEARER ". You will get the error "invalid format of Authorization" if you  add the digest after Bearer. To avoid the error in SharePoint Designer, you could define the key Authorization with empty string or leave it with Bearer, not add the digest.

Good luck!

No comments: