Use CSOM instead of PnP core to interact with SharePoint online inside my Azure function

john john 1,021 Reputation points
2023-02-16T00:20:44.72+00:00

I have an Azure Function which uses PnP.Core.Services to interact with SharePoint to create a list item. The Azure function is based on .net version 6.0 and i got it from this video @ https://www.youtube.com/watch?v=9erhWdwbkq8&t=543s.

I have this startup.cs:-

using Microsoft.Azure.Functions.Extensions.DependencyInjection;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using PnP.Core.Auth;
using System.Security.Cryptography.X509Certificates;

[assembly: FunctionsStartup(typeof(FunctionApp2.Startup))]
namespace FunctionApp2
{
    class Startup : FunctionsStartup
    {
        public override void Configure(IFunctionsHostBuilder builder)
        {

            var config = builder.GetContext().Configuration;
            var azureFunctionSettings = new AzureFunctionSettings();
            config.Bind(azureFunctionSettings);
            builder.Services.AddPnPCore(options =>
            {
                options.DisableTelemetry = true;
                var authProvider = new X509CertificateAuthenticationProvider(azureFunctionSettings.ClientId,
                    azureFunctionSettings.TenantId,
                    StoreName.My,
                    StoreLocation.CurrentUser,
                    azureFunctionSettings.CertificateThumbprint);
                options.DefaultAuthenticationProvider = authProvider;

                options.Sites.Add("Default", new PnP.Core.Services.Builder.Configuration.PnPCoreSiteOptions

                {
                    SiteUrl = azureFunctionSettings.SiteUrl,
                    AuthenticationProvider = authProvider


                });

            });

        }

    }
}

and this Function1.cs:-

using System;

using Microsoft.Azure.WebJobs;

using Microsoft.Azure.WebJobs.Host;

using Microsoft.Extensions.Logging;

using PnP.Core.Services;

using PnP.Core.Model.SharePoint;

using System.Collections.Generic;

namespace FunctionApp2

{
public class Function1

{
    private readonly IPnPContextFactory pnpContextFactory;
    public Function1(IPnPContextFactory pnpContextFactory)
    {
        this.pnpContextFactory = pnpContextFactory;

    }
    [FunctionName("Function1")]
    public void Run([TimerTrigger("0 */5 * * * *")] TimerInfo myTimer, ILogger log)
    {
        log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");

        using (var context = pnpContextFactory.Create("Default"))
        {
            var myList = context.Web.Lists.GetByTitle("SubFolders");
            Dictionary
Azure Functions
Azure Functions
An Azure service that provides an event-driven serverless compute platform.
5,911 questions
Microsoft 365 and Office SharePoint Development
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. RaytheonXie_MSFT 40,471 Reputation points Microsoft External Staff
    2023-02-16T06:14:08.2866667+00:00

    Hi @john john

    You can create a csomHelper.csx to reach access sharepoint online. Please refer to following code

    using Microsoft.IdentityModel.Clients.ActiveDirectory;
    using Microsoft.SharePoint.Client;
    using System.Security.Cryptography.X509Certificates;
     
    public static class csomHelper {
     
    private static string ClientId = "(Application ID)";
     private static string Cert = "(filename).pfx";
     private static string CertPassword = "(password)";
     private static string Authority = "https://login.windows.net/(tenantName).onmicrosoft.com/";
     private static string Resource = "https://(tenantName).sharepoint.com/";
     
    public async static Task<ClientContext> GetClientContext(string siteUrl)
     {
     var authenticationContext = new AuthenticationContext(Authority, false);
     
    var certPath = Path.Combine(Environment.GetEnvironmentVariable("HOME"), "site\\wwwroot\\&lt;FunctionName&gt;\\", Cert);
     var cert = new X509Certificate2(System.IO.File.ReadAllBytes(certPath),
     CertPassword,
     X509KeyStorageFlags.Exportable |
     X509KeyStorageFlags.MachineKeySet |
     X509KeyStorageFlags.PersistKeySet);
     
    var authenticationResult = await authenticationContext.AcquireTokenAsync(Resource, new ClientAssertionCertificate(ClientId, cert));
     var token = authenticationResult.AccessToken;
     
    var ctx = new ClientContext(siteUrl);
     ctx.ExecutingWebRequest += (s, e) =>
     {
     e.WebRequestExecutor.RequestHeaders["Authorization"] = "Bearer " + authenticationResult.AccessToken;
     };
     
    return ctx;
     }
    }
    
    

    Here is a nice article for you to reference

    https://bob1german.com/2017/06/24/az-func-csom/

    Note: Microsoft is providing this information as a convenience to you. The sites are not controlled by Microsoft. Microsoft cannot make any representations regarding the quality, safety, or suitability of any software or information found there. Please make sure that you completely understand the risk before retrieving any suggestions from the above link.


    If the answer is helpful, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.