Client Context in AddIn

SharePoint Short #22

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:

http://myaddindomain.com/pages/custompage.aspx?SPHostUrl={etc}

You want something like this, without all the parameters:

http://myaddindomain.com/pages/custompage.aspx

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, Shorts and tagged . Bookmark the permalink.
0 0 votes
Article Rating
Subscribe
Notify of
guest

Solve the maths problem shown below before posting: *

0 Comments