[Windows Azure] Using the Graph API to Query Windows Azure AD
Using the Graph API to Query Windows Azure AD
This document will explain how to configure a .NET application to use the Graph API to access Directory data from a Windows Azure AD Tenant’s directory.
Overview
This sample application is intended for .NET developers who want to add to existing applications and build new applications for Windows Azure Active Directory. This walkthrough builds upon the previous walkthrough, Adding Sign-On to Your Web Application Using Windows Azure AD, which produced a sample app that demonstrates how to provide a web single sign-on user experience for Windows Azure AD customers. This document will show how to add capability to read directory data using the Windows Azure AD Graph API. The Graph API is a new RESTful API that allows applications to access customers’ Windows Azure directory data.
Applications need access to directory data for many scenarios including:
- Retrieving lists of users, groups, contacts for people/group pickers
- Reading detailed tenant, user and group information
- Verifying Group membership
- Modifying user and groups, group membership
- Updating a user’s password
- Disabling user accounts
Outline of Sections
This document is organized into the following sections:
- Prerequisites: This section lists all the requirements that must be met for you to complete the walkthrough.
- Solution Architecture: This section provides a high level introduction of what is required to enable access to the Graph API in your application.
- Configuring Application Authentication and Authorization for the Graph API: This section shows you how to configure your application for authentication and authorization before making calls to the Graph API.
- Adding Graph API Access to the MVC 4 Single Sign-On Walkthrough Application: This section shows you how to modify the single sign-on project to give it access to the Graph API.
- Advanced Topics Section: This section briefly discusses tokens and the request headers and responses for the Graph API.
Prerequisites
This following prerequisites are required to complete this tutorial:
- An Internet connection
- An active Windows Azure subscription: You can get a 90 day free trial here: Windows Azure Free Trial
- Visual Studio 2012 Professional or Visual Studio 2012 Ultimate: You can download a free trial here: Visual Studio Free Trial
- Identity and Access Tools for Visual Studio 2012
- Download and install the WCF Data Services 5.3 tools from here.
- The completed single sign-on walkthrough sample application, which you create by following this topic: Adding Sign-On to Your Web Application Using Windows Azure AD
Solution Architecture
At the end of this walkthrough, you will have an application that is configured to read data from your tenant hosted in Windows Azure Active Directory. Directory entities that can be read include Users, Groups, Contacts, Company Information, Licenses, and Roles. Several of these directory entities’ properties can also be updated if your application is granted write Permissions.
In this sample application, we’ll review how to read directory data from your Windows Azure AD company. Additional advanced topics include:
- Getting full user details
- Creating and Updating Users
- Getting a list of groups
- Updating group membership
Authentication and Accessing the Graph API
The single sign-on experience remains the same after updating this application for accessing the Graph API. After successful user authentication, the application start the process of calling the Graph API by first requesting a token from Windows Azure AD Authentication endpoint, and once successful, the app will use the token in the subsequent Graph API call to get all users from the tenant. The application will then display a list of users, showing their Display Names and User Principal Names.
Application Authentication and Authorization for the Graph API
In this walkthrough, we will be using the OAuth 2.0 client credential flow to authenticate the application. Before accessing the Graph API endpoint, the application must first acquire a valid token from Windows Azure Active Directory’s Authentication endpoint -- it does this by presenting valid application credentials (Client ID and Secret). If the credentials are validated, a signed token is returned to the application. The application will then include the token in its Authorization header in its calls to the Graph API. The Graph API service will validate the token against the incoming request, and if this passes, then an authorization check occurs next.
Application authorization is verified by the Graph API and its underlying Role Based Access Control (RBAC) service. Calls to the Graph API are limited to the permissions that are configured to the application. Data is returned to the application if authentication and authorization passes.
Configuring Application Authentication and Authorization for the Graph API
An application’s authentication and authorization configuration are stored in Windows Azure AD using a Service Principal object stored in tenants’ directory. Similar to how users are represented by User Principal objects stored in tenants’ Active Directory, each having unique identities, credentials and permissions, an application in Windows Azure AD is represented by a Service Principal object, with a unique identity, credential and permissions.
An application’s Service Principal is configured to have a unique ID and Secret, which is used for authentication. Authorization is managed by adding the application’s Service Principal to a role that has the required permissions. Creating application Service Principals and adding them to roles can be done by Tenant Administrators using the Windows Azure AD Management Portal. Optionally, Tenant Administrators can also use PowerShell to manage Service Principals.
In the previous single sign-on walkthrough, you authorized the application to allow single sign-on using your Windows Azure AD user credentials by configuring the app permissions in the Windows Azure AD Management Portal. You will now update the application configuration to enable this walkthrough application to authenticate, and be authorized to call the Graph API. The following steps should be executed:
- Authorization: configure your app permissions to allow read/write access to the directory.
- Authentication: get an Application Key, which is your application’s password and used to authenticate your application to the Graph API.
Authorization – Configure the Application to Allow for Read and Write Permissions
- Log on to the Windows Azure Active Directory Management Portal and find the sample application you created in the single sign-on walkthrough.
- Select the MANAGE ACCESS button on the bottom of the screen.
- On the What do you want to do? screen, select Change the directory access for this app.
- On the next screen, select the radio button next to SINGLE SIGN-ON, READ DIRECTORY DATA, then check button in the bottom right-hand corner of the screen to save your changes.
Authentication – Configure the Application Key
- From the main application page, expand Enable your app to read or write directory data, then under the CREATE A KEY section, select the Configure key option.
- Next on the Properties page, under the Keys section, add a key by selecting the key’s lifespan (default 1 year), and then select Save at the bottom of the screen. This will generate a key value that is your application’s password and will used in the application configuration.
Warning The key value is displayed after key creation, but cannot be retrieved later. Therefore, you should immediately copy the key value and store it in a secure place for your future reference. Also, your application can have multiple keys –- for example, you may want one or more for testing and production.
At this point you have a Client ID (Application ID), an application key (the key value) and have configured read and write permissions for the application.
Note |
---|
In this walkthrough sample application, we are using the key values as a password to authenticate the application (in OAuth 2.0 terms, are using the Client credentials grant flow, where grant_type=client_credentials ).
|
Adding Graph API Access to the MVC 4 Single Sign-On Walkthrough Application
Open Visual Studio, then open the single Sign-on walkthrough project that you previously built. We will be modifying the sign sign-on walkthrough application in the following steps:
- Add the Graph helper class project
- Update to WCF Datservices 5.3 or greater
- Update the Web.config file
- Modify the HomeController
- Add a new View for Users
- Update the common _Layout View
Add Graph Helper Class Project to the Single Sign-On Walkthrough Application
The Graph Helper class project includes a library and classes that facilitate authenticating to and calling the Graph API. It includes source code and should be included and built as part of this walk-through. Download the Graph Helper project.
- To add the Graph Helper to the single sign-on project, right-click the ExpenseReportsolution, click Add, then click Existing Project.
- From the Add Existing Project dialog, navigate to the Graph Helper path, then open theMicrosoft.WindowsAzure.ActiveDirectory.GraphHelper.csproj project file.
The Graph Helper project will be added to your ExpenseReport solution.
Update the Existing Single Sign-On Application’s Web.config File
The appSettings section of the Web.config file has application specific configuration information – add the ClientId and Password values to the application’s Web.config file.
- ClientId: equal to the Client ID value from the Windows Azure AD Management Portal application management page.
- Password: equal to the Application Key Value from the Windows Azure AD Management Portal Application management page. This should have been recorded from the previous step to create a key – note this is not retrievable. If you forgot or lost the previous key, create another under the same application.
<appSettings>
<add key="ClientId" value="<insert your ClientId here>"/>
<add key="Password" value="<insert your Application Key here>"/>
...
Save the Web.config file after making the changes.
Update the Project’s References
- From Visual Studio, right-click on the single sign-on walkthrough project’s Referencesfolder, then click Add Reference…
- On the Reference Manager dialog, click Extensions from the left menu, then click the checkbox next to the Microsoft.Data.OData version 5.3.0.0 assembly and theMicrosoft.Data.Services.Client version 5.3.0.0 assembly.
- In the same Reference Manager dialog, expand the Solution menu on the left, then click the checkbox for the Microsoft.WindowsAzure.ActiveDirectory.GraphHelper. PressOK, then the references will be added to your project.
Update the HomeController
Open the HomeController.cs file, which is in the Controllers folder. Add the following assemblies to the file, then save the file.
using System.Configuration;
using System.Security.Claims;
using System.Data.Services.Client;
using Microsoft.WindowsAzure.ActiveDirectory;
using Microsoft.WindowsAzure.ActiveDirectory.GraphHelper;
Find the HomeController class in the HomeController.cs file, where the existing ActionResultsreside (Index, About, Contact). Add a new ActionResult called Users as shown below:
public ActionResult Users()
{
//get the tenantName
string tenantName = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value; // retrieve the clientId and password values from the Web.config file
string clientId = ConfigurationManager.AppSettings["ClientId"];
string password = ConfigurationManager.AppSettings["Password"]; // get a token using the helper
AADJWTToken token = DirectoryDataServiceAuthorizationHelper.GetAuthorizationToken(tenantName, clientId, password); // initialize a graphService instance using the token acquired from previous step
DirectoryDataService graphService = new DirectoryDataService(tenantName, token); // get Users
//
var users = graphService.users;
QueryOperationResponse<User> response;
response = users.Execute() as QueryOperationResponse<User>;
List<User> userList = response.ToList();
ViewBag.userList = userList; // For subsequent Graph Calls, the existing token should be used.
// The following checks to see if the existing token is expired or about to expire in 2 mins
// if true, then get a new token and refresh the graphService
//
int tokenMins = 2;
if (token.IsExpired || token.WillExpireIn(tokenMins))
{
AADJWTToken newToken = DirectoryDataServiceAuthorizationHelper.GetAuthorizationToken(tenantName, clientId, password);
token = newToken;
graphService = new DirectoryDataService(tenantName, token);
} // get tenant information
//
var tenant = graphService.tenantDetails;
QueryOperationResponse<TenantDetail> responseTenantQuery;
responseTenantQuery = tenant.Execute() as QueryOperationResponse<TenantDetail>;
List<TenantDetail> tenantInfo = responseTenantQuery.ToList();
ViewBag.OtherMessage = "User List from tenant: " + tenantInfo[0].displayName; return View(userList);
}
Add a new View for Users
Create a new view under the Views/Home folders called Users.cshtml, and add the following code:
@model IEnumerable<Microsoft.WindowsAzure.ActiveDirectory.User>
@{
ViewBag.Title = "Users";
} <h1>@ViewBag.Message</h1>
<h2>@ViewBag.OtherMessage</h2>
<table>
<tr>
<th>
DisplayName
</th>
<th>
UPN
</th>
<th></th>
</tr> @if (User.Identity.IsAuthenticated)
{ foreach (var user in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => user.displayName)
</td>
<td>
@Html.DisplayFor(modelItem => user.userPrincipalName)
</td>
</tr>
}
}
</table>
Update the _Layout.cshtml View
Find and open the _Layout.cshtml file under the Views/Shared folder, and add the following<nav> section within the <header> section of the file. Then, save the file.
<nav>
<ul id="menu">
<li>@Html.ActionLink("Home", "Index", "Home")</li>
<li>@Html.ActionLink("About", "About", "Home")</li>
<li>@Html.ActionLink("Contact", "Contact", "Home")</li>
<li>@Html.ActionLink("Users", "Users", "Home")</li>
</ul>
</nav>
Run the Application
Press F5 to run the application. The single sign-on experience is the same as you saw in the previous walkthrough, requiring authentication using your Windows Azure AD credentials. If you published your application to a website, you should update it with the updates from this walkthrough. After successful user authentication, select the Users tab from the top right menu.
The application starts the process of calling the Graph API by first requesting a token from Windows Azure AD Authentication endpoint. Once this is successful, it will use the token in the subsequent Graph call to get all users from the tenant. The application will then display a list of users, showing their Display Names and User Principal Names.
This concludes the coding for the Graph API walkthrough application. The next section includes more detailed information and links to a more advanced Graph API sample application that shows additional read and write operations.
Advanced Topics Section
Application Execution
After successful single sign-on, the application will request a token from the Windows Azure AD Authorization endpoint, using the tenant name (obtained from the signed on user’s tenant ID claim), ClientID and Password to authenticate. The details of the method that supports the token acquisition can be found in the DirectoryDataServiceAuthorizationHelper class found in the file of the same name. The GetAuthorization method manages acquiring the JSON Web Token (JWT) token from Windows Azure AD Authentication by providing a valid tenant name (any verified domain owned by the tenant), Client ID and the Password.
A successful request will return a JWT token to be used in calls to the Graph API, which is inserted in the Authorization header of subsequent requests. The Graph API call to get all users is an HTTP GET request that contains the following headers:
Content-Type: application/json; odata=minimalmetadata
Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik5HVEZ2ZEstZnl0aEV1T….
It is recommended that the JWT token be cached by the application for subsequent calls – in the sample application, the JWT token expiration is checked before making a second Graph API call. If the token is expired, then a new token is acquired. If a call to the Graph API is made with an expired token, the following error response will be returned, and the client should request a new token.
HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer realm="contoso.com", error="invalid_token", error_description="Your access token has expired. Please renew it before submitting the request.",
Note |
---|
Currently there is a preview of Windows Azure Authentication Library (AAL) which manages the acquisition of the Windows Azure AD authentication tokens. When AAL is released, we will update our sample applications and documentation to use AAL. The documentation for the AAL preview is located here. |
Other Advanced Topics
Additional REST calls, including read and write methods, can be found in another MVC4 Sample application that can downloaded from here.
This sample demonstrates additional REST functionality including:
- Get and Set User Details, including thumbnail photos
- Create, Update Groups
- Update Group Membership
- Paging for handling a large number of returned objects
[Windows Azure] Using the Graph API to Query Windows Azure AD的更多相关文章
- 【Azure API 管理】解决API Management添加AAD Group时遇见的 Failed to query Azure Active Directory graph due to error 错误
问题描述 为APIM添加AAD Group时候,等待很长很长的时间,结果添加失败.错误消息为: Write Groups ValidationError :Failed to query Azure ...
- 如何通过Azure Service Management REST API管理Azure服务
通过本文你将了解: 什么是Azure Service Management REST API 如何获取微软Azure 订阅号 如何获取Azure管理证书 如何调用Azure Service Manag ...
- Windows Phone 8 - Runtime Location API - 2
原文:Windows Phone 8 - Runtime Location API - 2 在<Windows Phone 8 - Runtime Location API - 1>介绍基 ...
- Windows Phone 8 - Runtime Location API - 1
原文:Windows Phone 8 - Runtime Location API - 1 在Windows Phone里要做Background Service的方式,除了Background Ag ...
- 【Azure Developer】使用Microsoft Graph API 如何批量创建用户,用户属性中需要包含自定义字段(如:Store_code,Store_name等)
Microsoft Graph 是 Microsoft 365 中通往数据和智能的网关. 它提供统一的可编程模型,可用于访问 Microsoft 365.Windows 10 和企业移动性 + 安全性 ...
- AAD Service Principal获取azure user list (Microsoft Graph API)
本段代码是个通用性很强的sample code,不仅能够操作AAD本身,也能通过Azure Service Principal的授权来访问和控制Azure的订阅资源.(Azure某种程度上能看成是两个 ...
- 【Azure Developer】Python 获取Micrisoft Graph API资源的Access Token, 并调用Microsoft Graph API servicePrincipals接口获取应用ID
问题描述 在Azure开发中,我们时常面临获取Authorization问题,需要使用代码获取到Access Token后,在调用对应的API,如servicePrincipals接口. 如果是直接调 ...
- 【Azure Developer】使用Microsoft Graph API 批量创建用户,先后遇见的三个错误及解决办法
问题描述 在先前的一篇博文中,介绍了如何使用Microsoft Graph API来创建Azure AD用户(博文参考:[Azure Developer]使用Microsoft Graph API 如 ...
- 【Azure Developer】使用Microsoft Graph API创建用户时候遇见“401 : Unauthorized”“403 : Forbidden”
问题描述 编写Java代码调用Mircrosoft Graph API创建用户时,分别遇见了"401 : Unauthorized"和"403 : Forbidden&q ...
随机推荐
- windows常用命令行整理
Windows虽然以GUI界面为主,但有时命令行也起到了很大的作用,下面就介绍几个常用.常见的windows命令行命令 1.ping 功能:用来测试数据包能否通过IP协议到达特定主机.即测试本机与特定 ...
- Android如何设置TextView的行间距、行高。
Android系统中TextView默认行间距比较窄,不美观. 我们可以设置每行的行间距,可以通过属性android:lineSpacingExtra或android:lineSpa ...
- (原)使用tensorboard显示loss
转载请注明出处: http://www.cnblogs.com/darkknightzh/p/7416551.html 参考网址: http://blog.csdn.net/jerry81333/ar ...
- iOS 适用于Pad上的菜单弹出界面-最简单的一种实现记录
前言: 此种方式实现只适用于pad开发,在iPhone上是无效的. 实现: 比如我在界面上有一个按钮,点击按钮,在按钮旁边弹出一个Pop框. 1.按钮点击事件 btn.addTarget(self, ...
- ios持久化存储
前言 iOS中常用的持久化存储方式有好几种: 偏好设置(NSUserDefaults) plist文件存储 归档 SQLite3 Core Data 沙盒 每个iOS应用都有自己的应用沙盒(应用沙盒就 ...
- iOS 10 的一个重要更新-自定义的通知界面
续上篇,在简单闹钟的例子上,在通知界面上显示图片动画,并用通知关联的按钮更新通知界面.介绍 iOS 10 通知 API 的扩展:自定义通知显示界面. 新框架可以统一处理本地通知和远程推送,同时增加了一 ...
- 有关memcached企业面试案例讲解
有关memcached企业面试案例讲解 1.Memcached是什么,有什么作用? a. memcached是一个开源的.高性能的内存的缓存软件,从名称上看Mem就是内存的意思,而Cache就是 ...
- Windows系统使用vbs脚本或bat脚本强制杀死指定所有进程 vbs实现循环持续写入内容到vbs打开开的记事本 使用vbs、bat添加windows计划任务 使用cmd schtasks命令添加windows计划任务
以下脚本windows7下成功运行过,脚本也可以windows计划任务程序一起组合使用 新建一个记事本文档粘贴下面代码后将新建的记事本文档重命名下面对应的脚本名就能使用了: 添加windows计划任务 ...
- MapReduce 模式、算法和用例
翻译自:http://highlyscalable.wordpress.com/2012/02/01/mapreduce-patterns/ 在这篇文章里总结了几种网上或者论文中常见的MapReduc ...
- MVC几种找不到资源的解决方式
在MVC中,controller中的Action和View中的.cshtml文件名称有一个对应的关系. 当不对应时,有以下几种情况发生: 一.找不到视图的错误 请求URL:http://localho ...