About lavssun

View all posts by lavssun

SharePoint 2013 OAuth Tokens–Frequently asked questions

In one of my previous blog post I wrote about SharePoint 2013 App authentication flow, which briefed about oAuth protocol. There is lot of things to be learnt with respect to oAuth. I feel it’s worth compiling an FAQ  on oAuth, this is the result of that :

1. What is a Context Token ?

The context token is specific to App Configuration information and it is issued by Windows Azure Access Control Services (ACS). The trusted ACS server signs and issues the Context Token, when it receives request from App.

2. What is the format of CacheKey of Context Token ?

The CacheKey of context token is a combination of UserNameId, UserNameIdIssuer, ApplicationId and Realm.

CacheKey= UserNameId + “,” + UserNameIdIssuer + ApplicationId + “,” + Realm.

Note: The Cache Key does not have site URL details. The Cache Key relies on the uniqueness of the realm, it is unique for user, app and tenant.

3. How a Context Token look like ?

The same context token is illustrated below:


4. What are the various information present in the Context Token ?



Represented Fields

Sample Value


‘add’ means audience. The format of add is below

{target client ID}/ {target URL authority} @ {target realm}



iss iss stands for issuer. It represents the principal that has created the Token. The format is {ACS}@{target realm} ACS


realm Tenancy realm


nbf ‘nbf’ stands for not before. It represents the validity start of the token nbf


exp ‘exp’ stands for expiration. It represents the time after which the token is not valid. exp


Actor It is the principal identity of SharePoint 2013 SharePoint 2013


5. How to calculate the validity and expiry timestamp from nbf and exp ?

Nbf and Exp are denoted based on JWT specification. It is calculated as number of elapsed seconds since 1’st January, 1970.

6. How long a refresh token is valid ?

The refresh token is valid for 6 months (as of today’s App Authentication Framework design).

7. Can we store the access token in cookies ?

It is recommended not to store the access token in cookies (it’s not very secure). The refresh token can be stored in cookies (which is valid for 6 months), a new Access Token can be requested based on the stored refresh token.

8. Can we grant or deny the permissions for launching an App ?

No. If the user has access to browse the site, he’ll automatically be able to launch the app. The Grant or Deny permissions for an app can be defined only during the install time.

9. Can we use HttpDav protocol (HttpDav APIs) inside the App ?

The HTTP Dav protocol does not work with oAuth.

10. Whether AppId and SecretId will be same across all tenants for a given app ?

The AppId and SecretId are constant across all tenants for a given app, if the app is running in a separate remote web application and app is registered in the Seller dashboard.


 Subscribe to my blog

How to Add external users to SharePoint Online

I was wondering if there is a way to add external users to SharePoint Online. The external users are nothing but people who don’t have user accounts in the SharePoint Online environment. The access to external users can be provided by sending them an invitation through e-mail. I’ve learnt that we can send the e-mail invitation to any type of e-mail address such as *.gmail.com, *.yahoo.com or *.yourowndomain.com. However to log-in to the SharePoint online environment, the e-mail account has to be associated with a valid Microsoft account.


Click Share


Now the a email invite will be sent to the invitees (external users)

Open the e-mail invite and click the link on that.


To accept the invite, you need to have a valid Microsoft account.


This completes the sign-in process for the external user to the SharePoint Online Team site using a valid Microsoft account.

 Subscribe to my blog

Virtual Tech Conference by South Asia MVPs–August 01, 2013

Virtual Tech Conference (VTC) is a South Asia MVP community initiative to bring you up-to the speed on latest Microsoft technologies. This event is being hosted by South Asia MVP team and they have a very interesting line-up of speakers and topics in this event. This includes two parallel tracks – developer and IT Pro.

In the IT Pro track, I am speaking on ‘SharePoint 2013 App Model – SharePoint Hosted Apps’. My session starts at 6 PM IST.

For IT Pro Registration please check this link : http://aka.ms/Uu9msj

For Developer Registration: http://aka.ms/Ozhcyh

All the session timings are based on the Indian Standard Time


Session Category

Proposed Session Title


Time in IST



Create Cross Platform apps effectively with Portable Class Libraries


4:00 PM

Niraj Bhatt


Introduction to Windows Azure Active Directory


5:00 PM

Vishnu Kumar Tiwari


Integrating Onpremise SQL Server with Salesforce using BizTalk Server 2013


6:00 PM

Nauzad Kapadia


OAuth and the App security model in SharePoint 2013


7:00 PM

Ashutosh Singh


Enriching SharePoint Search using FAST


8:00 PM

Dr Nitin Paranjape


What every developer should know about Office


9:00 PM

Shantanu Kaushik

IT Pro

Preparing and Deploying Windows 8


4:00 PM

Geetesh Bajaj

IT Pro

Working with Flowcharts in Microsoft Office (Audience Profile: Consumer)


5:00 PM

Sundaraarajan Narasiman

IT Pro

SharePoint 2013 App Model – SharePoint Hosted Apps


6:00 PM

Ravikanth C

IT Pro

Desired State Configuration in PowerShell 4.0


7:00 PM

Ratish Nair

IT Pro

Exchange Server 2013 Load balancing and Outlook Client connectivity


8:00 PM

Prabhat Nigam

IT Pro

Exchange 2013 – Database availability Group and Auto Reseed.


9:00 PM

 Subscribe to my blog

Create SharePoint sites using Powershell

I was trying to create the SharePoint Site Provisioning using PowerShell. The following PowerShell script will help us to create a SharePoint sites based on Site Address, Site Name and Site Template parameters.

# This is Script to  Create the Sites, based on the Siteadress and Templates, given by the user.
# Use Get-SPWebTemplate cmdlet to get the list of the installed Site templates.

[Parameter(Mandatory=$true, Position=0)]
[string] $YourSiteAddress,

[Parameter(Mandatory=$true, Position=1)]
[string] $YourSiteName,

[Parameter(Mandatory=$true, Position=2)]
[string] $YourSiteTemplate

#[Parameter(Mandatory=$true, Position=3)]
#[bool] $OverWrite =$false

$OverWrite ='N'
$web = Get-SPWeb $YourSiteAddress -erroraction silentlycontinue
if ($web -ne $null)
     Write-Host ("Web site already present with same name : {0}"-f $YourSiteAddress)
     $OverWrite = Read-Host "If want to overwrite the current website Please enter [Y] else enter [N]"
    if($OverWrite -eq 'Y')
            Write-Host ("Removing the Site {0}" -f $YourSiteAddress)
            Remove-SPWeb $YourSiteAddress -Confirm:$false -erroraction silentlycontinue
            Write-Host (" {0} - Site Removed" -f $YourSiteAddress)

     $web = Get-SPWeb $YourSiteAddress -erroraction silentlycontinue

if($web -eq $null)   
    Write-Host ("Creating the Site {0}"-f $YourSiteAddress)
    New-SPWeb     –url $YourSiteAddress     -name $YourSiteName     -template $YourSiteTemplate     –AddToTopNav:$false   
    –UniquePermissions    -UseParentTopNav:$false
    Write-Host "use OverWrite =[Y]  to overwrite this Site upon getting the prompt, once you rerun the script"
 Subscribe to my blog

Programmatically update Author and Editor fields in SharePoint

I’m working on a data-migration scenario, where there is a need to update the CreatedBy (Author) and ModifiedBy(Editor) fields in SharePoint.

            using (SPSite oSPSite = new SPSite(http://yoursitecollectionurl))
                using (SPWeb oSPWeb = oSPSite.RootWeb)
                    SPList oSPList = oSPWeb.Lists["testlist"];

                    foreach (SPListItem oSPListItem in oSPList.Items)
                        SPFieldUserValue oSPFieldUserValue = new SPFieldUserValue(oSPWeb, oSPWeb.AllUsers[@"domainuser"].ID, 
                        oSPListItem["Author"]= oSPFieldUserValue;
                        oSPListItem["Editor"]= oSPFieldUserValue;

The above code-snippet updates the Author and Editor fields of SharePoint list, based on the specific user (SPFieldUserValue object).

 Subscribe to my blog

SharePoint Multitenancy – Faqs–Part 2

This post is the continuation to my previous post tiled SharePoint Multitenancy – Faqs

1. What are multiple ways in which customer sites can be deployed a SharePoint farm enabled with multi-tenancy ?

  • Dedicated application pool and Web application
  • Shared application pool and dedicated Web application
  • Authenticated Sites
  • Unauthenticated Sites
  • Shared Web application

2.  When to choose dedicated web applications for tenants ?

If the customizations required for tenants affect the resources that are shared across a web application, such as a web.config file

3. What will be the recommended strategy when multiple tenants need to be combined in a single web application ?

While combining multiple tenants into one, it is recommended to have one dedicated web application for authenticated content of all the tenants and another dedicated tenant for all unauthenticated content for all the tenants. Finally, it will require two different subscription IDs for tenants for both the types of content. This approach also will make the licensing simpler.

4. What are the factors to be considered while deploying customizations to a multi-tenant environment ?

The following factors need to be considered while deploying customizations to multi-tenant environment :-

  • Do not allow full-trust code to be deployed to the sites
  • Do not allow the customizations that require changes to the shared resources like web.config file
  • Use host named site-collections to create multiple root-level site-collections (domain-named sites) within a web application

5. What is the factor to be considered when the tenant must span 1 database ?

If the tenant needs to span more than 1 database, there must one and only tenant in all those databases (dedicated content databases for a tenant)

6. What is the factor to be considered when the multiple tenant needs to share a database ?

If a tenant needs to share a database with another tenant, those tenants should NOT span databases.

7. How a hosted environment can be scaled out ?

The hosted environment can be scaled out by creating separate set of farms.

a)Services farm – A dedicated services farm can be created for all the services (applicable) that can be shared across farms.

b)Search farm – A dedicated farm can be created to host Search

c)Tenant content farm – Tenant content farms can be scaled out in a similar way as the services farm

8. What is Organizational Units (OU) of Active Directory and how its is relevant in the context of SharePoint hosting?

Organizational units are used to organize users and computer objects in the Active Directory environment. The same Organizational Unit for SharePoint is illustrated below :-

organizational units IU

9. What is the role of Domain Root ?

The Security policies that need to be applied to the entire domain is applied in the Domain policy. They are configured in the GPOs that apply to the entire domain.

10. What is the role of Domain Controllers OU ?

It holds the most sensitive data in the organization, the data which controls the security configuration itself. GPOs are applied at this level to protect the domain controller.

11. What is the role of SharePoint Server OU ?

It has unique role not included in other servers in the directory. It can be placed in its own OU to allow unique policies to be applied on the servers. It can also be segregated from other servers in the directory.

12. What is the role of customers OU ?

The Customer OU (top-level OU) allows all users accounts to be segregated from the rest of the directory. The next level OU would be the respective customer’s OU (like Customer A OU or Customer B OU). In order to give the users the impression they are logging into their own customer domain, use ADSI Edit or another Active Directory tool to edit the uPNSuffixes attributes.

 Subscribe to my blog

SharePoint Multi tenancy – Faqs

1. What is multi-tenancy in SharePoint ?

The SharePoint platform has the capability to isolate and separate data from different web sites while sharing Service Application resources across same sites. This capability is called as Multi-tenancy. It primarily relies on Site Subscriptions and Subscription Ids

2. How data is partitioned in a hosted environment in SharePoint ?

The data is partitioned in a hosted environment in SharePoint by using the concept of Site Subscriptions. Site Subscription group tenant data across all site-collections owned by tenant, and provide the ability to separate and group each tenant’s data in a shared environment.

3. What is the role of Administrator in the context of hosted SharePoint environments ?

The administrators can centrally deploy and manage features & services, while providing tenants full control over the usage and experience.

4. What is the role of Subscription Ids with respect to SharePoint multi-tenancy ?

The site-collections of each and every tenant are grouped based on a common subscription ID. The Subscription ID helps to map features and services to tenants and also to partition service data according to tenant.

5. Can multiple subscriptions be hosted be hosted in a single web application ?

Yes, multiple Subscriptions can be hosted inside a single web application. Again, multiple subscriptions can also reside in the shared content database.

6. How administrators manage subscriptions and features for each tenant?

Administrators can define which services are available and activated for each tenant. The Subscription ID for a tenant can be used to map service partitions to site-collections

7. Can a service data be shared across multiple tenants ?

Yes, the service data can be shared across multiple tenants, so that all the tenants can share data for a specific service.

8. Can a service data be partitioned for each and every tenant ?

Yes, the service data can be partitioned for each and every tenant, ensuring that sensitive data is not exposed to other tenants. In this case, service data for a single tenant need to be implemented within a separate partition for that service.

9. What are the various roles involved when it comes to Tenant Administration ?

  • Hosting Company
  • Hosted Company Administrator
  • Hosted Company

10. What are the roles of a Hosting Company when it comes to Tenant Administration ?

The following are the typical roles of a Hosting Company for Tenant Administration:

  • Manages the farm-level settings and hardware
  • Controls the database configurations
  • Installs all new approved features and solutions
  • Brands the Tenant Administrator pages

11. What are the roles of a Hosted Company Administrator when it comes to Tenant Administration ?

The following are the typical roles of a Hosted Company when it comes to Tenant Administration :

  • Purchases space, features, and bandwidth from hosting company
  • Controls the architecture of customer sites but not the content
  • Reviews usage statistics

12. What are the roles of a Hosted Company when it comes to Tenant Administration ?

The following are the typical roles of a Hosted Company when it comes to Tenant Administration :

  • Owns a site collection
  • Installs or removes set of features and solutions
  • Configures features and services
  • Reviews usage statistics

 Subscribe to my blog

Migrate SharePoint sites using Content Migration APIs

The export/import method provides the flexibility to migrate a site/sub-site from one web application to another web application (in a different content database) within a farm. It also provides the flexibility to export a sub-site and import it as a root site-collection in another web application. In this post I’d be discussing about how to programmatically migrate SharePoint sites using Content Migration APIs.


Code to export a site

                    string sourceSiteURL = "Your site url";//site to be exported
                    SPExportObject exportObject = "Path where you site to be exported";
                    string folderPath = "folder path";

                    using (SPSite sourceSite = new SPSite(sourceSiteURL))
                        using (SPWeb sourceWeb = sourceSite.OpenWeb())
                            //Create the Export Setting object and update the setting properties.  
                            SPExportSettings settings = new SPExportSettings();
                            settings.SiteUrl = sourceWeb.Url;
                            settings.ExportMethod = SPExportMethodType.ExportAll;
                            settings.BaseFileName = EXPORT_FILENAME; // "export.cmp";
                            settings.FileLocation = "provide file location";
                            settings.LogFilePath = @folderPath + LOG_FILENAME; // "\LogFile.log";                                
                            settings.IncludeSecurity = SPIncludeSecurity.All;

                            setExcludeDependencies(migrationSettings, settings);
                            settings.OverwriteExistingDataFile = true;
                            settings.CommandLineVerbose = true;
                            settings.FileMaxSize = 1024;
                            settings.FileCompression = true;

                            // Add the Export object to the ExportSetting Object  

                            // add the Export Settings to the SPExport object and Run the Export .  
                            SPExport export = new SPExport(settings);

                            LogAll.logTextWriting(true, ServerConstant.exportSuccessfully);
                            isExportCompleted = true;

Code to import a site

                    // Get the Site collection Url from the config file.  

                    using (SPSite rootSiteColl = new SPSite(destinationSiteURL))
                        SPWebApplication webApp = rootSiteColl.WebApplication;
                        rootSiteColl.AllowUnsafeUpdates = true;
                        using (SPWeb rootWeb = rootSiteColl.OpenWeb())
                            // Package import
                            System.Uri siteURL = new Uri(destinationSiteURL);
                            string baseDataFileName = EXPORT_FILENAME; // "export.cmp";
                            string dataFileLocation = @folderPath;
                            string logFileLocation = @folderPath + LOG_FILENAME; // "\LogFile.log";

                            SPImportSettings importSettings = new SPImportSettings(siteURL, dataFileLocation, baseDataFileName);
                            importSettings.IncludeSecurity = SPIncludeSecurity.All;
                            importSettings.RetainObjectIdentity = true;                            
                            importSettings.CommandLineVerbose = true;
                            importSettings.LogFilePath = logFileLocation;
                            importSettings.WebUrl = destinationSiteURL;
                            importSettings.FileCompression = true;

                            SPImport import = new SPImport(importSettings);
                            rootWeb.AllowUnsafeUpdates = false;
                            webApp.FormDigestSettings.Enabled = true;
                            webApp.FormDigestSettings.Expires = true;
                        rootSiteColl.AllowUnsafeUpdates = false;

The power of the import functionality is that we can pick and choose whether to retain the security, versions, object ids etc. The main drawback of this approach
is that it does not preserve workflow instances, workflow associations, history and tasks. Every workflow association must be recreated and there is no way
to restore the running instances from original site. But nonetheless, the export/import has real power or re-arranging the site-hierarchy in the target.

 Subscribe to my blog

SharePoint 2013 Programmatically read list items using Java Script

Yesterday, I saw a question in MSDN forums on how to programmatically read SharePoint List items using JavaScript. Here is the full workable code below :-

var siteUrl = '/sites/MySiteCollection';

function retrieveListItems() {

    var clientContext = new SP.ClientContext(siteUrl);
    var oList = clientContext.get_web().get_lists().getByTitle('YourCustomList');
    var camlQuery = new SP.CamlQuery();
    camlQuery.set_viewXml('<View><Query><Where><Geq><FieldRef Name='ID'/>' + 
        '<Value Type='Number'>1</Value></Geq></Where></Query><RowLimit>10</RowLimit></View>');
    this.collListItem = oList.getItems(camlQuery);
    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));        

function onQuerySucceeded(sender, args) {

    var listItemInfo = '';

    var listItemEnumerator = collListItem.getEnumerator();
    while (listItemEnumerator.moveNext()) {
        var oListItem = listItemEnumerator.get_current();
        listItemInfo += 'nID: ' + oListItem.get_id() + 
            'nTitle: ' + oListItem.get_item('Title') + 
            'nBody: ' + oListItem.get_item('Body');


function onQueryFailed(sender, args) {

    alert('Request failed. ' + args.get_message() + 'n' + args.get_stackTrace());

 Subscribe to my blog

Inspecting SharePoint 2013 ContextToken and Refresh Token

In previous post, I briefly discussed about the OAuth Tokens and SharePoint 2013 Authentication & Authorization.  We know that there are couple of tokens, namely Context-Token and Refresh-Token are involved in the life-cycle of SharePoint 2013 App Authentication and Authorization. These tokens are not exactly the SAML 1.1 tokens and they  are bit different. The whole intend of this article is to inspect and understand what these tokens are.

In this article I would be creating a sample Auto-Hosted App, inside the page_load of the App-web project (of auto-hosted app) I would be adding some snippet of code to inspect and fetch the OAuth Context Token and Refresh Token.

Let’s create a sample Auto-Hosted App in Visual Studio 2012 with name ‘TestAppforOAuth’,


Open the default.aspx.cs of the AppWeb Project

Import the following namespaces at the top of the project

using Microsoft.SharePoint.Client;
using System.Net;
using System.IO;

In the Page_Load method add the following snippet of code

string contextTokenString =

if (contextTokenString != null)
            SharePointContextToken contextToken =
                  contextTokenString, Request.Url.Authority);

            Response.Write("<h2>Valid context token</h2>");
                  "<p>" + contextToken.ToString() + "</p>");

            Uri sharepointUrl = new      
            string accessToken =

            Response.Write("<h2>Valid access token 
            Response.Write("<p>" + accessToken + "</p>");

            HttpWebRequest request =
                   (sharepointUrl.ToString() + 
            request.Headers.Add("Authorization", "Bearer " +
            HttpWebResponse response = 
            StreamReader reader = new 

            Response.Write("<h2>Web title retrieved using 
            Response.Write("<p>" + reader.ReadToEnd() + "</p>");

Configure the Tenant level Read Permission for the App.

app permission1

app permission2

Hit F5, Deploy the app and trust it. If we inspect the Tokens these are not SAML, they are what they call it as JWT Tokens.


 Subscribe to my blog