1 out of 2 rated this helpful - Rate this topic

How-To: Read Windows Azure Active Directory Entities Using Windows Azure AD Graph

[This topic is pre-release documentation and is subject to change in future releases. Blank topics are included as placeholders.]

Applies To

  • Windows Azure Active Directory (AD) Graph.

Summary

This how-to procedure provides the steps and code snippets required to successfully retrieve entities data from Windows Azure AD by using Windows Azure AD Graph. After completing this how-to procedure, you will have a working console application that retrieves and prints out the first page of the users in your Windows Azure AD subscription.

Contents

  1. Prerequisites

  2. Objectives

  3. Overview

  4. Summary of Steps

  5. Step 1: Add Required Dependencies and References

  6. Step 2: Collect Required Configuration Information

  7. Step 3: Acquire Token from Windows Azure AD Access Control

  8. Step 4: Read User Entities Information from Windows Azure AD

  9. Step 5: Test Your Solution

Prerequisites

The following are required to perform the steps in this example.

Objectives

  • Authenticate to Windows Azure AD Access Control

  • Retrieve and display raw user entities data from Windows Azure AD using Windows Azure AD Graph

Overview

If your users’ account information is stored and managed in Windows Azure AD, you may want to access it programmatically.

The scenarios could be:

  • As an enterprise developer you want to extend your enterprise line of business application that requires access to your accounts.

  • As an ISV you want to offer a reusable feature for sale that requires access to user information.

To successfully accomplish the task of retrieving information about users from Windows Azure AD you need to follow the steps outlined in this how-to procedure.

Summary of Steps

  • Step 1: Add Required Dependencies and References

  • Step 2: Collect Required Configuration Information

  • Step 3: Acquire Token from Windows Azure AD Access Control

  • Step 4: Read User Entities Information from Windows Azure AD

  • Step 5: Test Your Solution

Step 1: Add Required Dependencies and References

This step shows you which dependencies your application needs to have in order to successfully consume Windows Azure AD Graph.

To add dependencies

  1. Open Visual Studio and click New Project on the Start page.

  2. In the New Project dialog box, choose the Console Application Visual C# project template and specify the name of your application (for example, MyFirstWindowsAzureAdGraphApp).

  3. Install the Windows Azure Authentication Library (AAL) using NuGet. To do this, right-click your project in Solution Explorer, and click Manage NuGet Packages …. In the Manage NuGet Packages window, search for AAL. In the list of packages returned by the search, click Windows Azure Authentication Library Beta, then click Install and accept the license terms. After AAL is installed, click Close to close the Manage NuGet Packages window. As part of the installation, a reference to Microsoft.WindowsAzure.ActiveDirectory.Authentication is added to your project.



    noteNote
    Select the non-platform specific version of AAL. Do not select either of the platform specific versions if they appear in your list.

  4. Right-click your application in Solution Explorer and click Add Service Reference.

  5. In the Add Service Reference dialog box, specify the address of Windows Azure AD Graph REST service (https://graph.windows.net/<your tenant domain>/$metadata), and then click Go. After the service information is downloaded, Click OK to add the service reference to the project.

    In addition to the service reference, this step also adds references to the WCF Data Services Client and its dependent assemblies to your project:

    • Microsoft.Data.Edm

    • Microsoft.Data.OData

    • Microsoft.Data.Services.Client

    • System.Spatial



    ImportantImportant
    If you are using Visual Studio 2010, WCF Data Services 5.1 Tools must be installed before you add the service reference. You can determine whether WCF Data Services 5.1 Tools is installed from Programs and Features in Control Panel. You can install WCF Data Services 5.1 Tools from the Download Center.

    noteNote
    If, for some reason, you need to install the WCF Data Services Client manually, NuGet is the preferred method for doing so. Follow the instructions in Step 3, but search for WCF Data Services and click WCF Data Services Client in the list of packages that is returned. When you click Install, NuGet will resolve dependencies for WCF Data Services Client and you will be asked to accept the licenses for all of the packages to be installed. You can also install WCF Data Services from the Download Center.

  6. Right-click your project in Solution Explorer and click Add Reference.

  7. In the Reference Manager dialog box, ensure that Framework is selected under Assemblies, then check System.Windows.Forms in the list of .NET assemblies and click OK. This adds a reference to System.Windows.Forms to your project. This assembly is needed by AAL.

  8. Open the Program.cs file in Visual Studio editor.

  9. Replace the using directives at the top of the Program.cs file with the following:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net;
    using System.Data.Services.Client;
    using MyFirstWindowsAzureAdGraphApp.ServiceReference1;
    using MyFirstWindowsAzureAdGraphApp.ServiceReference1.Microsoft.WindowsAzure.ActiveDirectory;
    using Microsoft.WindowsAzure.ActiveDirectory.Authentication;
    
    

Step 2: Collect Required Configuration Information

This step helps you to verify what information you need before you can successfully run your Windows Azure AD Graph application.

To verify required information

  1. Open the Program.cs file in Visual Studio editor.

  2. At the top of the Program class, add the following variable declarations. Where indicated, you must replace the supplied values with values that are specific to your scenario.

    // AppPrincipalId is displayed when creating a service principal with the New-MsolServicePrincipal cmdlet
    // It can also be obtained by using the Get-MsolServicePrincipal cmdlet on an existing service principal
    private static string appPrincipalId = "b3d88062-...-79b944210e4e";
    
    // Your tenant domain name – this can be any domain that is owned by your tenant
    private static string tenantDomainName = "fabrikam.com";
    
    // The symmetric key for your service principal
    private static string servicePrincipalSymmetricKey = "yHi2 ... GB48=";
    
    private static string fullTenantName = "https://accounts.accesscontrol.windows.net/" + tenantDomainName;
    
    // Well known service principal ID for Windows Azure AD Access Control
    private static string protectedResourcePrincipalId = "00000002-0000-0000-c000-000000000000";
    
    // The Graph service endpoint
    private static string azureADServiceHost = "graph.windows.net";
    
    // The Graph API version for the request
    private static string dataContractVersion = "0.8";
    
    // The Graph service endpoint for your tenant
    private static Uri connectionUri = new Uri(string.Format(@"https://{0}/{1}", azureADServiceHost, tenantDomainName));
    
    // The service realm and issuing resource for acquiring a token from Windows Azure AD Access Control
    private static string serviceRealm = protectedResourcePrincipalId + "/" + azureADServiceHost + "@" + tenantDomainName;
    private static string issuingResource = appPrincipalId + "@" + tenantDomainName; 
    
    private static DirectoryDataService dataService;
    

Step 3: Create Authorization Header Using a Token from Windows Azure AD Access Control

This step helps you implement code that requests a token form Windows Azure AD Access Control and generates an authentication header for each request. The following requires that you have added the Azure Authentication Library (AAL) assembly to your project.

To acquire a token from Windows Azure AD Access Control

  1. Open the Program.cs file in Visual Studio editor.

  2. Add the following methods to the Program class:

    /// Method to get the Oauth2 Authorization header from Windows Azure AD Access Control
    private static string GetAuthorizationHeader()
    {
        string authzHeader = null;
        AuthenticationContext _authContext = new AuthenticationContext(fullTenantName);
    
        try
        {
            SymmetricKeyCredential credential = new SymmetricKeyCredential(issuingResource, Convert.FromBase64String(servicePrincipalSymmetricKey));
            AssertionCredential _assertionCredential = _authContext.AcquireToken(serviceRealm, credential);
            authzHeader = _assertionCredential.CreateAuthorizationHeader();
        }
        catch (Exception ex)
        {
            AALException aex = ex as AALException;
            string a = aex.Message;
        }
    
        return authzHeader;
    }
    
    
    // Attaches the token and adds the headers to the request. This method is called every time a request is sent.
    private static void AddHeaders()
    {
        dataService.SendingRequest += delegate(object sender1, SendingRequestEventArgs args)
        {
            ((HttpWebRequest)args.Request).Headers.Add("Authorization", GetAuthorizationHeader());
            ((HttpWebRequest)args.Request).Headers.Add("x-ms-dirapi-data-contract-version", dataContractVersion);
        };
    }
    

Step 4: Read User Entities Information from Windows Azure AD

This step helps you to issue a request to Windows Azure AD Graph with attached token acquired from Windows Azure AD Graph.

To read user entities information from Windows Azure AD

  1. Open the Program.cs file in Visual Studio editor.

  2. Add the following method to the Program class.

    private static List<User> GetUsers()
    {
        List<User> result = null;
    
        var userQuery = dataService.Users.Execute();
        result = userQuery.ToList();
        return result;
    }
    

Step 5: Test Your Solution

This step helps you to test your code and make sure it retrieves user information from the Windows Azure AD subscription.

To test your solution

  1. Open the Program.cs file in Visual Studio editor.

  2. Replace the Main method with the following code.

    static void Main(string[] args)
    {
        dataService = new DirectoryDataService(connectionUri);
    
        AddHeaders();
    
        var users = GetUsers();
    
        foreach (var user in users)
        {
            Console.WriteLine(user.DisplayName + ": " + user.UserPrincipalName);
        }
    
        Console.ReadLine();
    }
    
  3. Build the solution by pressing Ctrl+Shift+B to make sure there are no compilation errors.

  4. Press F5 to run your Windows Azure AD Graph console application.

  5. You should see user information appearing in the console window. You can use continuation tokens to request more users from Windows Azure AD Graph. See the following sample on Code Gallery for more details: Sample App (Write support) for Windows Azure Active Directory Graph API-REST Api.

Verify Your Solution

Your code should look similar to the following complete code example.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Data.Services.Client;
using MyFirstWindowsAzureAdGraphApp.ServiceReference1;
using MyFirstWindowsAzureAdGraphApp.ServiceReference1.Microsoft.WindowsAzure.ActiveDirectory;
using Microsoft.WindowsAzure.ActiveDirectory.Authentication;

namespace MyFirstWindowsAzureAdGraphApp
{
    class Program
    {
        // AppPrincipalId is displayed when creating a service principal with the New-MsolServicePrincipal cmdlet
        // It can also be obtained by using the Get-MsolServicePrincipal cmdlet on an existing service principal
        private static string appPrincipalId = "b3d88062-...-79b944210e4e";

        // Your tenant domain name – this can be any domain that is owned by your tenant
        private static string tenantDomainName = "fabrikam.com";

        // The symmetric key for your service principal
        private static string servicePrincipalSymmetricKey = "yHi2 ... GB48=";

        private static string fullTenantName = "https://accounts.accesscontrol.windows.net/" + tenantDomainName;

        // Well known service principal ID for Windows Azure AD Access Control
        private static string protectedResourcePrincipalId = "00000002-0000-0000-c000-000000000000";

        // The Graph service endpoint
        private static string azureADServiceHost = "graph.windows.net";

        // The Graph API version for the request
        private static string dataContractVersion = "0.8";

        // The Graph service endpoint for your tenant
        private static Uri connectionUri = new Uri(string.Format(@"https://{0}/{1}", azureADServiceHost, tenantDomainName));

        // The service realm and issuing resource for acquiring a token from Windows Azure AD Access Control
        private static string serviceRealm = protectedResourcePrincipalId + "/" + azureADServiceHost + "@" + tenantDomainName;
        private static string issuingResource = appPrincipalId + "@" + tenantDomainName;

        private static DirectoryDataService dataService;

        static void Main(string[] args)
        {
            dataService = new DirectoryDataService(connectionUri);

            AddHeaders();

            var users = GetUsers();

            foreach (var user in users)
            {
                Console.WriteLine(user.DisplayName + ": " + user.UserPrincipalName);
            }

            Console.ReadLine();
        }

        private static List<User> GetUsers()
        {
            List<User> result = null;

            var userQuery = dataService.Users.Execute();
            result = userQuery.ToList();
            return result;
        }

        /// Method to get the Oauth2 Authorization header from Windows Azure AD Access Control
        private static string GetAuthorizationHeader()
        {
            string authzHeader = null;
            AuthenticationContext _authContext = new AuthenticationContext(fullTenantName);

            try
            {
                SymmetricKeyCredential credential = new SymmetricKeyCredential(issuingResource, Convert.FromBase64String(servicePrincipalSymmetricKey));
                AssertionCredential _assertionCredential = _authContext.AcquireToken(serviceRealm, credential);
                authzHeader = _assertionCredential.CreateAuthorizationHeader();
            }
            catch (Exception ex)
            {
                AALException aex = ex as AALException;
                string a = aex.Message;
            }

            return authzHeader;
        }


        // Attaches the token and adds the headers to the request. This method is called every time a request is sent.
        private static void AddHeaders()
        {
            dataService.SendingRequest += delegate(object sender1, SendingRequestEventArgs args)
            {
                ((HttpWebRequest)args.Request).Headers.Add("Authorization", GetAuthorizationHeader());
                ((HttpWebRequest)args.Request).Headers.Add("x-ms-dirapi-data-contract-version", dataContractVersion);
            };
        }
    }
}

See Also

Did you find this helpful?
(1500 characters remaining)
© 2013 Microsoft. All rights reserved.