Skip to content

Instantly share code, notes, and snippets.

@AhmadiRamin
Last active October 3, 2020 13:24
Show Gist options
  • Save AhmadiRamin/bf8b5decba49d7169b8a4e173e58b16c to your computer and use it in GitHub Desktop.
Save AhmadiRamin/bf8b5decba49d7169b8a4e173e58b16c to your computer and use it in GitHub Desktop.
SharePoint App Only Helper
/*
If you have a .Net Core/Standard solution or you don't want to use PnP Authentication Manager, this is the best approach to get SharePoint App Only Permission.
1- Create an App Registration in Azure
2- Navigate to http://<SharePointWebSite>/_layouts/15/AppInv.aspx and follow the steps from the link below to give your application access:
https://docs.microsoft.com/en-us/sharepoint/dev/sp-add-ins/add-in-permissions-in-sharepoint
3- Add this class to your solution and install Microsoft.SharePointOnline.CSOM NuGet Package.
4- Update Client Id, Client Secret and Tenant Id in this class
5- Get the SharePoint context and do what your application needs to do:
var token = await SharePointAppOnlyHelper.AcquireTokenAsync();
string webUrl = Environment.GetEnvironmentVariable("WebURL");
var clientContext = SharePointAppOnlyHelper.GetClientContext(webUrl, token);
*/
using System;
using System.Threading.Tasks;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using Microsoft.SharePoint.Client;
namespace Contoso.AuthenticationHelpers
{
public static class SharePointAppOnlyHelper
{
private static readonly string ClientId = Environment.GetEnvironmentVariable("CLIENTID");
private static readonly string ClientSecret = Environment.GetEnvironmentVariable("CLIENTSECRET");
private static readonly string targetHost = Environment.GetEnvironmentVariable("TARGETHOST"); //e.x. contoso.sharepoint.com
private static readonly string TenantId = Environment.GetEnvironmentVariable("TENANTID");
private static readonly string principal = "00000003-0000-0ff1-ce00-000000000000";
private static readonly string tokenEndpoint = $"https://accounts.accesscontrol.windows.net/{TenantId}/tokens/OAuth/2";
public static async Task<string> AcquireTokenAsync()
{
string resource = $"{principal}/{targetHost}@{TenantId}";
var body = $"resource={resource}" +
$"&client_id={ClientId}@{TenantId}" +
$"&grant_type=client_credentials" +
$"&client_secret={ClientSecret}";
using (var stringContent = new StringContent(body, Encoding.UTF8, "application/x-www-form-urlencoded"))
{
using (HttpClient httpClient = new HttpClient())
{
var result = await httpClient.PostAsync(tokenEndpoint, stringContent).ContinueWith((response) =>
{
return response.Result.Content.ReadAsStringAsync().Result;
}).ConfigureAwait(false);
var tokenResult = System.Text.Json.JsonSerializer.Deserialize<JsonElement>(result);
var token = tokenResult.GetProperty("access_token").GetString();
return token;
}
}
}
public static ClientContext GetClientContext(string targetUrl, string accessToken)
{
ClientContext clientContext = new ClientContext(targetUrl);
clientContext.ExecutingWebRequest +=
delegate (object oSender, WebRequestEventArgs webRequestEventArgs)
{
webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] =
"Bearer " + accessToken;
};
return clientContext;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment