Forum Discussion

johnjohn-Peter's avatar
johnjohn-Peter
Iron Contributor
Feb 06, 2024

Connecting a .net 8.0 console application which uses PnP Core sdk to sharepoint online using certifi

I have create a AD app registration which uses self-signed certificate for authentication. and i grant the AD app registration full control on SharePoint and graph APIs.

now i want to build a .net 8.0 console application which run on schedule bases .. so can i use PnP core SDK with AD app that uses self-signed certificate ? if this is possible, then is there a sample code that can help me?

here what i tried so far, but got error:-

using PnP.Core.Auth;
using PnP.Core.Services;
using System.Security.Cryptography.X509Certificates;

namespace ConsoleApp3
{
    public class Program
    {
        private readonly IPnPContextFactory pnpContextFactory;
        public Program(IPnPContextFactory pnpContextFactory)
        {
            this.pnpContextFactory = pnpContextFactory;

        }
        static async Task Main(string[] args)
        {
            var tenantId = "your-tenant-id";
            var clientId = "your-application-id";
            var certificatePath = "path-to-your-certificate.pfx";
            var certificatePassword = "your-certificate-password";

            // Load the certificate
            var authenticationProvider = new X509CertificateAuthenticationProvider(tenantId, clientId, X509Certificate2.CreateFromPemFile(certificatePath, certificatePassword));

            // Use the authentication provider to configure PnPContextFactory
            var pnpContextFactory = new PnPContextFactory(new AuthenticationProviderFactory((resource) => authenticationProvider));

            // Create a PnPContext for your SharePoint site
            var siteUrl = "https://yourtenant.sharepoint.com/sites/yoursite";
            using var context = await pnpContextFactory.CreateAsync(new Uri(siteUrl));
        }
    }
}

Here is the full error details:-

 

 

1 Reply

  • _Mor10_'s avatar
    _Mor10_
    Copper Contributor

    johnjohn-Peter I think you have swapped the tenantid and clientid parameters for X509CertificateAuthenticationProvider constructor:

     

    // Load the certificate
                var authenticationProvider = new X509CertificateAuthenticationProvider(tenantId, clientId, X509Certificate2.CreateFromPemFile(certificatePath, certificatePassword));

     It is clientid first, then tenantid according to documentation:

     

    public X509CertificateAuthenticationProvider(string clientId, string tenantId, X509Certificate2 certificate)

     

Resources