Using CSOM with Azure Active Directory Apps

Hi,

Azure Active Directory Apps represent the new way of consuming Microsoft’s SaaS applications among which SharePoint Online. When it comes to the latter, it’s a little hard to see the added value of AAD Apps versus SharePoint Add-Ins. Admittedly, it’s not a revolution when it comes to SharePoint. However, from a broader perspective, this new technology represents a single coherent way to address Microsoft SaaS applications as a whole. It currently includes Yammer, SharePoint Online, Exchange Online, PowerBI, AAD, OneNote, Office 365 Unified API and Office 365 Management API.

So, with a single AAD App, you can cover a wide range of SaaS applications and the list will probably grow over time. Moreover, Microsoft didn’t reinvent the wheel, they’re just reusing OAUTH and OpenID. In a nutshell, it’s just a matter of getting an AccessToken to a given resource, that resource being one of the above listed SaaS applications.

Once you have the precious token in hand, you can start consuming the REST APIs endpoints. The great news is that for well known SaaS applications such as Yammer and SharePoint Online, you can target the exact same REST endpoints as before. The only difference is that you’ll get the token in a different manner.

In a nutshell, the token is quite easy to get, if you want to involve an end user, you’ll first need to request an Autorization Code, that is when the user signs in. Then, you’ll target the token endpoint to request an AccessToken and a Refresh token by redeeming the authorization code. The AccessToken you get is only valid for 1 hour and for the specific resource. You can’t reuse it for any other resource (meaning other Saas Applications). The RefreshToken however can be reused across resources. Another advantage of the RefreshToken lives in the fact that it remains usable during 90 days unless invalidated by a specific event such as the user got disabled in AAD, his password has changed etc…As long as the RefreshToken is valid, you can get fresh AccessTokens for any resource supported by AAD and you don’t need the end user to sign in again.

If you want to use App Only calls, meaning that no end user is involved in the process, it’s going to be a little harder in terms of configuration since you must create a certificate and export the public key into your Azure AD App. For more info on that, you can read the excellent blog post of Richard Dizerega http://blogs.msdn.com/b/richard_dizeregas_blog/archive/2015/05/03/performing-app-only-operations-on-sharepoint-online-through-azure-ad.aspx.

So, whatever method you use, in the end, you get a token. Regarding SharePoint Online, you can just reuse the CSOM to interact with SharePoint. Instead of using the SharePoint Online credentials, you’ll simply add the token to the request.

To do that, you can reuse the TokenHelper class that is present in any SharePoint Add-In project:

using (ClientContext ctx = TokenHelper.GetClientContextWithAccessToken("https://eyskens.sharepoint.com/", AccessToken))

and if you don’t want to bother with that guy, you can simply do the following:

 using (ClientContext ctx = new ClientContext("https://eyskens.sharepoint.com/"))

            {
                ctx.AuthenticationMode = ClientAuthenticationMode.Anonymous;
                ctx.FormDigestHandlingEnabled = false;
                ctx.ExecutingWebRequest +=
                    delegate(object oSender, WebRequestEventArgs webRequestEventArgs)
                    {
                        webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] =
                            "Bearer " + AccessToken;
                    };

                ctx.Load(ctx.Web.CurrentUser);
                ctx.ExecuteQuery();
                Console.WriteLine(ctx.Web.CurrentUser.LoginName);

            }

Where you simply add the Authorization HTTP Header with the typical “Bearer AccessToken value”. This code is extracted from the TokenHelper class by the way :).

Happy Coding!

About Stephane Eyskens

Office 365, Azure PaaS and SharePoint platform expert
This entry was posted in Azure Active Directory, Office 365, SharePoint Online and tagged , , . Bookmark the permalink.

3 Responses to Using CSOM with Azure Active Directory Apps

  1. Pingback: SharePointOnlineCredentials versus Azure Active Directory Apps versus ACS Apps | Stéphane Eyskens, Office 365 and Azure PaaS Architect

  2. mrtasci says:

    Hello, first of all thank you for this article.
    I get 401 while calling SPO endpoint by CSOM adding Graph API token to the request. How can I call SPO endpoint with same token? The code as below:

    ClientContext context = TokenHelper.GetClientContextWithAccessToken(“https://mycompany.sharepoint.com/sites/test1/”, _token);
    SharePoint.Client.List testList = context.Web.Lists.GetByTitle(“Test”);
    CamlQuery query = CamlQuery.CreateAllItemsQuery(100);
    ListItemCollection items = testList.GetItems(query);
    context.Load(items);
    context.ExecuteQuery(); //Fires 401 error

    Like

    • Stephane Eyskens says:

      Hi, the example you show is not what I explain in this post. I’m talking about AAD Apps, not about SharePoint Apps. In your case, the App needs to be registered into SharePoint since the TokenHelper class relies on SP, not on AAD.

      Like

Leave a comment