How-To: Read Windows Azure Active Directory Entities Using Windows Azure AD Graph
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
-
Prerequisites
-
Objectives
-
Overview
-
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
Prerequisites
The following are required to perform the steps in this example.
-
A Windows Azure AD tenant. For more information, see Windows Azure Active Directory Graph Prerequisites.
-
A service principal. For information about service principals and how to create them, see Windows Azure AD Graph Authentication and How-To: Authenticate To Windows Azure AD Graph Using Windows Azure AD Access Control.
-
The service principal should be in the following Windows Azure AD administrator role: User Account Administrator. For more information about Windows Azure AD tenant roles and how to add a service principal to them, see Windows Azure AD Graph and Role-Based Access Control and How-To: Manage Role-Based Access Control When Using Windows Azure AD Graph.
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
-
Open Visual Studio and click New Project on the Start page.
-
In the New Project dialog box, choose the Console Application Visual C# project template and specify the name of your application (for example, MyFirstWindowsAzureAdGraphApp).
-
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.
Note Select the non-platform specific version of AAL. Do not select either of the platform specific versions if they appear in your list. -
Right-click your application in Solution Explorer and click Add Service Reference.
-
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
Important 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.
Note 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. -
Microsoft.Data.Edm
-
Right-click your project in Solution Explorer and click Add Reference.
-
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.
-
Open the Program.cs file in Visual Studio editor.
-
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
-
Open the Program.cs file in Visual Studio editor.
-
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
-
Open the Program.cs file in Visual Studio editor.
-
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
-
Open the Program.cs file in Visual Studio editor.
-
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
-
Open the Program.cs file in Visual Studio editor.
-
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(); } -
Build the solution by pressing Ctrl+Shift+B to make sure there are no compilation errors.
-
Press F5 to run your Windows Azure AD Graph console application.
-
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