So, recently I needed to create a service that would read and write some data to SharePoint Online, easy enough, isn’t it? Problem was that the scenario demanded that the processing were done in Azure, specifically in Azure Functions. Hmmm… How difficult can it be? (Well, it has to do with SharePoint, so…)
The first thing I did was to import the usual packages that I use to connect to SharePoint:
Both packages had worked perfectly in all previous scenarios, then I had no reason to not try it.
Problem was that the version that the runtime downloaded didn’t have an option for obtaining an App Only Authorization Token, which was necessary in my case.
So, cutting to the chase, after some struggle I found a version of TokenHelper.cs that had the methods that I needed and then I’ve been able to successfully convert it to .csx. The file is available in the following link:
This file will allow you to connect to SharePoint Online using App-Only Authorization like this:
const string SharePointPrincipal = "00000003-0000-0ff1-ce00-000000000000";
static Uri TargetHost = new Uri(Environment.GetEnvironmentVariable("SiteUrl", EnvironmentVariableTarget.Process));
static string Realm = Environment.GetEnvironmentVariable("Realm", EnvironmentVariableTarget.Process);
static string ClientId = Environment.GetEnvironmentVariable("ClientId", EnvironmentVariableTarget.Process);
static string ClientSecret = Environment.GetEnvironmentVariable("ClientSecret", EnvironmentVariableTarget.Process);
var token = TokenHelper.GetAppOnlyAccessToken(SharePointPrincipal, TargetHost.Authority, Realm, ClientId, ClientSecret).AccessToken;
var ctx = TokenHelper.GetClientContext(Environment.GetEnvironmentVariable("SiteUrl", EnvironmentVariableTarget.Process), token);
This is as simple as it gets 😀
I hope this helps anyone who is starting with Azure Functions and SharePoint!