đź”§ Authenticating to SharePoint Online with PnP Core SDK and MSAL in .NET 6+
Author: Edvaldo GuimarĂŁes\ Category: Microsoft 365 Development / C# / SharePoint\ Tags: .NET 6, PnP Core SDK, MSAL, SharePoint Online, Authentication
đź§ Introduction
In this article, we’ll explore how to authenticate to SharePoint Online using the PnP Core SDK and MSAL interactive login in a .NET 6+ console application. This is the foundation for building powerful automation tools that interact with SharePoint securely and efficiently.
🛠️ Prerequisites
To follow along, you’ll need:
- Visual Studio 2022 with .NET 6 or later
- A registered Azure AD App with:
- Client ID
- Tenant ID
- Delegated permission:
Sites.ReadWrite.All
- Access to a SharePoint Online site
🚀 Implementation
1. Create a Console App
In Visual Studio:
- Create a new project → Console App (.NET 6 or higher)
- Name it
SharePointUploader
2. Install Required NuGet Packages
Install the following packages via NuGet Package Manager:
PnP.Core
PnP.Core.Auth
These packages provide access to SharePoint Online and authentication via MSAL.
3. Final Working Code
using System;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using PnP.Core.Auth;
using PnP.Core.Services;
class Program
{
static async Task Main(string[] args)
{
var services = new ServiceCollection();
string clientId = "YOUR_CLIENT_ID";
string tenantId = "YOUR_TENANT_ID";
string siteUrl = "https://YOUR_DOMAIN.sharepoint.com/sites/YOUR_SITE";
// Register PnP Core SDK services
services.AddPnPCore();
services.AddPnPCoreAuthentication();
// Register interactive authentication provider
services.AddScoped<IAuthenticationProvider>(sp =>
new InteractiveAuthenticationProvider(
clientId,
tenantId,
new Uri("http://localhost")
)
);
var serviceProvider = services.BuildServiceProvider();
var contextFactory = serviceProvider.GetRequiredService<IPnPContextFactory>();
using var context = await contextFactory.CreateAsync(siteUrl);
Console.WriteLine("âś… Successfully connected to SharePoint!");
}
}
âś… What This Code Does
- Sets up dependency injection for PnP Core SDK
- Uses MSAL for interactive login
- Connects to a SharePoint Online site using the provided URL
- Prints a success message once connected
🔄 What’s Next?
In the next article, we’ll extend this app to:
- List files modified in the last hour from a local directory
- Upload those files as attachments to a specific item in a SharePoint list
This will turn your app into a practical automation tool for document tracking and integration with Microsoft 365.
📌 Conclusion
Using the PnP Core SDK with MSAL interactive login is a modern, secure, and scalable way to connect to SharePoint Online. This approach aligns with Microsoft’s best practices and prepares your app for future enhancements
