Connect To SharePoint Online Site With App Only Authentication

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.

Overview 

 
SharePoint Online is 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 SharePoint online site. 
  1. public void ConnectToSharePointOnline()    
  2. {    
  3.     string siteCollectionUrl = "https://tenant.sharepoint.com/";    
  4.     string userName = "user@companyname.onmicrosoft.com";    
  5.     string password = "XXXXXX";    
  6.     
  7.     // Namespace: Microsoft.SharePoint.Client    
  8.     ClientContext ctx = new ClientContext(siteCollectionUrl);   
  9.     
  10.     // Namespace: System.Security  
  11.     SecureString secureString = new SecureString();     
  12.     password.ToList().ForEach(secureString.AppendChar);    
  13.     
  14.     // Namespace: Microsoft.SharePoint.Client    
  15.     ctx.Credentials = new SharePointOnlineCredentials(userName, secureString);   
  16.     
  17.     // Namespace: Microsoft.SharePoint.Client    
  18.     Site site = ctx.Site;   
  19.     
  20.     ctx.Load(site);    
  21.     ctx.ExecuteQuery();    
  22.     
  23.     Console.WriteLine(site.Url.ToString());    
  24. }  
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 as a plain text format.
 

Store credentials in a secure way

 
Let’s go one step further and store these credentials in a secure way.
 
Below PowerShell script will help to generate secure password as an encrypted password.
  1. $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)  
  2.   
  3. Write-Host "Type the password to encrypt: "  
  4. $secureString = Read-Host -AsSecureString  
  5. $securePassowrd = $secureString | ConvertFrom-SecureString -Key $key  
We can use this encrypted password in our code or store in configuration file. The below PowerShell script will help to decrypt the password.
  1. $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)  
  2. $targetPassword = ConvertTo-SecureString $securePassword -Key $key  
The decrypted password can be used to pass to 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
  1. Navigate to SharePoint site (e.g. https://tenant.sharepoint.com)
  2. Open appregnew.aspx page (https://tenant.sharepoint.com/_layouts/15/appregnew.aspx)

    Connect To SharePoint Online Site With App Only Authentication
  3. Click “Generate” button against Client Id row to generate a new client id
  4. Click “Generate” button against Client secret row to generate a new client secret
  5. Type any Title, which describes your app principal
  6. Type App domain as www.localhost.com
  7. Specify redirect URI as https://www.localhost.com
  8. Click Create
  9. 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 perform 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 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 write access on a list, we can use the below code
  1. <AppPermissionRequests>  
  2.       <AppPermissionRequest Scope="http://sharepoint/content/sitecollection/web/list" Right="Write"/>  
  3. </AppPermissionRequests>  

Tenant Scoped Permissions

 
Tenant scoped permissions can be only granted from tenant administration site.
  1.  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

  2. In the App Id textbox type your generated Client Id
  3. Click Lookup button
  4. In the Permission Request XML textbox type below xml,
    1. <AppPermissionRequests AllowAppOnlyPolicy="true">    
    2.     <AppPermissionRequest Scope="http://sharepoint/content/tenant" Right="FullControl" />    
    3. </AppPermissionRequests>    
  5. Click Create button
  6. In the next dialog click Trust It button,
    Connect To SharePoint Online Site With App Only Authentication 

Consume App Only Principal in Code

 
Use configuration file to store App Id and App Principals.
  1. <?xml version="1.0" encoding="utf-8" ?>  
  2. <configuration>  
  3.   <appSettings>  
  4.     <!-- Use AppRegNew.aspx and AppInv.aspx to register client id with secret -->  
  5.     <add key="ClientId" value="[Your Client ID]" />  
  6.     <add key="ClientSecret" value="[Your Client Secret]" />  
  7.   </appSettings>  
  8. </configuration>  
Office Dev PnP (Office Developer Patterns and Practices) have nuget package available to help use app principals in managed C# code.
 
Use below managed C# code to connect to SharePoint 
  1. using OfficeDevPnP.Core;
  2. using Microsoft.SharePoint;
  3. using Microsoft.SharePoint.Client;

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

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 principal.

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 App Only Policy instead of real user credentials.