Thursday, 7 July 2016

OfficeDev: Inconvenient SharePoint App only permission using Azure AD Apps

App Only Permission using AAD App and SharePoint online
I was playing around with adal-node trying to build a remote event receiver using NodeJS, however I stumble on a big issue, which is even my Azure AD App explicitly has SharePoint Online added as a resource with all app only permission set selected I always got a strange error "unsupported app only token" I find out that my fellow MVP  John Liu faced a similar problem and he explained it in details in his post here with a fix using certificates.



Inspecting SharePointContext.cs


By Looking at SharePointContext.cs abstract class which is generated when you add SharePointPnPCoreOnline nuget package to your visual studio project I notice in this case app only permission works fine for SharePoint online!
By going through the code and with little help of ILSPY I manage to understand how the accesstoken is being generated using SharePointContext  and TokenHelper classes to access SharePoint online via client credentials, the flow is as below:

  1. get realm by executing dummy call to client.svc and reading the www-authenticate header 
  2. update client_id to be on the format client_id@realm
  3. update resource to be string concatenation of the following
    1. SharePoint Principle always =00000003-0000-0ff1-ce00-000000000000
    2. your tenant subdomain *.sharepoint.com
    3. realm value
  4. executing a client_credential token POST request to https://accounts.accesscontrol.windows.net/{realm}/tokens/OAuth/2

by executing this request in postman I manage to get access_token for SharePoint online 


Creating NodeJs Module

After this small experiment I figured I will create a small nodejs package so it can be used to connect to SharePoint online using client Id and secret without the need for a certificate in the same manner any command line application created using visual studio can.

I've created nodejs module and published it here @https://github.com/ministainer/SharePoint-apponly-node

The modeul is also published @https://www.npmjs.com/package/sharepoint-apponly-node you can install it by simply

and here is how to use it



The repos is just a seed will add token refresh and cache capabilities later.


Related Articles