How do I use SharePoint Rest API in C# .NET Framework using Client ID and Client Secret?

775 Views Asked by At

Is there any way to authenticate an application with SharePoint rest API like Graph API using Client ID and Client Secret? I wanna use SharePoint rest API in my console application.

1

There are 1 best solutions below

1
On BEST ANSWER

This works for me:

In Azure Active Directory I have configured permissions for SharePoint API. enter image description here

In my code I have scopes defined this way:

var scopes = new [] {"https://<tenantName>.sharepoint.com/allsites.manage"};

var clientApp = ConfidentialClientApplicationBuilder.Create($"{clientId}")
            .WithAuthority($"https://login.microsoftonline.com/{tenantId}")
            .WithClientSecret($"{clientSecret}").Build();

// acquire a token for the app
AuthenticationResult result = null;
try
{
    result = await clientApp.AcquireTokenForClient(scopes)
                             .ExecuteAsync();
}
catch (MsalUiRequiredException ex)
{
...
}
catch (MsalServiceException ex)
{
...
}