Skip to content

Instantly share code, notes, and snippets.

@jesuslpm
Created April 11, 2020 06:38
Show Gist options
  • Save jesuslpm/f71ccb75ba37bd7ce84f2aa43518cbbf to your computer and use it in GitHub Desktop.
Save jesuslpm/f71ccb75ba37bd7ce84f2aa43518cbbf to your computer and use it in GitHub Desktop.
Access SharePoint REST API from .net core using Azure AD registered app with certificate
using Microsoft.Identity.Client;
using System;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
namespace SharePoint.RestApi
{
class Program
{
const string ClientId = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";
const string CertificateFileName = "example.sharepoint.pfx";
const string Authority = "https://login.windows.net/example.com";
static string[] scopes = new string[] { "https://example.sharepoint.com/.default" };
static async Task Main(string[] args)
{
var app = ConfidentialClientApplicationBuilder.Create(ClientId)
.WithCertificate(GetCertificate())
.WithAuthority(Authority)
.Build();
var aquireTokenResult = await app.AcquireTokenForClient(scopes).ExecuteAsync();
using (var httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", aquireTokenResult.AccessToken);
httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Accept", "application/json;odata=verbose");
var requestMessage = new HttpRequestMessage(HttpMethod.Post, "https://example.sharepoint.com/_api/web?$select=Title");
var responseMessage = await httpClient.SendAsync(requestMessage);
var responseContent = await responseMessage.Content.ReadAsStringAsync();
Console.WriteLine(responseMessage.StatusCode);
Console.WriteLine(responseContent);
}
}
static X509Certificate2 GetCertificate()
{
var certificatePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, CertificateFileName);
return new X509Certificate2(certificatePath);
}
}
}
@jesuslpm
Copy link
Author

jesuslpm commented Apr 11, 2020

Read the article Granting access via Azure AD App-Only to learn how to set up an Azure AD app.

Also the article Get Azure AD app-only access token using certificate on .NET Core is very interesting, it provides you some background.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment