Pieter van der Westhuizen

Office 365 API – Authentication & Setup

In our last article, we took a 10,000 foot view of what Office 365 has to offer. The article also made note of the Office 365 API, which enables developers to integrate with and use their users’ Office 365 data.

Before we can access the users’ data, we’ll need to authenticate our Office app and make sure it has the required permissions to access said data. This is accomplished by using single sign-on with Azure AD. The Office 365/Azure AD authentication uses OpenID Connect and OAuth 2.0, which is an open standard and if you’ve ever authenticated using either Facebook, Twitter or a Google account, the process of authenticating with Azure AD will be very familiar to you.

For the purpose of this article, we’ll only focus on authenticating using the new Office 365 Unified API. Although it is still only in preview, it will very shortly become the de facto method to access Office 365 data.

Creating the application in Azure AD

Before we can authenticate, we’ll need to create our application in Azure AD. To do this, sign into your Office 365 portal and click on the Admin icon on the home screen.

Sign into your Office 365 portal and click on the Admin icon on the home screen.

On the Office 365 admin center home page, scroll down to the bottom of the screen and click on the Azure AD link which is located under the ADMIN menu.

click on the Azure AD link which is located under the ADMIN menu.

This will take you to your Windows Azure AD management portal. Next, click on the Active Directory menu item on the left hand. This will list your active directory on the right.

Microsoft Azure Active Directory

Click on the arrow next to the name of your directory, which will open up more information about your Active Directory. Click on the APPLICATIONS link in order to show a list of applications set up for your Active Directory.

Click on APPLICATIONS to show a list of applications set up for your Active Directory.

This will display a list of applications that have already been setup for your organization. Depending on your Office 365 plan, you should already see Exchange Online and/or SharePoint Online in the list. If you’ve already created an application and are not seeing it in the list, simply change the Show dropdown list to Applications my company owns to update the list.

In order to create a new application, click on the ADD button at the bottom of the screen. This will start a short wizard that will help you create a new application. On the first step, select “Add an application my organization is developing”.

On the first step, select 'Add an application my organization is developing'.

On the next page, enter a name for you application and select whether it will be a Web/Web API application or a Native Client Application. If you’re going to develop a mobile or Windows desktop style app, select Native Client Application. If you’re building a website that integrates with Office 365 select Web Application and/or Web API.

We’ll build a Windows application for this example, so select NATIVE CLIENT APPLICATION.

If you're building a website that integrates with Office 365, select Web Application and/or Web API.

On the next page, enter the Redirect URI. This is the URI to which Azure AD will redirect to after an OAuth 2.0 request. It does not need to be a physical endpoint, but it would need to be a valid URI.

Enter the Redirect URI to which Azure AD will redirect to after an OAuth 2.0 request.

Complete the wizard by clicking on the Complete button. On the application page, click on the CONFIGURE menu item. This will take you to the configuration page for your application, where you can set various options for your application as well as the required permissions. It is also the page where we’ll get two of the most important values for our application: (a) the Client ID; and (b) Client Secret. The Client Secret is not required when creating a Native Client Application.

Set various options and required permissions for your application on the configuration page.

Copy the Client ID to a location where you can access it later and scroll down to the bottom of the page. Under the “permissions to other application” heading, click the “Add application” button.

Under 'permissions to other application', click the Add application button.

This will open a page where you can select which applications your application needs access to. Because we’ll be using the Unified API, click on the plus icon next to Office 365 unified API (preview) and click the check mark button to close this page.

If you are using the Unified API, click on the plus icon next to Office 365 unified API (preview).

Back on your applications’ page, you’ll see Office 365 unified API (preview) in the list of applications. Next to it, you’ll notice a dropdown list with all the available permissions. There are a host of permissions, enabling your app to read all the organization’s user profiles, manipulate site collections, read and write files, email, calendar and users.

For this example, we’ll only need access to the users’ profiles so select the following permissions:

  • Read and write access to user profile; and
  • Enable sign-in and read user profile.

Select the permissions to other applications

Once done, save your Office 365 application.

Save your new Office 365 application.

Creating the client application

It is important to understand that the Office 365 API can be used in almost all applications, even traditional COM/Managed Add-ins! So, for this example, we’ll create a simple Excel Managed Add-in that adds some of the users’ profile information into the currently selected cell.

For this task there is no better toolset than Add-in Express! So, we’ll fire up Visual Studio and create a new ADX COM Add-in.

Creating a new add-in for Office

Select your programming language (C#, VB.NET or C++.NET) and the minimum supported version of Office. The latest release of Add-in Express supports Microsoft Office 2016!

Select your programming language and the minimum supported version of Office.

For this example, we’ll only need to support Microsoft Excel.

Select the applications you want the add-in to support.

Once the “New Microsoft Office COM Add-in” wizard has completed, we’ll need to add a few Nuget packages to our project in order to easily access the Office 365 data. The first package we need is the Office 365 unified API client library (preview). To add a reference to this package, open the Package Manager console by selecting it from the Tools > NuGet Package Manager menu.

Type the following into the Package Manager console:

Install-Package Microsoft.Graph -Pre

This will add the required dependencies for the library as well as add a reference to Microsoft.Graph to your project.

Next, in order to facilitate the authentication, we’ll need to add the Active Directory Authentication Library NuGet package to our project by entering the following in the Package Manager console and hitting Enter:

Install-Package Microsoft.IdentityModel.Clients.ActiveDirectory -Version 2.16.204221202

With the required references added, let’s add a Ribbon Button with which we’ll authorize our app and retrieve some user information. Open the AddinModule designer surface and add a new ADXRibbonTab component to it. Design the Ribbon Tab to resemble the following image:

Design your custom ribbon tab.

Select the Ribbon Button and add an event handler for its OnClick event by double-clicking next to the OnClick event name in the properties windows’ events list.

Add an event handler for its OnClick event.

Add the following code to the button’s OnClick event handler:

private void adxGetProfileInfoRibbonButton_OnClick(object sender,
    IRibbonControl control, bool pressed)
{
    Excel.Range currSelection = null;
    try
    {
        var client = new GraphService(
            new Uri("https://graph.microsoft.com/beta/{tenant-id}"), GetUserToken);
        IUser user = client.Me.ExecuteAsync().Result;
        var name = user.displayName;
        currSelection = ExcelApp.Selection as Excel.Range;
        currSelection.Value2 = name;
    }
    finally
    {
        if (currSelection != null)
            Marshal.ReleaseComObject(currSelection);
    }
}

In the preceding code, we first created a reference to the active selection in the Excel sheet. We then initialized a new instance of the GraphService object, which took a parameter for the service root of the service you’re trying to call. Because we’re using the Office 365 Unified API, this was set to https://graph.microsoft.com/beta/[tenant-id], whereas [tenant-id] will be your Office 365 tenant name e.g. mycompany.onmicrosoft.com.

The second parameter is a method called GetUserToken that will return the OAuth token to use for the service calls. The code for this method follows below:

private Task<string> GetUserToken()
{
    var authContext = new AuthenticationContext(
        "https://login.microsoftonline.com/common", false);
    var authResult = authContext.AcquireToken(
        "https://graph.microsoft.com",
        "98651301-70ac-481f-9a3b-4a2ade1e3132",
        new Uri("https://myapp"),
        PromptBehavior.Auto);
 
    var userToken = authResult.AccessToken;
    return Task.FromResult(userToken);
}

In the GetUserToken method, we created a new instance of the AuthenticationContext object and called its AcquireToken method. This method’s first parameter is the resource URI what we’re trying to access, when accessing the Unified API this should be https://graph.microsoft.com. The second parameter is the Client ID of the application we created in Azure AD. The third parameter should be a URI you’ve specified in the list of Redirect URI’s when you created the application.

Lastly, we used the GraphService client to return a new instance of the logged in user as an IUser interface. We then simply set the current selection in Excel’s value to the Display name of the current user.

Accessing Office 365 data in Excel add-ins

With the necessary code in place, it’s time to test! Build, register and run your project, and when Excel starts up, you should see an Office 365 Tab.

An Office 365 Tab in Excel.

Make sure you have a cell selected and click on the “Get Profile Info” button. This will open an Office 365 sign-in window. Enter your Office 365 username and password and click Sign In.

Sign in to your Office 365 application.

If you’re signing in with a different account that is associated with a different Azure AD organization than the one that the application was setup in, a list of permissions required by the application will be displayed with a request to allow the Office 365 application access to your information or not.

Allow the Office 365 application access to your information or not

After clicking Accept, you should see your Office 365 user’s Display name in the selected Excel cell.

After clicking the Accept button, you will see your Office 365 user's Display name in the selected Excel cell.

In the upcoming articles, we’ll dive deeper into the Office 365 API and see how to access different types of Office 365 data.

Until then, thank you for reading and keep coding!

Available downloads:

This sample Outlook Add-in was developed using Add-in Express for Office and .net:

Office 365 Authentication sample

10 Comments

  • Nico says:

    Pieter, Thank you again for this post, but I have a question to get it work ;o)
    Regarding the Valid URI when you add the application:
    What can I do (or need to do) in my Office365 Development account to have such a URI?

    I found some extra info here:
    https://msdn.microsoft.com/en-us/library/dn132633.aspx#BKMK_AppObject

    “the value of the App ID URI of the app must be an address in one of your directory’s verified domains. As a result, it cannot be a URN. This safeguard prevents other organizations from specifying (and taking) unique property that belongs to your organization. During development, you can change your App ID URI to a location in your organization’s initial domain (if you haven’t verified a custom/vanity domain), and update your app to use this new value. The initial domain is the 3-level domain that you create during sign up, such as contoso.onmicrosoft.com.”

    I’m just started with my Office365 developer account and coming from VBA and Com-Addins (with Add-In Express off course!), but your posts are really, really helpfull.
    All links very welcome regarding this topic!

    Many Thx!
    Nico

  • Pieter van der Westhuizen says:

    Hi Nico,

    The APP ID URI, should be contain one of the domains you have registered on your Office 365 tenant.

    To see what the domain are, sign into you Office 365 admin account(https://portal.office.com) and click on DOMAINS. On the list you should see a list of domains associated with your Office 365 account.

    When you sign up you get a domain name that looks something like this : yourcompany.onmicrosoft.com

    The APP ID URI, shoud work with something like :yourcompany.onmicrosoft.com/myApp

    After you’ve associated a custom domain with your Office 365 account e.g. mycompany.com you can have an APP ID URI like myapp.mycompany.com

    Hope this makes sense!

  • Nico says:

    Pieter,

    Thank you for the extra info, it works now! I’m looking forward to more articles!

    The following can be interesting to other readers ;o) If someone else was blocked by installing the ‘Office 365 unified API client library (preview)’

    It did not work with:

    Install-Package Microsoft.Graph –P

    this worked on my side:

    Install-Package Microsoft.Graph –Pre

    I have not that much experience with Nuget, so this will probably be obvious for more experienced users.

    Best regards,
    Nico

  • Pieter van der Westhuizen says:

    Hi Nico,

    Great! Happy that you got it working. It should be Install-Package Microsoft.Graph –Pre

    Looks like our blog’s formatting did not show the -Pre bit.

    Thanks for letting us know!

  • Tavi Truman says:

    FYI – there have been a number of updates and this code no longer works. I’ll submit working code in just a bit.

    Tavi

  • Dmitry Kostochko (Add-in Express Team) says:

    Hi Tavi,

    Thank you in advance!

  • Tavi Truman says:

    Hey guys where should I upload working code fixes to examples?

    Tavi

  • Dmitry Kostochko (Add-in Express Team) says:

    Hi Tavi,

    Could you please send the fixes to our support email address? You can find it in the readme.txt file located in Add-in Express installation folder.

    Alternatively, you can use the Contact Add-in Express support service online feedback form.

  • jyothi says:

    Hi,

    I am facing issue with dependents of add-in express when creating the installer with this add-in express we are using add-in express 9.0.4160.0″, could you please help us in ASAP.

    thanks in advance!..

  • Andrei Smolin (Add-in Express Team) says:

    Hello jyothi,

    Please provide details to the support email address. You can use the contact form at https://www.add-in-express.com/support/askus.php.

Post a comment

Have any questions? Ask us right now!