Client Context in AddIn

How to get the client context for code in a provider-hosted add-in that is called outside of the SharePoint context.

For example, you want a page in your solution to be called directly and not from SharePoint. Reasons for this may be that you have a page in the add-in that you want to share with users and don’t want to give the full add-in url. Instead of:{etc}

You want something like this, without all the parameters:

With the former, you’ll be able to get the context with:

var context = SharePointContextProvider.Current.GetSharePointContext(Context);

Trying this without all the parameters will obviously fail and you’ll get a 401 unauthorised error.

To get a valid context this way, you’ll need to have the SharePoint host’s URL stored somewhere in the remote website. In the web.config for example.

To obtain the context, use this instead:

var hostUri = new Uri(ConfigurationManager.AppSettings["HostUrl"]);
using (var context = TokenHelper.GetS2SClientContextWithWindowsIdentity(hostUri, Request.LogonUserIdentity){
// CSOM code

This will create the context for the current user and you should now be able to query the SharePoint site’s content.

This entry was posted in SharePoint, SharePoint Shorts and tagged . Bookmark the permalink.
0 0 votes
Article Rating
Notify of

Solve the maths problem shown below before posting: *

Inline Feedbacks
View all comments