.Net Core Console Application for SharePoint Online Using PNPCore Library Username and Password Login

Sathish Nadarajan
 
Solution Architect
November 23, 2021
 
Rate this article
 
Views
3340

In the earlier article,   we saw how to get the PNP Core Context through interactive login, similarly in this article, let us see to get the context by Providing the Username and Password.  Usually this could be the Service Account credentials.

using Microsoft.Extensions.Configuration;

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using PnP.Core.Auth;
using PnP.Core.Services;
using System.Linq;
using System.Threading.Tasks;

 

namespace AZ.Help.Core
{
class Program
{
public static async Task Main(string[] args)
{

var host = Host.CreateDefaultBuilder()

.ConfigureLogging((hostingContext, logging) =>

{
logging.AddConsole();
})
.ConfigureServices((hostingContext, services) =>
{

var customSettings = new CustomSettings();
hostingContext.Configuration.Bind("CustomSettings", customSettings);

//Create an instance of the Authentication Provider that uses Credential Manager
var authenticationProvider = new UsernamePasswordAuthenticationProvider(
customSettings.ClientId,
customSettings.TenantId,
customSettings.UserPrincipalName,
customSettings.Password.ToSecureString());

services.AddPnPCore(options =>
{
options.DefaultAuthenticationProvider = authenticationProvider;
options.Sites.Add("DemoSite",
new PnP.Core.Services.Builder.Configuration.PnPCoreSiteOptions
{
SiteUrl = customSettings.DemoSiteUrl,
AuthenticationProvider = authenticationProvider
});
});
})

// Let the builder know we're running in a console
.UseConsoleLifetime()

// Add services to the container

.Build();

await host.StartAsync();

using (var scope = host.Services.CreateScope())
{
var pnpContextFactory = scope.ServiceProvider.GetRequiredService<IPnPContextFactory>();
using (var context = await pnpContextFactory.CreateAsync("DemoSite"))
{
var page = (await context.Web.GetPagesAsync("DemoPage")).FirstOrDefault();
await page.TranslatePagesAsync();
}
}
host.Dispose();
}
}

}

  

Happy Coding

Sathish Nadarajan

Author Info

Sathish Nadarajan
 
Solution Architect
 
Rate this article
 
Sathish is a Microsoft MVP for SharePoint (Office Servers and Services) having 15+ years of experience in Microsoft Technologies. He holds a Masters Degree in Computer Aided Design and Business ...read more
 

Leave a comment