Authenticate SharePoint Using Pnp.Framework In An Azure Functions

Introduction

In this article, you will learn how to authenticate SharePoint online and get a context in Azure functions using PnP.Framework.

Steps

  1. Create an Azure function
  2. Add PnP.framework and Microsoft.SharePointOnline.CSOM package
  3. Use AuthenticationManager class to authenticate SharePoint.
  4. Publish the Azure functions in Azure Portal ( Need to have an active Azure subscription)
  5. Test the function

Create an Azure function

Step 1

Login to Visual Studio 2019 and Create a new Project.

Step 2

Select the Azure functions and click on Next.

Authenticate SharePoint using Pnp.Framework in an Azure Functions

Step 3

Provide the name and click on Create.

Authenticate SharePoint using Pnp.Framework in an Azure Functions

Step 4

Select the Azure functions v3(.NET Core),  select HTTP trigger and select Anonyms and click on Create.

Authenticate SharePoint using Pnp.Framework in an Azure Functions

Install NuGet Package

Select solution and right-click on dependencies and NuGet Process.

Install the packages,

  1. Microsoft.SharePoint online.CSOM
  2. PnP.Framework

Authenticate SharePoint using Pnp.Framework in an Azure Functions

Add AuthenticationManager

This AuthenticationManager is from PnP, the framework which helps to get token and provide the context of the SharePoint.

Copy-paste the below code in the Function,

using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Microsoft.SharePoint.Client;
using PnP.Framework;
using System.Security;

namespace Demo_Function
{
    public static class Function1
    {
        [FunctionName("Function1")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            Web currentWeb;
            string userLogin = "sp@sp1226.onmicrosoft.com";  //enter your account
            string userPassword = "*****";  //enter your password for account
            string sharePointUrl = "https://sp1226.sharepoint.com/sites/portal";  // enter your site URL here

            var securePassword = new SecureString();
            foreach (char c in userPassword)
            {
                securePassword.AppendChar(c);
            }

            AuthenticationManager auth = new AuthenticationManager(userLogin, securePassword);

            using (ClientContext ctx = await auth.GetContextAsync(sharePointUrl))
            {
                currentWeb = ctx.Web;
                ctx.Load(currentWeb);
                await ctx.ExecuteQueryRetryAsync();
            }

            log.LogInformation($"Web's title : {currentWeb.Title}");
            var myObj = new { Title = currentWeb.Title, Descr = currentWeb.Description };


            //   return new HttpResponse($"Web's title : {currentWeb.Title}" );
            return new JsonResult(myObj);

        }
    }
}

Publish the Azure function

Step 1

Build the project and then Right-click on the project to click on Publish,

Authenticate SharePoint using Pnp.Framework in an Azure Functions

Step 2

Select Target as Azure and click on Next,

Authenticate SharePoint using Pnp.Framework in an Azure Functions

Step 3

Select Azure function app (Windows) and click on Next.

Authenticate SharePoint using Pnp.Framework in an Azure Functions

Step 4

Create a new Azure Function as shown in the image,

Authenticate SharePoint using Pnp.Framework in an Azure Functions

Step 5

Provide the name of functionApp, Resource Group, and other fields and click on Create.

Authenticate SharePoint using Pnp.Framework in an Azure Functions

Step 6

After that click on the Finish button as you will see your new Function App.

Authenticate SharePoint using Pnp.Framework in an Azure Functions

Step 7

Now click on Publish so that this Function app will be deployed to the Azure Portal.

Authenticate SharePoint using Pnp.Framework in an Azure Functions

Test the Azure function

You can now see the function app deployed to your Azure resource.

Step 1

Navigate to the Azure portal using portal.azure.com and see the function app.

Authenticate SharePoint using Pnp.Framework in an Azure Functions

Step 2

Click on the functions and get the function URL for Function1 and paste in the browser to check the output.

Authenticate SharePoint using Pnp.Framework in an Azure Functions

Step 3

After browsing the Function URL in the browser you can see the results.

Authenticate SharePoint using Pnp.Framework in an Azure Functions

As we are getting the site title and description from the Function app in our code same is returned back from the URL.

Conclusion

In this way, we can authenticate the SharePoint using the user name and password in the .Net core projects. In this way, we don’t have to use the token helper class as a token is obtained from the AuthenticationManager class in the backend. So we only have to write our SharePoint logic.

We can also use the Azure AD app-only method to authenticate the SharePoint where we can use ClientId and certificate to authenticate and hence don’t need to have to use the credentials.

Note
In this, I have used credentials in the code itself but you might need to fetch it from the Azure Key vault in actual development scenarios.

Hope you find it helpful.