Reputation: 14159
A C# console application which runs like a background job from Windows Task Scheduler is using simple authentication with hardcoded username and password to connect to Sharepoint.
This application downloads list of sites from Sharepoint and creates a file in a folder. I have been asked to replace the simple authentication with any modern authentication. I googled around and found that I need an authentication without interactive browser since it is a background job.
I found below code and also want to try out on a machine which does not have Microsoft Identity and Sharepoint license. So I have two questions here:
Is the below code sufficient to authenticate without interactive browser ?
I want to buy Microsoft 365 Basic license. It shows under included list Identity, Sharepoint etc. Are these sufficient to try out below code ?
Code:
using System;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.Graph;
using Microsoft.Identity.Client;
class Program
{
private static async Task Main(string[] args)
{
string tenantId = "YOUR_TENANT_ID";
string clientId = "YOUR_CLIENT_ID";
string clientSecret = "YOUR_CLIENT_SECRET";
var scopes = new[] { "https://graph.microsoft.com/.default" };
// Create an authentication provider
var confidentialClient = ConfidentialClientApplicationBuilder
.Create(clientId)
.WithClientSecret(clientSecret)
.WithAuthority($"https://login.microsoftonline.com/{tenantId}")
.Build();
var authProvider = new DelegateAuthenticationProvider(async (requestMessage) =>
{
var authResult = await confidentialClient.AcquireTokenForClient(scopes).ExecuteAsync();
requestMessage.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", authResult.AccessToken);
});
// Create GraphServiceClient
var graphClient = new GraphServiceClient(authProvider);
// Fetch SharePoint site details
await GetSharePointSite(graphClient);
}
private static async Task GetSharePointSite(GraphServiceClient graphClient)
{
try
{
var site = await graphClient.Sites["contoso.sharepoint.com"].Request().GetAsync();
Console.WriteLine($"Site ID: {site.Id}");
Console.WriteLine($"Site Name: {site.DisplayName}");
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
}
}
Upvotes: 0
Views: 35