How-To: Authenticate To Windows Azure AD Graph Using Windows Azure AD Access Control
Applies To
-
Windows Azure Active Directory (AD) Graph
Summary
This how-to procedure provides the steps and code snippets required to successfully authenticate to Windows Azure AD Access Control using a symmetric key.
Contents
-
Prerequisites
-
Objectives
-
Overview
-
Summary of Steps
-
Step 1: Create a Service Principal Using Office 365 Windows PowerShell cmdlets.
-
Step 2: Request a Token from Windows Azure AD Access Control using Windows Azure Authentication Library (AAL).
-
Step 3: 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.
-
You must have the Office 365 Windows PowerShell cmdlets installed. For more information, see Windows Azure Active Directory Graph Prerequisites.
-
Your Windows Azure AD user account should be in the Company Administrator role. This role enables you to perform create, read, update, and delete operations on service principals, and also to add or remove them from administrator roles.
Objectives
-
Create a service principal using Office 365 Windows PowerShell cmdlets.
-
Authenticate to Windows Azure AD Access Control using AAL.
Overview
Authentication to Windows Azure AD Access Control is required to successfully access Windows Azure AD entities using Windows Azure AD Graph. Your application is represented by a service principal in Windows Azure AD. Service principals can be created with one of two types of credentials depending on your security requirements; either a shared symmetric key or an X.509 client certificate. Your application will need to provide the appropriate credential, depending on how its service principal was created, to successfully authenticate to Windows Azure AD Access Control. Upon successful authentication, your application receives an access token back from Windows Azure AD Access Control which it then includes in the authentication header of every request it makes to Windows Azure AD Graph.
You can use the Windows Azure AD Authentication Library (AAL) to authenticate to Windows Azure AD and receive an access token for your application. AAL provides a simple interface that abstracts away the complexity of handling underlying communication protocols between a client, Windows Azure AD Access Control, and a relying party (RP) application. AAD enables you to easily write code to authenticate a user or an application to Windows Azure AD using just a few, intuitive classes and methods. For more detailed information about AAL, see the Windows Azure Authentication Library documentation.
To successfully authenticate to Windows Azure AD Access Control using AAL you need to follow the steps outlined in this how-to.
Summary of Steps
-
Step 1: Create Service Principal Using Office 365 Windows PowerShell cmdlets
-
Step 2: Request a Token from Windows Azure AD Access Control using AAL
-
Step 3: Test Your Solution
Step 1: Create a Service Principal Using Office 365 Windows PowerShell cmdlets
This step shows you how to create a service principal using Office 365 Windows PowerShell cmdlets. This administrative step is performed only once for each service principal. You will use the credentials used to create the service principal in this step – either a shared symmetric key or an X.509 client certificated -- when programmatically requesting a token from Windows Azure AD Access Control.
To create Service Principal
-
From your desktop, click the Microsoft Online Services Module shortcut to open a Windows PowerShell workspace that has the Office 365 cmdlets. Alternatively, you can load the Office 365 cmdlets manually by typing import-module MSOnline at the Windows PowerShell command prompt.
-
Run the following command to import the MsOnlineExtended module into your Windows PowerShell workspace. This module contains commands that enable you to create, read, update and delete service principals.
C:\PS>Import-Module MsOnlineExtended -Force
-
Run the following command to initiate a connection to Microsoft Online.
C:\PS>Connect-MsolService
-
When prompted, provide your administrative credentials.
-
Use the New-MsolServicePrincipal cmdlet to create a service principal. You will be using the service principal and its credentials to authenticate to Windows Azure AD Access Control from your application. The cmdlet should look similar to the following; you will use your values for the service principal name or names and the display name.
By default, the service principal is created with a symmetric key credential and a validity of one year. The output will be similar to the following.C:\PS> New-MsolServicePrincipal -ServicePrincipalNames @("MyApp/myApp.com") -DisplayName "My Application"
The following symmetric key was created as one was not supplied tKSGj3sM7I8+7UO4bSYOMpujG/yiaZSOUI4pszf0ONI= DisplayName : My Application ServicePrincipalNames : {MyApp/myApp.com, ff5d4e7a-59fc-4b72-8b58-8cbeb50d8d50} ObjectId : 920d78c6-a1b4-4a07-9e8c-ee0e38a2d06e AppPrincipalId : ff5d4e7a-59fc-4b72-8b58-8cbeb50d8d50 TrustedForDelegation : False AccountEnabled : True Addresses : {} KeyType : Symmetric KeyId : 8f84a89d-8e8d-421b-be1a-0c80de7fd8aa StartDate : 11/30/2012 12:41:51 AM EndDate : 11/30/2013 12:41:51 AM Usage : Verify
Important The default symmetric key credential created by the New-MsolServicePrincipal cmdlet cannot be retrieved later from the service principal. You should copy this credential from the output of the cmdlet and keep it in a secure location. You will need it to authenticate with Windows Azure AD Access Control.
Note After the command completes, it may take a few minutes for the service principal to actually be provisioned to Windows Azure AD. If you run your application code immediately after running this command, the authentication may fail due to this latency. If this happens, wait a few minutes and try running your application code again. -
Note the ObjectId, the AppPrincipalId, and the value of the symmetric key from the output of the cmdlet. You will use these in the next step.
Step 2: Request a Token from Windows Azure AD Access Control
This step shows you how to request a token from Windows Azure AD Access Control
To request a token form Windows Azure AD Access Control
-
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, WindowsAzureADAccessControlAuthentication).
-
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 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 Program.cs file in the editor by double clicking it in Solution Explorer.
-
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 Microsoft.WindowsAzure.ActiveDirectory.Authentication;
-
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 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;
-
Add the following method to the Program class. This method uses AAL to retrieve an access token from Windows Azure AD Access Control and returns it to the caller as a bearer token that can be added to the authentication header in requests to Windows Azure AD Graph.
// 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 (AALException aalEx) { // For this example, if an AAL exception occurs just write it to the console. // Note: other exceptions can occur. Console.WriteLine(aalEx.ToString()); } return authzHeader; } -
Replace the Main method with the following code.
static void Main(string[] args) { Console.WriteLine("Authenticating with Windows Azure AD Access Control and getting an access token ..."); Console.WriteLine(GetAuthorizationHeader()); Console.WriteLine("\nPress <Enter> to exit."); Console.ReadLine(); }
Step 3: Test Your Solution
This step helps you test your code and make sure Windows Azure AD Access Control successfully issues a token upon successful authentication.
To test your solution
-
Compile your solution by pressing Ctrl+Shift+B to make sure there are no compilation errors.
-
Run your solution by pressing F5. If no exceptions occurred, you should see a bearer token issued by Windows Azure AD Access Control, similar to the following: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1N….cOFh3NaJx8tDMWLSRNBMJgi8CtLC1H1Dye8Oo4S8nEpLfrsg
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 Microsoft.WindowsAzure.ActiveDirectory.Authentication;
namespace WindowsAzureADAccessControlAuthentication
{
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 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;
static void Main(string[] args)
{
Console.WriteLine("Authenticating with Windows Azure AD Access Control and getting an access token ...");
Console.WriteLine(GetAuthorizationHeader());
Console.WriteLine("\nPress <Enter> to exit.");
Console.ReadLine();
}
/// 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 (AALException aalEx)
{
// For this example, if an AAL exception occurs just write it to the console.
// Note: other exceptions can occur.
Console.WriteLine(aalEx.ToString());
}
return authzHeader;
}
}
}
See Also