Created
April 11, 2020 06:38
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.