DEV Community

Jaime López
Jaime López

Posted on • Originally published at intranetfromthetrenches.substack.com

A Guide to SharePoint Embedded Authentication with Examples

In this article, we will explore the practical applications of authentication in SharePoint Embedded development. By delving into the two authentication methods—app-only access and on-behalf-of-a-user—and demonstrating how to implement them effectively, we'll equip you with the knowledge and tools to harness the full potential of SharePoint Embedded. Whether you're a seasoned developer or a curious newcomer, this guide will provide you with the necessary insights to securely interact with SharePoint Embedded's rich feature set.

What is SharePoint Embedded by Intranet from the Trenches

SharePoint Embedded supports two primary authentication methods:

  1. App-only Access: This method is ideal for background processes and automation tasks that do not require user interaction. An application registered in Entra ID can obtain an access token and execute actions on behalf of the application itself.

  2. On-Behalf-of-a-User Access: This method enables applications to act on behalf of a specific user, leveraging their permissions to perform actions such as creating, editing, and deleting files. This approach is well-suited for rich, user-centric applications that require personalized experiences.

SharePoint Embedded Authorization Types by Intranet from the Trenches

To embark on your SharePoint Embedded development journey, you'll need to register an application in Entra ID and configure it with the necessary permissions. A detailed guide on this process can be found in the following article: Step-by-Step Guide: Configuring Container Types in SharePoint Embedded.

In the subsequent sections, we will explore practical examples of both app-only and on-behalf-of-a-user authentication, demonstrating how to leverage the Microsoft Graph API to retrieve container names.

A C# CLI Example

The application begins by reading configuration settings from a local JSON file. These settings are crucial for its authentication. They include information such as the tenant ID, client ID, client secret, and the specific container type ID to be queried.

{
    "entraId": {
        "tenantId": "",
        "clientId": "",
        "clientSecret": ""
    },
    "sharepoint-embedded": {
        "containerTypeId": ""
    }
}
Enter fullscreen mode Exit fullscreen mode

With the configuration in place, the application proceeds to authenticate. Upon successful authentication, Entra ID grants the application an access token, a temporary credential that allows it to make authorized requests to Microsoft Graph.

Armed with the access token, the application constructs a GET request to the Microsoft Graph API. The request is specifically targeted to the endpoint responsible for listing containers. The request includes a filter based on the container type ID obtained from the configuration. Once the API responds, the application parses the JSON response, extracting information about each container. Finally, it presents the extracted container details, including their IDs and display names, to the user.

using Azure.Core;
using Azure.Identity;
using System.Text.Json;
using Microsoft.Extensions.Configuration;
using System.Net.Http.Headers;


Console.WriteLine(">>> Reading configuration...");
var configuration = new ConfigurationBuilder().AddJsonFile(".\\configuration.json").Build();

var entraIdSection = new EntraIdConfigurationRetriever(configuration);
var speSection = new SPEConfigurationRetriever(configuration);  


Console.WriteLine(">>> Setting app-only credentials...");
var credential = null; // Each example shows how to develop it

Console.WriteLine(">>> Retrieving the access token...");
var scopes = new string[] {
    "https://graph.microsoft.com/.default"
};
var requestContext = new TokenRequestContext(scopes, null);
var accessToken = credential.GetToken(requestContext, new CancellationToken());


Console.WriteLine(">>> Requesting the list of containers...");
HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken.Token);
var response = await httpClient.GetAsync($"https://graph.microsoft.com/v1.0/storage/fileStorage/containers?$filter=containerTypeId eq {speSection.ContainerTypeId}");
var content = await response.Content.ReadAsStringAsync();


var containerResponse = JsonSerializer.Deserialize<ContainerResponseModel>(content);
foreach (var container in containerResponse.Containers) {
    Console.WriteLine($">>> Container: {container.Id} - {container.DisplayName}");
}
Enter fullscreen mode Exit fullscreen mode

Example 1: App-Only Access

App-only access in SharePoint Embedded involves obtaining an access token for the application itself, without a user's direct involvement. This is achieved by registering the application within the Entra ID tenant and assigning it necessary permissions. The application then requests an access token using its client ID and client secret, which are kept confidential. This token grants the application specific privileges to interact with Microsoft Graph API on behalf of the application itself.

While app-only access simplifies the authentication process and eliminates the need for user interaction, it comes with security considerations. Since the application acts independently, any compromise of the client secret could grant unauthorized access to sensitive data.

It's crucial to store and manage the client secret securely, using robust encryption and access control mechanisms. Additionally, carefully consider the permissions granted to the application, limiting them to the minimum required to perform its intended tasks. Regular review and updates of the application's permissions are recommended to maintain security best practices.

var credential = new ClientSecretCredential(
    entraIdSection.TenantId,
    entraIdSection.ClientId,
    entraIdSection.ClientSecret);
Enter fullscreen mode Exit fullscreen mode

This lines of C# code creates an instance of a ClientSecretCredential object. This object is used to authenticate your application with Entra ID and obtain access tokens to access other Microsoft services, such as Microsoft Graph.

Here's a breakdown of the parameters:

  • entraIdSection.TenantId: This is the ID of your Entra ID tenant, which is essentially your organization's unique identifier within Azure.
  • entraIdSection.ClientId: This is the application ID assigned to your registered application in Entra ID. It uniquely identifies your application within the tenant.
  • entraIdSection.ClientSecret: This is a secret key associated with your application. It's used to prove the identity of your application to Entra ID and obtain access tokens.

By providing these credentials, the ClientSecretCredential object can securely interact with Entra ID to acquire necessary tokens for your application to access Microsoft Graph and other services.

Example 2: On-Behalf-of-a-User Access

Delegated access in SharePoint Embedded involves obtaining an access token on behalf of a specific user, allowing the application to act with the user's permissions. This process typically involves a user's consent to grant the application access to their data. The application redirects the user to Entra ID's authorization endpoint, where they sign in and authorize the requested permissions. Upon successful authorization, Entra ID returns an authorization code to the application. The application then exchanges this code for an access token using its client ID and client secret.

While delegated access provides more granular control and enables access to user-specific data, it introduces additional security considerations. It's essential to implement robust consent mechanisms to ensure users understand the permissions being granted and can revoke them if necessary. Careful attention should be paid to the requested permissions, limiting them to the minimum required to fulfill the application's purpose. Additionally, consider implementing measures to protect user privacy, such as minimizing the amount of user data collected and stored. Regular security audits and updates to the application's security practices are crucial to address potential vulnerabilities and evolving threats.

var options = new InteractiveBrowserCredentialOptions();
options.TenantId = entraIdSection.TenantId;
options.ClientId = entraIdSection.ClientId;

var credential = new InteractiveBrowserCredential(options);
Enter fullscreen mode Exit fullscreen mode

This code snippet is used to create an InteractiveBrowserCredential object, which is a type of credential used for device code flow authentication. This flow is often used in scenarios where the application needs to authenticate a user interactively, typically through a web browser.

Here's a breakdown of the code:

  1. Creating InteractiveBrowserCredentialOptions:

    • An instance of InteractiveBrowserCredentialOptions is created. This object holds configuration settings for the device code flow.
    • The TenantId and ClientId properties are set to the respective values from the entraIdSection configuration. These values are essential for identifying the Entra ID tenant and the registered application.
  2. Creating InteractiveBrowserCredential:

    • An instance of InteractiveBrowserCredential is created, passing the options object as a parameter.
    • This credential object will be used to initiate the device code flow. When the application needs to authenticate a user, it will prompt the user to open a specific URL in their web browser. The user will then be redirected to a sign-in page where they can enter their credentials.
    • Once the user authenticates, the application can use the InteractiveBrowserCredential to obtain access tokens for making API calls to Microsoft Graph or other services.

In essence, this code sets up the necessary components for device code flow authentication, allowing the application to securely interact with Entra ID and obtain access tokens for authorized API calls.

Conclusion

Choosing the right access method, app-only or delegated, depends on the specific requirements of your SharePoint Embedded application. If your application needs to access user-specific data or perform actions on the user's behalf, delegated access is the appropriate choice. However, if your application requires minimal user interaction and only needs to access public or organization-wide data, app-only access might be sufficient.

Consider the sensitivity of the data being accessed and the level of user permissions required. Additionally, evaluate the application's functionality and whether it needs to adapt to different user contexts. By carefully assessing these factors, you can select the most suitable access method to ensure security, privacy, and optimal application performance.

References

Top comments (0)