Connect To SharePoint Online Site With App Only Authentication

Overview

SharePoint Online is a Software as a Service (SAAS) offering from Microsoft, available as part of Office 365. CSOM (Client Side Object Model) APIs are available for developers to connect to SharePoint Online sites. Using CSOM APIs, we can connect to SharePoint Online remotely and perform desired operations. There are various ways available to connect to SharePoint Online.

In this article, we will explore various options to connect to SharePoint Online. Pros and Cons of each option and mainly how we can connect SharePoint Online site with App Only Authentication.

Connect to SharePoint Online

In a nutshell, the below-managed C# code will help to connect to the SharePoint online site.

public void ConnectToSharePointOnline()
{
    string siteCollectionUrl = "https://tenant.sharepoint.com/";
    string userName = "[email protected]";
    string password = "XXXXXX";
    
    // Namespace: Microsoft.SharePoint.Client
    ClientContext ctx = new ClientContext(siteCollectionUrl);
    
    // Namespace: System.Security
    SecureString secureString = new SecureString();
    password.ToList().ForEach(secureString.AppendChar);
    
    // Namespace: Microsoft.SharePoint.Client
    ctx.Credentials = new SharePointOnlineCredentials(userName, secureString);
    
    // Namespace: Microsoft.SharePoint.Client
    Site site = ctx.Site;
    
    ctx.Load(site);
    ctx.ExecuteQuery();
    
    Console.WriteLine(site.Url.ToString());
}

The above code is fine as long as it is running on a developer’s machine. It is not production-ready, as the credentials are used in a plain text format.

Store credentials in a secure way

Let’s go one step further and store these credentials in a secure way.

The below PowerShell script will help to generate a secure password as an encrypted password.

$key = (3,4,2,3,56,34,254,222,1,1,2,23,42,54,33,233,1,34,2,7,6,5,35,43)

Write-Host "Type the password to encrypt: "
$secureString = Read-Host -AsSecureString
$securePassword = $secureString | ConvertFrom-SecureString -Key $key

We can use this encrypted password in our code or store it in a configuration file. The below PowerShell script will help to decrypt the password.

$key = (3,4,2,3,56,34,254,222,1,1,2,23,42,54,33,233,1,34,2,7,6,5,35,43)
$targetPassword = ConvertTo-SecureString $securePassword -Key $key

The decrypted password can be used to pass credentials to connect to SharePoint online.

In the future, there will be a situation when the password will expire and gets regenerated. It is the moment when our code will stop working.

App Only Authentication

App-Only is a model for setting up app principals. It can be used with SharePoint Online, as will SharePoint OnPremise (SharePoint 2013 / 2016 versions).

Setup app-only principal

Navigate to the SharePoint site (e.g. https://tenant.sharepoint.com)

Open apprehend.aspx page (https://tenant.sharepoint.com/_layouts/15/appregnew.aspx

Connect To SharePoint Online Site With App Only Authentication

  1. Click the “Generate” button against the Client ID row to generate a new client ID
  2. Click the “Generate” button against the Client secret row to generate a new client secret
  3. Type any Title, that describes your app's principal
  4. Type App domain as www.localhost.com
  5. Specify redirect URI as https://www.localhost.com
  6. Click Create
  7. Note down the Client ID and Client Secret for future references

Grant permissions to the newly created principal

The next step is to grant some permission to our created principal. Try to have the permission as granular as it can be. You may create as many numbers of app principals as you need with each app principal having unique permission.

Permission indicates the activity permitted to be performed within a requested scope. The permission can be any of the below:

  • Read
  • Write
  • Manage
  • FullControl

Along with permission, we can specify the scope. Below are a few examples of scope.

  • http://sharepoint/content/sitecollection
  • http://sharepoint/content/sitecollection/web
  • http://sharepoint/content/sitecollection/web/list
  • http://sharepoint/content/tenant

To give the writer access to a list, we can use the below code

<AppPermissionRequests>
    <AppPermissionRequest Scope="http://sharepoint/content/sitecollection/web/list" Right="Write"/>
</AppPermissionRequests>

Tenant Scoped Permissions

Tenant-scoped permissions can be only granted from the tenant administration site.

Open SharePoint Online Tenant site with Tenant Administrator account (https:// UNESCO-admin.sharepoint.com/_layouts/15/appinv.aspx)

Connect To SharePoint Online Site With App Only Authentication

  1. In the App ID textbox type your generated Client ID
  2. Click Lookup button
  3. In the Permission Request XML textbox type the below XML,
    <AppPermissionRequests AllowAppOnlyPolicy="true">
        <AppPermissionRequest Scope="http://sharepoint/content/tenant" Right="FullControl"/>
    </AppPermissionRequests>
    

Click Create button

In the next dialog click Trust It button,

Full trust

Consume App Only Principal in Code

Use a configuration file to store App ID and App Principals.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <appSettings>
    <!-- Use AppRegNew.aspx and AppInv.aspx to register client id with secret -->
    <add key="ClientId" value="[Your Client ID]" />
    <add key="ClientSecret" value="[Your Client Secret]" />
  </appSettings>
</configuration>

Office Dev PnP (Office Developer Patterns and Practices) has nuget available to help use app principals in managed C# code.

Use the below-managed C# code to connect to SharePoint

using OfficeDevPnP.Core;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Client;

string siteUrl = "https://tenant.sharepoint.com/sites/demo";
using (var cc = new AuthenticationManager().GetAppOnlyAuthenticatedContext(siteUrl, "[Your Client ID]", "[Your Client Secret]"))
{
    cc.Load(cc.Web, p => p.Title);
    cc.ExecuteQuery();
    Console.WriteLine(cc.Web.Title);
};

Advantages of using App Principals

  1. App principals can be consumed from any application (Console, Workflow, etc.)
  2. We do not need any user credentials to connect to SharePoint.
  3. Anyone can use app principals to perform activities specified in the scope of app principals.

Summary

App Only Authentication is a secure way to connect to SharePoint without any user dependency. OfficeDevPnP has a NuGet package ready to get started using App Only Authentication. It helps to authenticate with the App Only Policy instead of real user credentials.