Consuming SharePoint CSOM from an Office 365 app

I’ve been a C# developer for more than five years now. When SharePoint 2013 was released, I started doing development for SharePoint 2013 and later also SharePoint Online. My focus was on developing web services (in combination with the SharePoint App model), native client and mobile applications using the Client Side Object Model.

When I was at the Barcelona TechEd conference in 2014, I decided to follow quite some breakout sessions about Office 365 and the “new” Office 365 APIs. It was around that time also that they released the new Office 365 Apps look and feel by means of the new “App Launcher” and the “My Apps” page.

clip_image002

Without having the knowledge about Apps for Office 365, I initially thought that these would be quite comparable to Apps for SharePoint. However, Apps for Office 365 are completely different.

Apps for Office 365

An app for Office 365 is conceptually:

  • An application that is running externally (i.e. on some website) or standalone (i.e. mobile or desktop). The application can be accessible from within the office 365 website, but also could be surfaced from within Word or Outlook.
  • Integrating somehow with Office 365 (this is not required).
  • Registered in the Azure Active Directory (AAD) that is running behind your Office 365 tenant.
  • Can use the same authentication mechanism as Office 365, resulting in single sign-on.

So before you can use your app in Office 365, you have to register it in Azure Active Directory. When registering you app in Azure AD, you also configure the permissions it gets to access the Office 365 services like mail, contacts, events and OneDrive for Business, but also SharePoint! Then I started thinking: “Does this mean that you can register an app in Azure AD and let it access SharePoint online?”.

clip_image004

Getting the access token

I was eager to discover whether it was possible to access SharePoint using the Client Side Object Model and the Azure Authentication mechanism. Jeremy Thake briefly mentioned in a blog post that it is possible to use the token you get from Azure as the Bearer token in you ClientContext requests.
So I created an ASP.NET MVC5 web application, registered it in Azure AD, set the permissions for Office 365 SharePoint Online (see above) and started experimenting.

You can get the access token as follows:

/// <summary>
/// Get the access token for the required resource
/// </summary>
/// <param name="clientID">The client ID of your app</param>
/// <param name="appKey">The app key</param>
/// <param name="resource">The resource you would like access to</param>
/// <returns></returns>
public static async Task<string> GetAccessToken(String clientID, String appKey, String resource)
{
    // Redeem the authorization code from the response for an access token and refresh token.
    ClaimsPrincipal principal = ClaimsPrincipal.Current;

    String authorizationUri = "https://login.windows.net";
    String nameIdentifier = principal.FindFirst(ClaimTypes.NameIdentifier).Value;
    String tenantId = principal.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;

    AuthenticationContext authContext = new AuthenticationContext(
        string.Format("{0}/{1}", authorizationUri, tenantId),
        new ADALTokenCache(nameIdentifier)
    );

    try
    {
        // Get the object identifier
        String objectId = principal.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;

        // Authenticate
        AuthenticationResult result = await authContext.AcquireTokenSilentAsync(
            resource,
            new ClientCredential(clientID, appKey),
            new UserIdentifier(objectId, UserIdentifierType.UniqueId)
        );

        return result.AccessToken;
    }
    catch (AdalException exception)
    {
        //handle token acquisition failure
        if (exception.ErrorCode == AdalError.FailedToAcquireTokenSilently)
        {
            authContext.TokenCache.Clear();
        }
    }

    return null;
}

You obtain the values for the ClientID and AppKey from the application page in Azure AD. You typically store the values for these properties in the configuration file of your application.

clip_image006

Now what is the Resource you have to supply? Well the resource is as follows:

So in order to access a SharePoint, you can get the access token as follows:

String clientID = ConfigurationManager.AppSettings["ida:ClientId"] ?? ConfigurationManager.AppSettings["ida:ClientID"];
String appKey = ConfigurationManager.AppSettings["ida:AppKey"] ?? ConfigurationManager.AppSettings["ida:Password"];
String spSiteUrl = "https://tenant.sharepoint.com";

String accessToken = await GetAccessToken(clientID, appKey, spSiteUrl)

Accessing a SharePoint Online Site

In order to be able to use this token for your ClientContext, you need to set the Authorization Header on each webrequest the clientcontext sends out:

ClientContext clientContext = new ClientContext(spSiteUrl);
clientContext.ExecutingWebRequest +=
    (sender, e) =>
    {
        e.WebRequestExecutor.WebRequest.Headers["Authorization"] = "Bearer " + accessToken;
    };

You can now access this site through the clientcontext you created (taking into account the permissions you’ve set in Azure AD). In case you do not have the permissions to access something through the clientcontext, you’ll typically get a UnauthorizedaccessException.

Research Tracker application

Jeremy Thake often refers to a cool Office 365 project that combines different application types to access the same data in your SharePoint site. You can find these projects on GitHub.
One of these projects uses the SharePoint REST API to access a SharePoint site, create lists, manage list items. I cloned this project and extended it to also include the functionality by means of CSOM. You can also find this project on GitHub.