SharePoint app-only principal to acess SharePoint Online

Introduction

Azure Access Control Service aka ACS is a cloud authentication service provided by MSFT and it offers ease of authentication and authorization for users to web applications and services. You don’t have to factor the code for authentication and authorization in your applications.

The idea here is client application communicates first with ACS and gets access token and using this access token it performs required actions at web application. This concept is based out of OAuth2.0 client credentials flow. More about this concept can be found from authorization systems in SharePoint addins in the references section. 

Token Based Authentication in SharePoint Online

The SharePoint App-Only authentication is still relevant for setting up app principals. App principal is the way of authenticating to applications without your username and password, but instead using Client ID and Client Secret, which the ACS gets these details and generates Access Token in return.

This ACS has been retired on November 7, 2018 but this retirement doesn’t impact development for SharePoint Add-ins. The Azure ACS app-only authentication is still supported for SharePoint online. Also, note that for the new tenants ACS app-only authentication is disabled by default. You can still work with Global Admin team to run the below command to support ACS app only authentication.

set-spotenant -DisableCustomAppAuthentication $false

Now let’s see the steps to set up the App Only authentication to connect to SharePoint online sites. This article is scoped to connect to Single SharePoint site collection only. If you want to connect to multiple SharePoint sites, then we can use Azure AD app set up which I will be discussing in my next article.

Pre-requisites

Below are the pre-requisites needed to have a successful walkthrough of the steps

  • Having Visual Studio 2019 or later versions installed
  • Site Collection Admin rights to SharePoint online site collection to create and configure Client ID and Client Secret.

Steps to set up Client ID and Client Secret

Step 1

Login to the SharePoint site, where you want to connect and append the URL with appregnew.aspx. for instance, the URL should look like below

https://yourdomain.sharepoint.com/sites/o365poc/_layouts/15/appregnew.aspx

Step 2

Generate client id and client secret by clicking on the ‘Generate’ buttons, and give the below details

  • Title: It can be anything. in this case, I am giving it as TokenBasedAuthentication_POC
  • App Domain: www.localhost.com (since we are not redirected, we can give this value)
  • Redirect URI: https://www.localhost.com (Since we are not directed to any page or application after authentication)

Step 3

On clicking on next, it should give the below screen. Copy these values in notepad for next step

Step 4

Now modify the URL to find the above app, by appending with /_layouts/15/appinv.aspx. it should look like below.

https://yourdomain.sharepoint.com/sites/o365poc/_layouts/15/appinv.aspx

in the resulting screen search by client ID that you just noted down and click ‘Lookup’.

You should see like below screen

Step 5

Now we will update the ‘App’s permission request XML’. This is an important step to tell this app what kind of rights does your client application need. Below is the format of the permission XML.

<AppPermissionRequests AllowAppOnlyPolicy="true">
    <AppPermissionRequest Scope="http://sharepoint/content/sitecollection" Right="FullControl" />
</AppPermissionRequests>

Also, note that below are the rights that you can define.

  • FullControl
  • Write
  • Read
  • Manage

After updating the matrix, click on ‘Create’ in the bottom right corner.

Step 6

Now you should be asked for consent. Click on ‘Trust It’.

The above steps finish up setting up Client ID and Client Secret to get ‘Full Control’ access to your client application to the SharePoint site.

Creating Client Application

Step 1

Open visual studio and create a blank console application project based on .Net Framework

Token Based Authentication in SharePoint Online

Step 2

Give some name for your project. Here I have given it as ‘TokenBasedAuthentication’

Step 3

You should be seeing something like below

Step 4

Now go to ‘Tools’ -> ‘Manage Nuget Packages for the solution’

Step 5

In the Nuget Packager console it is required to install the following packages

  • PnP.Framework
  • AppForSharePointOnlineWebToolKit

Token Based Authentication in SharePoint Online

You might get below confirmation screen, click ‘Ok’.

Step 6

Now you should see the Pnp.Framework under ‘Installed’ tab.

Token Based Authentication in SharePoint Online

Similarly, install the package "AppForSharePointOnlineWebToolkit"

Token Based Authentication in SharePoint Online

Step 7

After installing the required components, right-click on the solution and add 'Application Configuration File'.

Now update the app.config with the code pasted below. Make sure to replace client Id and Client Secret Values with your values that got generated from the client Id Client secret set up. 

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="ClientId" value="5b10e80f-4320-4a80-a2a4-451e919af3f9"/>
    <add key="ClientSecret" value="Av2HdsYtp4sEk6o0+PanQ9j0adm0FbwOmpz53jVck=43"/>
    <add key="SiteUrl" value="https://cts229051.sharepoint.com/sites/o365poc"/>
  </appSettings>
</configuration>

Step 8

 Click on program.cs and have the below code pasted.

Token Based Authentication in SharePoint Online

string siteUrl = ConfigurationManager.AppSettings["SiteUrl"];
string clientID = ConfigurationManager.AppSettings["ClientId"];
string clientSecret = ConfigurationManager.AppSettings["ClientSecret"];
using(ClientContext cc = new AuthenticationManager().GetACSAppOnlyContext(siteUrl, clientID, clientSecret)) {
    cc.Load(cc.Web, p => p.Title);
    cc.ExecuteQuery();
    Console.WriteLine(cc.Web.Title);
}

Step 9

Below is the screenshot of the complete code. Please make sure that the following classes/methods are referenced

  • Using PnP.Framework
  • Using System.Configuration
  • Using Microsoft.SharePoint.Client

Token Based Authentication in SharePoint Online

Step 10

Validate the output. Since I have requested for only Title, it is giving the tile of the SharePoint online site.

Token Based Authentication in SharePoint Online

Conclusion

Thus, in this article we have seen how to connect to SharePoint online and retrieve the properties, using App Only Authentication based on Azure Access Control Service (ACS).

References