Connect Sharepoint With AppID Certificate

On 21/03/2023

In SharepointCode

Connect to Sharepoint using app registration and certificate

 



using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Graph;
using PnP.Core.Auth;
using PnP.Core.Auth.Services.Builder.Configuration;
using PnP.Core.Services;
using PnP.Core.Services.Builder.Configuration;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;


namespace HGH.Buisiness4
{
    public class SPTools2 : IDisposable
    {
        private IHost _host;


        public SPTools2()
        {

        }

        public async Task Connect(string appId, string tenantId, string siteUrl, string thumbprint, StoreName storeName, StoreLocation storeLocation)
        {
            try
            {
                _host = Host.CreateDefaultBuilder()
               .ConfigureServices((hostingContext, services) =>
               {
                   // Add the PnP Core SDK library
                   services.AddPnPCore(options =>
                   {
                       options.Sites.Add("SiteToWorkWith", new PnPCoreSiteOptions
                       {
                           SiteUrl = siteUrl
                       });
                   });
                   services.AddPnPCoreAuthentication(
                       options =>
                       {
                           // Configure an Authentication Provider relying on Windows Credential Manager
                           options.Credentials.Configurations.Add("x509certificate",
                               new PnPCoreAuthenticationCredentialConfigurationOptions
                               {
                                   ClientId = appId,
                                   TenantId = tenantId,
                                   X509Certificate = new PnPCoreAuthenticationX509CertificateOptions
                                   {
                                       StoreName = storeName,
                                       StoreLocation = storeLocation,
                                       Thumbprint = thumbprint
                                   }
                               });

                           // Configure the default authentication provider
                           options.Credentials.DefaultConfiguration = "x509certificate";

                           // Map the site defined in AddPnPCore with the 
                           // Authentication Provider configured in this action
                           options.Sites.Add("SiteToWorkWith",
                               new PnPCoreAuthenticationSiteOptions
                               {
                                   AuthenticationProviderName = "x509certificate"
                               });
                       });


               })
            // Let the builder know we're running in a console
            .UseConsoleLifetime()
            // Add services to the container
            .Build();
                await _host.StartAsync();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"ERROR SPTools2 appId {appId} siteUrl {siteUrl} thumbprint {thumbprint} {ex}");
                throw new Exception($"ERROR SPTools2 appId {appId} siteUrl {siteUrl} thumbprint {thumbprint}", ex);
            }
            return 1;
        }

        public async Task LoadWeb()
        {
            try
            {
                // Optionally create a DI scope
                using (var scope = _host.Services.CreateScope())
                {
                    // Obtain a PnP Context factory
                    var pnpContextFactory = scope.ServiceProvider
                        .GetRequiredService();
                    // Use the PnP Context factory to get a PnPContext for the given configuration
                    using (var context = await pnpContextFactory.CreateAsync("SiteToWorkWith"))
                    {
                        // Retrieving web with lists and masterpageurl loaded ==> SharePoint REST query
                        var web = await context.Web.GetAsync(p => p.Title, p => p.Lists,
                        p => p.MasterUrl);

                        Console.WriteLine($"Web Title {web.Title} Loaded");
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"ERROR LoadWeb{ex}");
                throw new Exception($"ERROR LoadWeb ", ex);
            }
            return 1;
        }

        public void Dispose()
        {
            if (_host != null)
                _host.Dispose();
        }
    }
}


 

 

 

 

Sharepoint

No ratings yet - be the first to rate this.