Integrate Office 365 APIs using Common Consent Framework

Learn how to create a web server app hosted on a Azure Web Site that integrates Microsoft Azure Active Directory and the new Common Consent Framework integration for Office 365.

Last modified: June 18, 2014

Applies to: Office 365

Prerelease content Prerelease content

The features and APIs documented in this article are in preview and are subject to change. Do not use them in production.

Your feedback about these features and APIs is important. Let us know what you think. Have questions? Connect with us on StackOverflow. Tag your questions with [ms-office].

The following are required to complete this walkthrough:

An Office 365 account

Microsoft Azure Account (associated with Office 365)

Visual Studio 2013

This walkthrough shows how to add sign-on functionality to an ASP.NET application using Microsoft Azure Active Directory (Microsoft Azure AD) and how to access Office 365 data using the new Common Consent Framework.

When you create an Office 365 tenancy, you also get a connected instance of a Microsoft Azure tenant with Microsoft Azure AD as part of your subscription. You can use the existing Microsoft Azure tenant to create a web application, and manage organizational user accounts through the default directory. This allows you to set up single sign-on using the directory as the Identity Provider (IdP) for your web application.

In a typical single sign-on scenario, there are three entities involved. The web application, the resource you are trying to access, and the IdP.

For more information about single sign-on, see Adding Sign-On to Your Web Application Using Windows Azure AD.

Figure 1 shows the flow of authentication between the web server app, Microsoft Azure AD and SkyDrive Pro resources.

Figure 1. Common Consent Authentication Flow

Common Consent Web Server App Authentication Flow

For a complete description of the steps included in Figure 1, see Authenticate your app.

The web page you are creating is hosted inside a Microsoft Azureweb site.

As mentioned before, this app uses Microsoft OneDrive for Business to demonstrate how to access secured Office 365 resources from an app outside of SharePoint. Microsoft OneDrive for Businessis for file and document storage in the cloud.

Architecturally, a Microsoft OneDrive for Business folder collection is simply a SharePoint document library. To access a user’s folders and files, you can use the SharePoint APIs through the client-side object model (CSOM) or Representational State Transfer (REST) URLs just as you would with any normal document library.

For more information about how to construct URLs to access resources, see the following:

Note Note

It is possible to access Microsoft OneDrive for Business resources today using SharePoint 2013, but the app must contain the login credentials in the app manifest and make a request to the Microsoft Azure Access Control Service (ACS). For more information, see Access OneDrive for Business using the SharePoint 2013 APIs.

You don’t have to create a separate Microsoft Azuretenant from your Office 365 tenant since, when you create the tenancy, a Microsoft Azuretenant is created underneath your Office 365 tenant. In order to ease app development, you can create a subscription to the underlying Microsoft Azuretenant inside your Office 365 admin portal.

You will need an Office 365 tenancy to begin. If you don't already have an Office 365 subscription, you can follow the steps in this article to get one: Sign up for an Office 365 Developer Site.

To create the Microsoft Azure subscription to your Office 365 tenant

  1. As shown in Figure 1, log in to your Office 365 tenant and go to the Office 365 admin center.

    Figure 1. Log into Office 365 tenant

    Common Consent Walkthrough Tenant LogIn
  2. In the same browser, open a new tab and go to Sign in to Microsoft Azure. This allows you to log in with your Office 365 credentials.

    Figure 2. Add subscription for Microsoft Azure

    Common consent tenant subcription
  3. Once your subscription is created, choose Portal.

    Figure 3. – Go to Microsoft Azure portal.

    Common Consent integration walkthrough - subscribe
  4. The Microsoft AzureTour appears. You can view it, or choose X to close it.

    Figure 4. Microsoft Azure Tour

    Microsoft Azure Tour
  5. You now see all items in the Microsoft Azuretenant. It lists a single directory with the name of your Office 365 tenant.

    Figure 5.All tenant items

    All items in tenancy

You won’t be able to use Microsoft accounts (or other account types) when running the web app using SSO. SSO will only work with organizational accounts. An organizational account is a user account managed in your Active Directory. It will have your company’s domain in the account name (or the default Microsoft Azuredomain such as if you don’t have a domain yet).

Therefore you need a test account that you can log on with to test your app.

To create an organizational user account

  1. Choose the Active Directory icon on the left side in the Microsoft Azure portal. An example of the default directory (renamed to) appears below.

    Figure 6 New directory is ready to use

    Active Directory ready to use
  2. Choose Add a user.

  3. In the dialog box, enter test for the user name. Verify that the user type is a new user in your organization.

    Figure 7. Add a new user to the directory

    Add a new user to the directory
  4. Choose the right arrow to move to the next screen.

  5. Enter the details for the user profile

    To create a user profile

    1. Enter a first name of Test, and last name of Tester.

    2. Enter a display name of Test Tester.

    3. Set the Role to Global Administrator.

    4. After you set the role you will be asked for an alternate email address. You can enter the email address that you used to create the subscription, or a different one.

    Figure 8. Set user role

    Set user role
  6. Choose the right-arrow to move to the next screen.

  7. On the Add user screen, choose create.

    Get temporary password

    Get temporary password
  8. The temporary password is generated. Record this somewhere so you do not lose it. Later, you will sign in and change it.

    Figure 9. Temporary password created

    Temporary password created
  9. Choose the check mark to complete creating the user.

The next step is to create the actual app that contains the user interface and code needed to work with the Microsoft OneDrive for Business REST APIs to list the folders and files in the user’s OneDrive. In this section, you create the skeleton project and wire it up to the Microsoft Azuretenant so that you can log on through SSO.

To create the Visual Studio project

  1. Open Visual Studio 2013 and create a new ASP.NET Web Application project. Name the application Get_Stats.

    Figure 10. Create new Visual Studio project

    Create a new VS project
  2. Choose OK. This displays the templates available with an ASP.NET Web Application.

    Figure 11. Choose MVC template

    Choose the MVC template
  3. Choose the MVC template and choose the Change Authentication button. Select the Organization Accounts option. This will display additional options for authentication.

  4. Choose Cloud – Single Organization.

  5. Specify the domain of your Microsoft AzureAD tenancy.

  6. Set the Access Level to Single Sign On, Read directory data.

    Under More Options, you will see the App ID URI is set automatically.

  7. Choose OK to continue. This brings up a dialog box to authenticate.

    Note Note

    If you receive an invalid domain name error you may need to implement a workaround by substituting a real domain name such as * from another Microsoft Azure subscription you have. When you complete the Visual Studio new project dialog box, Visual Studio creates a temporary app registration entry on the domain that you specify. You can delete that entry later.

    As part of the workaround you need to adjust the web.config settings and manually register the web app in the correct Microsoft Azure AD domain.

  8. Enter the credentials of the user you created earlier.

  9. Choose OK, to complete creating the new project. Visual Studio will automatically register the new web app in the Microsoft AzureAD tenant you specified.

    Note Note

    If you are registering the app manually, Visual Studio will register the web app in the domain you specified, but not the TAP domain you were provided. Register it manually by following steps in the next section.

    Skip the next step and proceed to the workaround in the next section.

  10. Run the Visual Studio project. It prompts you to sign on. Sign on using the test account you created earlier. Once the project is running, you can verify that Single-sign is working by seeing the test account user name displayed in the upper right corner of the web app.

For TAP customers, following the workaround for substituting an alternate domain for the organizational account authorization, then Visual Studio did not register your web app in the TAP domain provided to you.

To register your web app manually

  1. If you are not already logged in to your Microsoft Azure account, log in.

  2. Choose Active Directory on the left side. You see one active directory listed (for example ImGeeky).

  3. Choose your directory (in this example ImGeeky).

  4. Choose Applications (on the top nav).

  5. Choose Applications on the Active Directory tab.

  6. Add a new application in your Office 365 domain (created at Office 365 sign up) by choosing the "ADD" icon at the bottom of the portal screen. This will bring up a dialog box to tell Microsoft Azureabout your application.

  7. Choose Add an application my organization is developing.

  8. Enter Get Stats as the name of the application. Leave the Type as Web application and/or Web API. Then choose the arrow to move to step 2.

  9. For the Sign-On URL enter the localhost URL from your Get_Stats Visual Studio project. You can find the URL using the following steps.

    1. Open your project in Visual Studio.

    2. Choose the Get_Status project in the Solution Explorer.

    3. Copy the SSL URL value from the Properties window.

    4. Enter an App ID URI. The ID must be unique so it is a good idea to choose a name that is close the app name. For example your Sign-on URL plus app name (https://locahost:44044/Get_Stats.)

    5. Choose the checkmark to complete adding the application. You get a notification that the application has been added successfully

The next steps are necessary to configure your app to communicate with Microsoft Azure AD.

To configure the GL_Stats project

  1. Copy the APP ID URI to the clipboard.

  2. In your Get_Stats Visual Studio project, open the web.config file.

  3. Locate the ida:Realm key and paste the APP ID URI for the value.

  4. Locate the ida:AudienceUri key and paste the same APP ID URI for the value.

  5. Locate the audienceUris element and paste the same APP ID URI for the add element’s value.

  6. Locate the wsFederation element, and paste the same APP ID URI for the realm.

  7. In the Microsoft AzurePortal, copy the federation metadata document URL to the clipboard.

  8. In the web.config file, locate the ida:FederationMetadataLocation key, and paste the URL for the value.

  9. In the Microsoft Azure Portal, choose the View Endpoints icon at the bottom.

  10. Copy the WS-Federation Sign-On Endpoint to the clipboard.

  11. In the web.config file, locate the wsFederation element and paste the endpoint value for the issuer.

  12. Save your changes and run the project. You will be prompted to sign on. Sign on using the test account you created earlier. When the project runs you can verify that single-sign on is working by seeing your test account user name displayed in the upper right corner of the web app. 

Next, you need to generate a key that you can use to identify your application for access tokens.

To get an application key for your app

  1. In the Microsoft Azure Portal, select the Get_Stats application in the directory.

  2. Choose the Configure command and then locate the keys section.

  3. In the Select duration drop down box, choose 1 year. 

  4. Choose the Save icon at the bottom.

  5. The key value is displayed, and this is the only time it will be displayed. Copy it to the clipboard, or write it down.

  6. In Visual Studio, open the Get_Stats project, and open the web.config file.

  7. Locate the ida:Password element, and paste the key value for the value. Now your project will always send the correct password when it is requested.

  8. Save all files.

You need to specify which web APIs your web app needs access to, and what level of access it needs. This determines what scopes and permissions are request on the consent form for your web app that is displayed for users and admins.

To configure API permissions

  1. In the Microsoft Azure Portal, select the Get Status application in the directory.

  2. Choose Configure from the top nav. This displays all the configuration properties.

  3. At the bottom is a web apis section. Notice that your web app has already been granted access to Microsoft AzureAD.

  4. Choose the Office365 SharePoint Online API.

  5. Choose Delegated Permissions and select Read items in all site collections.

    Note Note

    The options activate when you move over them.

  6. Choose the Save icon at the bottom to save these changes. Your web app will now request these permissions.

    You can also manage permissions by using a manifest. You can download your manifest file by choosing Manage Manifest at the bottom.

The easiest way to call graph APIs in Microsoft Azure AD is to use the Graph API Helper Library. You can download this from the Microsoft Download Center. The following instructions show how to set up the Graph API Helper Library for the Get_Stats solution.

To configure the Graph API Helper Library

  1. Download the Windows Azure AD Graph API Helper Library (

  2. Copy the C# folder from the Graph API Helper Library to your project folder (i.e. \Projects\Get_Stats\C#.)

  3. Open the Get_Stats solution in Visual Studio.

  4. In the Solution Explorer, choose the Get-Stats solution and choose Add Existing Project.

  5. Go to the C# folder you copied, and open the WindowsAzure.AD.Graph.2013_04_05 folder.

  6. Select the Microsoft.WindowsAzure.ActiveDirectory.GraphHelper project and choose Open.

  7. If you are prompted with a security warning about adding the project, choose OK to indicate that you trust the project.

  8. Choose the Get_Stats project References folder and then choose Add Reference.

  9. In the Reference Manager dialog box, select Extensions and then select Microsoft.Data.OData version assembly and the Microsoft.Data.Services.Client version assembly.

  10. In the same Reference Manager dialog box, expand the Solution menu on the left, then select the checkbox for the Microsoft.WindowsAzure.ActiveDirectory.GraphHelper.

  11. Choose OK, to add the references to your project.

  12. Add the following using directives to the top of HomeController.cs

    using Microsoft.WindowsAzure.ActiveDirectory;
    using Microsoft.WindowsAzure.ActiveDirectory.GraphHelper;
    using System.Data.Services.Client;
  13. Save all files.

Since your web app accesses multiple workloads (Microsoft Azure AD, and SharePoint Online) you need to write some code to obtain tokens. It’s best to place this code in some helper methods that can be called when needed. Your code handles the following scenarios:

  • Obtaining an authentication code

  • Using the authentication code to obtain an access token, and multi-resource refresh token

  • Using the multi-resource refresh token to obtain a new access token for a new workload

To create code to handle the previous scenarios

  1. Open your Visual Studio project for [Get_Stats].

  2. Open the HomeController.cs file.

  3. Create a new method named Stats using the following code.

    public ActionResult Stats()
        var authorizationEndpoint = ""; // The oauth2 endpoint.
        var resource = ""; // Request access to the AD graph resource.
        var redirectURI = ""; // The URL where the authorization code is sent on redirect.
        // Create a request for an authorization code.
        string authorizationUrl = string.Format("{1}common/oauth2/authorize?&response_type=code&client_id={2}&resource={3}&redirect_uri={4}",
  4. The [Stats] method constructs a request for an authorization code and sends the request to the Oauth2 endpoint. If successful, the redirect returns to the specified CatchCode URL. Next, create a method to handle the redirect to CatchCode.

    public ActionResult CatchCode(string code)
  5. Acquire the access token by using the app credentials and the authorization code. Use your project’s correct port number in the code below.

    //  Replace the following port with the correct port number from your own project
        var appRedirect = "https://localhost:44307/Home/CatchCode";
    //  Create an authentication context
        AuthenticationContext ac = new AuthenticationContext(string.Format("{0}",
    //  Create a client credential based on the application id and secret.
    ClientCredential clcred = new ClientCredential(AppPrincipalId, AppKey);
    //  Using the authorization code acquire an access token.
        var arAD = ac.AcquireTokenByAuthorizationCode(code, new Uri(appRedirect), clcred);
  6. Next use the access token to call the Graph API and get the list of users for the Office 365 tenant. Paste in the code below.

    //  Convert token to the ADToken so we can use it in the graphhelper project.
        AADJWTToken token = new AADJWTToken();
        token.AccessToken = arAD.AccessToken; 
    //  Initialize a graphService instance using the token acquired from previous step
        Microsoft.WindowsAzure.ActiveDirectory.DirectoryDataService graphService = new DirectoryDataService("09f9ea02-9be8-4597-86b9-32935a17723e", token);
        graphService.BaseUri = new Uri("");
    //  Get the list of all users
        var users = graphService.users;
        QueryOperationResponse<Microsoft.WindowsAzure.ActiveDirectory.User> response;
        response = users.Execute() as QueryOperationResponse<Microsoft.WindowsAzure.ActiveDirectory.User>;
        List<Microsoft.WindowsAzure.ActiveDirectory.User> userList = response.ToList();
        ViewBag.userList = userList; 
  7. Now you need to call Microsoft OneDrive for Business, and this requires a new access token. Verify that the current token is a multi-resource refresh token, and then use it to obtain a new token. Paste in the following code.

    //  We need a new access token for new workload. Check to see if we have the MRRT.
        if (arAD.IsMultipleResourceRefreshToken)
            // This is an MRRT so use it to request an access token for SharePoint
            AuthenticationResult arSP = ac.AcquireTokenByRefreshToken(arAD.RefreshToken, AppPrincipalId, clcred, "");
  8. Finally, call Microsoft OneDrive for Business to get a list of files in the Shared with Everyone folder. Paste in the following code and replace any placeholders with correct values.

    //  Now make a call to get a list of all files in a folder 
    //  Replace placeholders in the following string with correct values for your domain and user name. 
        var skyGetAllFilesCommand = "'/personal/YourUserName_YourO365domain_spo_com/Documents/Shared%20with%20Everyone')/Files";
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(skyGetAllFilesCommand);
        request.Method = "GET";
        WebResponse wr = request.GetResponse();
        ViewBag.test = wr.ToString();
        return View(); 
  9. Create a view for the CatchCode method. In Solution Explorer expand the Views folder and choose Home, and choose Add View.

  10. Enter CatchCode as the name of the new view, and choose Add.

  11. Paste the following HTML to render the users and Microsoft OneDrive for Business response from the CatchCode method.

        ViewBag.Title = "CatchCode";
    <ul id="users">
        @foreach (var user in ViewBag.userList)
    <h2>OneDrive for Business Response</h2>
  12. Build and run the solution. Verify that you get a list of users, and that you get an XML response from the Microsoft OneDrive for Business method call. To change the XML response, add files to the Microsoft OneDrive for BusinessShare with Everyone folder.

© 2014 Microsoft