Hi SharePoint guys !

It’s been a while I haven’t written a blog post mainly due to lack of free time. Thanks to the end of year holidays, I could spend a few hours to build a proof-of-concept which, IMHO, might be really interesting. Hope you will be interested in it as much as I am.

Introduction

The SharePoint Framework is the new promoted development model for SharePoint customizations. It follows the current web development trends (Asynchronous HTTP calls, Web/REST APIs, …). In this article, we will then see how to implement a custom Web API based on the SharePoint add-in model we can call from our SPFx solutions.

A few months ago, I wrote a post explaning how to call App Only proxy implemented as Azure Functions from SPFx. This previous blog post focuses on Azure Functions, and is relevant for Cloud or Hybrid environments, it relies on Azure Function, Azure AD and can easily be extended with Microsoft Graph.

Unfortunately, in a ‘pure’ On-prem environment without any cloud components, the previous blog post is not relevant. At the time, SPFx was not available for SharePoint on-premises, Now it is ! I then decided to port this concept using the assets and techniques we can all use in a full on-prem environment. This post will leverage the SharePoint provider-hoster add-in model which is applicable to both SharePoint Online and SharePoint (full) On-prem.

The case study

In order to implement a relevant Proof-of-Concept, let’s ellaborate a context and some requirements.

  • We want to manage some business documents from a custom SPFx WebParts
  • The SPFx WebPart will interact with SharePoint exclusively via a custom Web API
  • The custom Web API will be a simple CRUD for Business Documents stored in a SharePoint document library

To make sure to rely on the same library structure as I am, you can use the provisioning assets here. You will need to have the PnP PowerShell module installed and execute the Provision.ps1 script.

Let’s create a SharePoint add-in

We will first create a new SharePoint provider-hosted add-in solution like any other one.
Open Visual Studio and create your new project as usual

vs-newproj

Enter the address of your SharePoint development site and select the Provider-hosted hosting option.

vs-addin-type

Select the targeted SharePoint version (in my case, I use SharePoint Online, but this blog post is also valid for SharePoint 2016 FP2)

vs-choose-spversion

Select ASP.NET MVC Web Application

vs-choose-webapp-type

vs-choose-trust-type

  1. Select this option if you are using SharePoint Online or SharePoint On-prem with a configured low trust
  2. Select this option if you are using Server-to-server authentication in an on-prem environement (You will have to configure the X.509 certificate if you do so). Check this for more accurate information

Now that we have the boilerplate code of our solution, let’s configure the SharePoint add-in. Open the AppManifest.xml file

Let’s change the start page value

addin-appmanifest-startpage

Let’s set the [your-project]/Home/Register value.

On the permissions tab, select List as the Scope and select Full Control. Make sure to tick the checkbox to allow app-only calls

addin-appmanifest-perms

A custom Web API in a SharePoint add-in

The SharePoint provider-hosted add-in model and the featured boilerplate code in the corresponding Visual Studio project template allows to use CSOM either in App+User or in App-Only mode.

How does it work ?

It relies on an authentication flow (OAuth in low-trust or direct in high-trust). To initiate this authentication flow, when you click the add-in icon in SharePoint, you reach a SharePoint system page (appredirect.aspx) that redirects you to your provider hosted application default page. This HTTP call issued for the redirection contains all the information of the current context (SharePoint and User context), this context will be persisted in the user session on the server side. It will later be used to create a CSOM ClientContext object instance that is the base of any CSOM operation.

At each time a page (or ASP.NET MVC action) is reached, the current user context is fetched from his session state or created if it does not exist yet. If no context can be fetched or created on the server (for example, because needed information is missing), the user is redirected to an error page. because he cannot be properly authenticated, he won’t be able to go further.

With a stateless Web API ?

By nature, a Web/REST API is stateless, it means that the common implementation will not handle user sessions. In the code, you won’t have access to any session state for the current Request object.

Anyway,  the SharePoint add-in model needs some kind of session mechanism to work properly, we can implement our own session mechanism with the following steps :

  1. When the appredirect.aspx SharePoint page redirects to the provider-hosted addin default page, save the created context in cache with a specific key.
  2. Add a cookie in the HTTP response that will contain the cache key. This cookie will be included in all subsequent calls
  3. In the next HTTP calls, get the cached context using the key contained in the cookie of the current request.

Hum…OK. That’s a lot of work for such a basic thing…

pnp-superhero

Exactly ! We might need some help! Let’s call our friend the PnP super-hero !

Actually, once again, the community has done great job and already implemented such a mechanism in the PnP Core library.

All the stuff we need are here:

https://github.com/SharePoint/PnP-Sites-Core/tree/master/Core/OfficeDevPnP.Core/WebAPI

OK, let’s install the PnP Core library package in our solution.
In the Package Manager Console of Visual Studio, make sure you select your Web application project and type the following command

vs-packagemanager-installpnp2016

There is a module for each SharePoint currently supported version

  • SharePointPnPCore2013
  • SharePointPnPCore2016
  • SharePointPnPCoreOnline

Choose the one that suits for you.

While you’re in the Package Manager console, enter also the command:
> Install-Package Microsoft.AspNet.WebApi.Cors

As you understood above, we will need to register the Web API to make sure the subsequent calls will be able to fetch the SharePoint context stored in the cache.

In the HomeController, we will then create a dedicated action (make sure to include the needed using clause)

Let’s then create a ViewModel class that will represent our business document entity. In the empty Models folder, add a new class name BusinessDocumentViewModel

We will then add our Web API controller

  1. Right-click the Controllers folder
  2. Expand the Add menu
  3. Click Controller…

vs-add-apicontroller-01

Select the Web API 2 Controller with read/write actionsvs-add-apicontroller-02And name if “BusinessDocumentsControllervs-name-apicontroller

Replace the code of the scaffolded class by this one

It is the complete implementation of our custom Web API. We have to notice several important parts:

  1. The use of [EnableCors] attribute that will allow our Web API to be called from JavaScript executed outside of our domain (JavaScript of the SPFx WebPart. You will have to change the value of the origins parameter to match your own SharePoint domain.
  2. The use of [WebAPIContextFilter] attribute that will make sure the call is issued by an authenticated user. Will actually fetch the context in cache from the key stored in the request cookie.
  3. The use of
    varclientContext = WebAPIHelper.GetClientContext(this.ControllerContext)
    instead of the classic SharePointContextProviderto instantiate the ClientContext object.

In order for everything to work, you will also have to make some changes in the Global.asax file

as well as in the WebApiConfig class

At this step, we are done with our Web API. you can hit F5 to deploy the addin of our dev site. You can leave it running.

Don’t forget to select the right library when trusting the add-in

trust-webapi

If you want to see the complete Web API solution code, you can go to the GitHub repo

The SPFx WebPart

Let’s create a new SPFx WebPart project with the famous yo @microsoft/sharepoint

Let’s add a service class that will be responsible to issue the calls the our Web API

and let’s create our main React component for our WebPart

The most important parts in this code are the following :

  • The hidden IFrame in the render() method, it will reach the default page of the add-in to initiate the context on the server-side
    <iframe
    src={this.apiConfig.appRedirectUri}
    style={{ display: ‘none’ }}
    onLoad={() => (this.authenticated = true)}
    />
  • The _executeOrDelayUntilAuthenticated() method that will execute the function as argument only after the IFrame content is loaded. This will make sure the the Web API calls are done only after the user is properly authenticated.

Another service class is used as the configuration holder and will take and compute its values from the WebPart properties.

webpart-properties

  • remoteApiHost : must contains the base URL of the provider hosted add-in (In this case, I use the address of my IIS Express instance launched by Visual Studio)
  • appInstanceId : must contains the GUID of the add-in instance. This GUID is found as the value of the query string parameter of the appredirect.aspx page when you click your add-in icon in SharePoint.

 

The App Instance ID can also be easily found using PnP PowerShell, just use the following PowerShell cmdlet:

Get-PnPAppInstance -Identity “your app name”

ps-appinstanceid

Just copy/paste the Id as the value of the “App Instance ID” WebPart property

You will find the whole SPFx solution in the GitHub repo

Result

This slideshow requires JavaScript.

We have now a custom WebPart able to interact with SharePoint data via our custom Web API. In this API we can implement any business logic, use App-Only mode or stick to the User permissions context. This solution is usable on SharePoint Online as well as on SharePoint On-prem !

Now that I have this boilerplate and PoC running, I think it will become my favorite approach when I need to build a customization that needs server-side custom code 🙂

Leave your comments and feedback and please share this blog around you !

I wish you all the best for the upcoming new year and you can expect plenty other blog posts in 2018 !

Best regards,

Yannick

Advertisements