Leverage Azure AD for modern business applications
Leverage Azure AD for modern business applicationsOverview Technical ArticleMicrosoft FrancePublished: December 2013 (Updated: January 2016) Version: 1.2aAuthor: Philippe Beraud (Microsoft France)Contributors/Reviewers: Sébastien Brasseur, Arnaud Jumelet (Microsoft France) For the latest information on Azure Active Directory, please see ? 2016 Microsoft Corporation. All rights reserved.Abstract: Identity management, provisioning, role management, and authentication are key services both on-premises and through the (hybrid) cloud. With the “Bring Your Own Apps” (BYOA) for the cloud and Software as a Service (SaaS) applications, the desire to better collaborate a la Facebook with the “social” enterprise, the need to support and integrate with social networks, which leads to a Bring Your Own Identity (BYOI) trend, identity becomes a service where identity “bridges” in the cloud talk to on-premises directories or the directories themselves move and/or are located in the cloud. Active Directory (AD) is a Microsoft brand for identity related capabilities. In the on-premises world, AD provides a set of identity capabilities and services and is hugely popular (88% of Fortune 1000 and 95% of enterprises use AD). Azure Active Directory (Azure AD) is AD reimagined for the cloud, designed to solve for you the new identity and access challenges that come with the shift to a cloud-centric, multi-tenant world. Azure AD can be truly seen as an Identity Management as a Service (IdMaaS) cloud multi-tenant service for modern business applications.This document is intended for system architects, and developers who are interested in understanding the various options for using identities in their applications based on the Azure AD foundation and how to leverage the related capabilities.Table of Contents TOC \o "1-2" \h \z \u Important notice PAGEREF _Toc440297010 \h 3Introduction PAGEREF _Toc440297011 \h 4Objectives of this paper PAGEREF _Toc440297012 \h 7Non-objectives of this paper PAGEREF _Toc440297013 \h 8Organization of this paper PAGEREF _Toc440297014 \h 8About the audience PAGEREF _Toc440297015 \h 8Providing identity and access management to your (new) applications PAGEREF _Toc440297016 \h 9Authenticating against the directory PAGEREF _Toc440297017 \h 11Accessing the directory data PAGEREF _Toc440297018 \h 29Supporting automatic provisioning (Azure AD Premium only) PAGEREF _Toc440297019 \h 40Leveraging the various available code samples on GitHub PAGEREF _Toc440297020 \h 40Adding a web application for Single Sign-On (SSO) (and more) PAGEREF _Toc440297021 \h 42Adding a single tenant web application PAGEREF _Toc440297022 \h 42Developing a multi-tenant web application PAGEREF _Toc440297023 \h 80Adding a web API for Single Sign-On (SSO) PAGEREF _Toc440297024 \h 92Registering the web API in the directory tenant PAGEREF _Toc440297025 \h 92Configuring the web API project for Azure AD PAGEREF _Toc440297026 \h 94Defining the web API application roles and permissions PAGEREF _Toc440297027 \h 97Enabling the client application to access the web API PAGEREF _Toc440297028 \h 101Understanding web application calls to web API using own identity PAGEREF _Toc440297029 \h 104Understanding web application calls to web API using user’s identity PAGEREF _Toc440297030 \h 105Understanding daemon calls to web API using own identity PAGEREF _Toc440297031 \h 111Understanding server application calls to web API using user’s identity PAGEREF _Toc440297032 \h 112Adding a native application for Single Sign-On (SSO) PAGEREF _Toc440297033 \h 114Registering the native application in the directory tenant PAGEREF _Toc440297034 \h 114Updating the native application’s code PAGEREF _Toc440297035 \h 116Enabling the native application to access a web API in the same directory PAGEREF _Toc440297036 \h 117Enabling a native application to access a multi-tenant web API PAGEREF _Toc440297037 \h 119Understanding native application calls to web API using user’s identity PAGEREF _Toc440297038 \h 120Allowing external identities with your application PAGEREF _Toc440297039 \h 124Introducing the App model v2.0 PAGEREF _Toc440297040 \h 126A new registration process PAGEREF _Toc440297041 \h 126A support for a variety of modern application architecture PAGEREF _Toc440297042 \h 130Important noticeFor the latest information that pertains to how to integrate applications and APIs in Azure AD as covered in this document, please refer to the newly released Azure Active Directory Developer's Guide. This online developer’s guide indeed constitutes the de-facto reference content on this subject by providing overviews on implementation, key features, and protocols of Azure AD. Interestingly enough, it also provides a collection of quick start guides with complete instructions to perform fundamental development tasks with Azure AD, designed to help you getting up and running as efficiently as possible.The aforementioned quick start guides are organized per app type first, platform and development stack second with:A first set for native clients (iOS, Android, .NET, Windows Phone, Windows Store, Xamarin, and Cordova). And a second set for web apps (.NET Web App,? .NET Web API, JavaScript, and Node.js).You can expect to see the above lists to grow in future for encompassing more platforms and more tasks.To even go deeper, you may also consider the recently published book Modern Authentication with Azure Active Directory for Web Applications (ISBN 9780735696945), by Vittorio Bertocci.Introduction The cloud is changing the way in which applications are written. Accelerated market cycles, multi-tenancy, pure cloud solutions and hybrid deployments, web programmability, and the rise of devices (smartphones, tablets, etc.) as well as rich clients as consumption models offer without any doubt new opportunities.They also present at the same time new challenges for the key services both on-premises and through the (hybrid) cloud that represent the identity management, the provisioning, the role management, and the authentication.With: The "Bring Your Own Apps" (BYOA) for cloud and Software-as-a-Service (SaaS) applications, The desire to better collaborate a la Facebook with the “social” enterprise,The need to support and integrate with social networks, which lead to a Bring Your Own Identity (BYOI) trend, Etc.Identity becomes a service where identity “bridges” in the cloud “talk” to on-premises directories or the directories themselves move and/or are located in the cloud (see Gartner report 2013 Planning Guide: Identity and Privacy). Identity, like compute and storage and networking, is an essential platform service. In the same way that identity played a critical role in the adoption of workgroup computing, identity services will play a critical role as organizations adopt the cloud. Organizations will use cloud services and applications created by ISVs, Platform-as-a-Service (PaaS) cloud platforms for (Line of Business (LOB)) custom development, (as well as Infrastructure-as-a-Service (IaaS) cloud environment for specific workloads to onboard the cloud for IT optimization reasons). Kim Cameron, Microsoft Chief Identity Architect, is convinced that “organizations will find they need new identity management capabilities to take full advantage of the cloud. They will also find that the most reliable and cost-effect way to obtain these capabilities is through Identity Management as a Service – i.e. using the cloud to master the cloud.We can therefore predict with certainty that almost all organizations will subscribe to identity services that are cheaper, broader in scope and more capable than the systems of today.Enterprises will use these services to manage authentication and authorization of internal employees, the supply chain, and customers (including individuals), leads and prospects. Governments will use them when interacting with other government agencies, enterprises and citizens.Identity Management as a Service will require that we move beyond the models of identity management that have guided our thinking to date. A new service-based model will emerge combining more advanced capabilities with externalization of operations to achieve reduction in risk, effort and cost."Active Directory (AD) is a Microsoft brand for identity related capabilities. In the on-premises world, Windows Server Active Directory (WSAD or simply AD) provides a set of identity capabilities and services and is hugely popular in organizations of all sizes. With the Infrastructure as a Service (IaaS) capability in the cloud, such as the one offered by the Azure platform, it becomes possible to deploy virtual machines (VM) that host AD domain controller.Whilst such an approach could be more than appropriate for specific workloads on IaaS platforms like a SharePoint environment, the Microsoft vision for the cloud consists in recreating a similar identity service, but one that is optimized to support cloud applications and support modern protocols. Azure Active Directory (Azure AD or AAD) is AD reimagined for the cloud (see blog posts Reimaging Active Directory for the Social Enterprise (Part 1), (Part 2)), designed to solve for you the new identity and access challenges that come with the shift to a cloud-centric, multi-tenant world. Azure AD can be truly seen as an Identity Management as a Service (IdMaaS) cloud multi-tenant service that provides a robust and comprehensive cloud identity platform architected to operate in the cloud with high scale, high availability, and integrated disaster recovery. To say it another way, it’s a REST-based service that provides identity management and access control capabilities for modern business applications. Wikipedia defines REST and RESTful service as follows:“Representational State Transfer (REST) is a style of software architecture for distributed hypermedia systems such as the World Wide Web. The term Representational State Transfer was introduced and defined in 2000 by Roy Fielding in his doctoral dissertation. Fielding is one of the principal authors of the Hypertext Transfer Protocol (HTTP) specification versions 1.0 and 1.1.Conforming to the REST constraints is referred to as being ‘RESTful’. …A RESTful web service (also called a RESTful web API) is a simple web service implemented using HTTP and the principles of REST. It is a collection of resources, with three defined aspects:the base URI for the web service, such as MIME type of the data supported by the web service. This is often JSON, XML or YAML but can be any other valid MIME type.the set of operations supported by the web service using HTTP methods (e.g., POST, GET, PUT or DELETE)."Being optimized to support cloud services and supports modern protocols based on http/REST for mobile and consumer scenarios, like OpenID Connect 1.0, and OAuth 2.0, Azure AD typically provides identity and access capabilities for:Web applications and web APIs on Azure or in other clouds such Amazon Web Services (AWS),SaaS applications or multi-tenant applications such as the Microsoft Office 365, which relies on it for its identity infrastructure (or not),Mobile and native applications (with or without a back-end in the cloud like the one proposed through the Azure Mobile Apps),NoteWith Azure AD being supported as an identity provider in Azure Mobile Apps - alongside with the other identity providers (which include Microsoft Accounts, Facebook ID, Google ID, and Twitter ID) -, mobile business applications can use the same easy Mobile Services authentication experience to allow employees to sign into their mobile applications with their corporate Active Directory credentials. Azure AD utilizes the enterprise-grade quality and proven capabilities of AD on-premises, so you can bring your applications to the cloud easily. It offers capabilities that can be leveraged to centralize the identity management needs of your solutions, whether they are cloud-based, hybrid, or even on-premises. Azure AD is a complete offering that can help you to take advantage of your on-premises existing investment, to fully outsource to the cloud your user’s management and anything in between. By leveraging the Azure AD, you can enable single sign-on (SSO) across all your modern business applications as well as with your SaaS subscriptions (provided that they support the integration with Azure AD as it is the case today for the Microsoft services like Office 365, Dynamics CRM Online, etc. and thousands of popular SaaS applications). Single sign-on is the ability for a user to login in once and not have to re-enter their credentials each time when accessing different applications, APIs, or clouds.Modern business applications live in an environment that includes a broad spectrum of mobile and native clients, server to server communication, and web APIs, in addition to traditional browser-and-website interactions. Thus, protocols like WS-Federation and SAML 2.0 aren’t even enough to address all the scenarios introduced by these applications. Through standards such as OAuth 2.0 and OpenID Connect 1.0 mentioned above, Azure AD, as a next generation authentication platform, is designed to address these new requirements.NoteThe OpenID Foundation has recently launched a certification program for OpenID Connect 1.0 implementations. For more information, see the article The OpenID Foundation Launches OpenID Connect Certification Program. Azure AD has successfully passed the certification and is certified as an OpenID Connect 1.0 identity provider. Having an OpenID Connect certification program provides confidence that certified implementations will "just work" together. This represents another important step on the road to widely-available secure interoperable digital identity for all the devices and applications that people use. Microsoft is proud to be a key contributor to the development of OpenID Connect and now of its certification program.This represents an important part of Azure AD. “So far over 6000 applications are integrated with Azure AD and that number is growing by multiple hundreds every week.”If you are an ISV, you can leverage Azure AD to reach a vast user population, which includes the ever-growing user base of the Office 365. Since its introduction, Azure AD "has handled 400 billion identity authentications in Azure AD". "We have 350 million Azure Active Directory users. […] We actually process 4 billion, with a B, authentications every week with Azure Active Directory". This is a real testament to the level of scale we can handle. “At a high level, Azure AD is a high availability, geo-redundant, multi-tenanted, multi-tiered cloud service that has delivered 99.99% uptime for over a year now. We run it across 28 datacenters around the world. Azure AD has stateless gateways, front end servers, application servers, and sync servers in all of those data centers. Azure AD also has a distributed data tier that is at the heart of our high availability strategy. Our data tier holds more than 500 million objects and is running across 13 data centers.” Objectives of this paperAs an addition to the white-paper Active Directory from on-premises to the Cloud, this document aims at providing you with the relevant information - as a "guided tour" - to: Understand how to develop and register for your organization custom web applications, web API, native applications, and daemon and server application that benefit from the single sign-on, single sign-out, and/or the authorization capabilities of Azure AD. Azure AD publishes for that purpose various tenant-specific endpoints for standard authentication modern protocols.Understand how to develop and register multi-tenant applications that seamlessly integrate with the Azure AD directory tenants of your customer(s) and that provide single sign-on and single sign-out capabilities, and more. Azure AD publishes for that purpose various tenant-independent endpoints for standard authentication modern protocols.Understand the various protocol flows that sustain the aforementioned single sign-on and single sign-out capabilities.Learn about its directory-oriented programmatic interface Azure AD Graph API, a REST-based API that enables access to your Azure AD directory tenant or a customer’s for multi-tenant applications for read-only or read/write operations.Etc. This paper can be seen a starting point for anyone tackled with identity, cloud based authentication in their development of modern business applications.Non-objectives of this paperThis document is intended an overview document for anyone interested in adding the application they develop in Windows AD to benefit from its identity and access management capabilities, and as such, it doesn’t provide neither in-depth description nor detailed step-by-step instructions on how to implement a specific covered feature or capability. Where necessary, it instead refers to more detailed documents, articles, and blog posts that describe a specific feature or anization of this paperTo cover the aforementioned objectives, this document is organized by themes which are covered in the following sections: REF _Ref374363920 \h \* MERGEFORMAT Providing identity and access management to your (new) applications. REF _Ref374363927 \h \* MERGEFORMAT Adding a web application for Single Sign-On (SSO) (and more). REF _Ref374363944 \h \* MERGEFORMAT Adding a web API for Single Sign-On (SSO). REF _Ref374363952 \h \* MERGEFORMAT Adding a native application for Single Sign-On (SSO). REF _Ref430794382 \h \* MERGEFORMAT Allowing external identities with your application. REF _Ref430794376 \h \* MERGEFORMAT Introducing the App model v2.0.About the audienceThis document is intended for system architects, and developers who are interested in understanding the various options for using identities in their (hybrid) cloud environment based on the Windows AD foundation and how to leverage the related capabilities. Providing identity and access management to your (new) applicationsAzure AD is the directory behind Microsoft Online Services subscriptions like Office 365, Dynamics CRM Online, etc and is used to store user identities and other tenant properties.?Interestingly, Azure AD allows you to provide identity and access management to your (new) applications. Azure AD is available in three different editions to choose from:Azure Active Directory (Free). With the Free edition of Azure AD, you can manage user accounts, synchronize with on-premises directories, and get single sign-on across Azure, Office 365, and thousands of popular SaaS applications. NoteThis is a free edition as being used by the above Microsoft Online Services subscriptions. If you’ve already subscribed to a Paid Office 365 subscription, you can benefit from an Azure $0 subscription that you can use to access the Azure management portal with your existing Office 365 subscription in order to directly manage the related Azure AD tenant with all the access management and security feature set and thus empower your Office 365 subscription. You can sign-up for this $0 subscription by following the link of any Microsoft Online Services subscriptions, you can sign-up for your free Windows AD tenant and trial Azure account by following the link . Azure Active Directory Basic. Azure AD Basic provides the application access and self-service identity management requirements of task workers with cloud-first needs.?With the Basic edition of Azure AD, you get all the capabilities that Azure AD Free has to offer, plus group-based access management, self-Service password reset for cloud applications, customizable environment for launching enterprise and consumer cloud applications, and an enterprise-level SLA of 99.9 percent uptime.An administrator with Azure AD Basic edition can activate an Azure AD Premium trial.Azure Active Directory Premium. With the Premium edition of Azure AD, you get all of the capabilities that Azure AD Free and Azure AD Basic have to offer, plus additional feature-rich enterprise-level identity management capabilities. The edition in part of the Enterprise Mobility Suite (EMS) offering, a comprehensive and cost effective solution for enterprise mobility needs.NoteThe EMS offering is not only available with an Enterprise Agreement (EA) but also through the Microsoft’s Cloud Solution Provider (CSP) and Open programs. For additional information, see the blog post Azure AD and Enterprise Mobility Suite now available without an Enterprise Agreement.NoteTo sign up and start using this edition, see the MSDN article Getting started with Azure AD Premium.NoteFor a description of each edition below and a comparison table, see the Microsoft MSDN article Azure Active Directory editions. For more information on usage model, see the Microsoft MSDN article Azure Active Directory Pricing. For information on the usage constraints and other service limits for the Azure AD service per edition, see the Microsoft MSDN article Azure AD service limits and restrictions.The rest of the document applies to all of the above editions of Azure AD.Authenticating against the directoryAzure AD enable applications to provide single sign-on and single sign-out experiences to their users, and/or obtain a delegated access to secured resources. As of this writing, the following four primary scenarios are supported by Azure AD:Web browser to web application. A user needs to sign in to a web application that is secured by Azure AD.Single Page Application (SPA). A single page application that uses Azure AD to secure its web API back end. NoteSingle page applications are typically structured as a JavaScript presentation layer (front end) that runs in the browser and a web API back end that runs on a server and implements the application’s business logic.Native application to web API. A native application that runs on a phone, tablet, or PC needs to authenticate a user to get resources from a web API that is secured by Azure AD.Web application to web API. A web application needs to get resources from a web API secured by Azure AD.Daemon or server application to Web API. A daemon application or a server application with no web user interface needs to get resources from a web API secured by Azure AD.NoteFor more information, see the Microsoft MSDN article Authentication Scenarios for Azure AD. Let’s consider the modern authentication and authorization protocols that enable the above scenarios.Using supported (modern) protocolsUsual on-premises authentication mechanisms such as Kerberos and NTLM no longer apply in a general manner in the cloud space since modern applications do not have most of the time connectivity to a WSAD domain controller (DC) and/or the operating systems underneath aren’t domain-joined at all.It’s all the more so with the mobility and the “Bring-Your-Own-Device” (BYOD) trend where users will also often be themselves considered outside of the organization infrastructure perimeter. Furthermore, cloud solutions can by nature encompass multiple security realms.Consequently, Internet identity federation protocols constitute a much more scalable and efficient way to implement authentication in such context. Moreover, Internet identity federation protocols can also relevantly respond to other concerns like single sign-on (SSO) between cloud-based applications that reside in the same of different clouds as well as claims issuance with the processing and transforming capability of security tokens in terms of type of trust, token format, semantics and (values of) claims for “impedance adaptation”. Azure AD opts to such protocols for integrating applications and furthermore systematically aims at being open standards based wherever possible. NoteFor more information, see the Microsoft MSDN article Azure Active Directory Authentication Protocols.This translates by the support of the two following OASIS standards widely established and adopted:WS-Federation (WS-Fed) 1.2,Security Assertion Markup Language (SAML)?2.0. These two protocols use SAML security tokens. NoteFor more information, see the Microsoft MSDN article Supported Token and Claim Types.SAML 2.0, as a token format and a protocol, is very popular in the public sector with government agencies as well as with enterprises and educational institutions. SAML 2.0 is a suite of specifications and, as such, comprises a set of normative and non-normative documents. As part of them, the normative document Profiles for the OASIS Security Assertion Markup Language (SAML)?V2.0 defines the use cases or the “How-to” in regards to the use of SAML 2.0 protocol to solve specific problems of the extended enterprise, and as an important number of profiles. As of today, Azure AD more specifically supports for the modern applications the SAML 2.0 web browser single sign-in profile and the SAML 2.0 web browser single sign-out profile. NoteThese profiles supports various possible deployment models. The one implemented here is the HTTP-Redirect binding specified in the document Bindings for the OASIS Security Assertion Markup Language (SAML)?V2.0.NoteProtocol specifics for the SAML 2.0 support in Azure AD can be found in the Microsoft MSDN article SAML Protocol Reference.As previously outlined, modern applications live in an environment that includes a broad spectrum of mobile and native clients, server to server communication, and web APIs as a result of the API economy, in addition to traditional browser-and-website interactions.?And thus, even WS-Federation or SAML aren’t enough to address the scenarios introduced by modern business applications.?To address these new requirements, Azure AD unsurprisingly also provides support for the OAuth 2.0 protocol, which is gaining popularity in the Internet as an authorization protocol for accessing information. This is the primarily protocol for authorization and delegated authentication. Using OAuth 2.0, an application can gain access (with consent from the resource owner – which could be the end user or the administrator user) to impersonate the user, or users in his organization to access the resource. NoteFor more information, see the Microsoft MSDN article OAuth 2.0 in Azure AD.The OAuth 2.0 protocol uses JSON Web Token (JWT).?JWT is a compact token format also defined by the IETF OAuth WG that is especially apt for REST-based development. JWT use is growing, and products supporting the format are increasingly common in the industry.NoteFor more information, see the Microsoft MSDN article Supported Token and Claim Types.Along with OAuth 2.0, Azure AD provides a model for representing applications as service principals in the directory (see later in this document section). An application can then make use of its own identity, i.e. the “app identity”, or instead the user’s identity, i.e. the “app + user identity” (or delegated identity).Finally, Azure AD provides the support for the OpenID Connect 1.0 protocol (which is now approved as a final specification). OpenID Connect 1.0 defines an identity layer on top of OAuth 2.0 and represents the state of the art in modern authentication protocols. It’s a suite of lightweight specifications that provide a framework for identity interactions via REST like APIs. It is based on OAuth 2.0, and JWT is also one of the basic components of it.NoteFor more information, see the Microsoft MSDN article OpenID Connect 1.0.OpenID Connect 1.0 provides:A JSON configuration document (openid-configuration.json) as per OpenID Connect Discovery specification. This metadata information in JSON format provides configuration information such as the OAuth 2.0 endpoint locations, the signing key and issuer values to validate, etc. in analogy to what happens for WS-Federation and SAML 2.0 as described before.Sign out and check session endpoints, which allows a performant way to check if the current user session is active. This is describes in the OpenID Connect session management specification.Many of you might not realize it, but every time you log into the Azure management portal you are using OAuth 2.0 and OpenID Connect 1.0 to do so. OpenID Connect 1.0 is used to authenticate you and the management portal uses OAuth 2.0 to acquire an access token and a refresh token which it then uses to communicate with the Azure service management REST API (RDFE) on your behalf.NoteFor more information, see the Microsoft MSDN article Service Management REST API Reference.You can leverage OpenID Connect 1.0 in your modern applications to take advantage of all the features that the Microsoft Online services provide (Azure AD authentication, Azure AD Graph API, Office 365 APIs, Azure RDFE API, etc.), and all the resources that customers and partners such as yourself are adding every day to the Azure AD ecosystem. Note Azure AD Graph API is a RESTful API that provides a directory programming surface for querying and updating the directory, and thus to sustain the identities lifecycle management as whole. For more information, see the Microsoft MSDN article Azure AD Graph API.Note Office 365 APIs are REST services that provide access to high-value data types from the various services in Office 365 services: mail, calendars, and contacts from Exchange Online; files and folders from SharePoint Online and OneDrive for Business; users and groups from Azure AD. The Office 365 APIs follow REST and OData standards for data transport, and use the OpenID Connect 1.0 and OAuth 2.0 standards for authentications and authorization. For more information, see the Microsoft MSDN article Developing on the Office 365 platform.Microsoft has been deeply involved in the standards work for both OAuth 2.0 and OpenID Connect 1.0. Microsoft takes the participation in the standards community seriously and have worked hard to ensure interoperability with other implementations.NoteThe OpenID Foundation has recently launched a certification program for OpenID Connect implementations. For more information, see the article The OpenID Foundation Launches OpenID Connect Certification Program. Azure AD has successfully passed the certification and is certified as an OpenID Connect identity provider. Having an OpenID Connect certification program provides confidence that certified implementations will "just work" together. This represents another important step on the road to widely-available secure interoperable digital identity for all the devices and applications that people use. Microsoft is proud to be a key contributor to the development of OpenID Connect and now of its certification program.Integrating with the Azure AD STSAs shortly previously introduced, Azure AD supports several of the most widely used authentication and authorization protocols via a STS.In a recent past, this STS was implemented by a combination of two STS: The login. sign in service.And login., which was the de-facto facade for modern business applications.In this past service configuration, the login. sign-in service was (and still is today) in charge of handling the user authentication step, i.e. username/password - with an optional second-form of authentication (e.g. a mobile phone app, an automated phone call, or text message challenge) through the native support of Azure Multi-Factor Authentication in Azure AD -, and login. the policy and claims generation steps for modern application. Application authentication was thus handled directly by login.. login. acted as a federation provider, which trusted a single authority: the login. sign-in service. As of today, all authentication requests can now be served directly by the login. STS end-to-end. While being most of the time completely to an existing application - if the app makes certain assumptions about our underlying implementation it may require changes – this evolution provides several benefits:Users enjoy a faster sign-in experience free of extra hops.The sign-in user experience includes several new features, for example the ability to maintain multiple actively signed-in users, and a more responsive UI that behaves appropriately across more devices and screens. From an engineering perspective, this also leads to an even more reliable service thanks to a number of features this allows in the underlying implementation of the STS.Important noteApplications that send requests to login. continue to be supported. The redirect to login. occurs earlier in the authentication flow than before, and maintains protocol consistency. This said, we do recommend to reflect the evolution in such applications as soon as possible, thus allowing users to get an improved sign in experience, and authentication flows to be free of extra complexity.NoteFor more information, see the blog post Simplifying our Azure AD Authentication Flows.Tenant-specific endpointsAzure AD publishes tenant-specific endpoints. Tenant-specific endpoints are designed for a particular tenant. They share the same base URL and are structured as follows: domain name>/<protocol>Where <tenant domain name> can be: A registered domain name of an Azure AD directory tenant, for example corpfabrikam..The immutable tenant id of the domain, such as 90995f16-6b12-4032-8b87-fd59566ed917And <protocol> refers to a supported security protocols such as saml2 for the SAML 2.0 protocol support.login. uses for the tenant-specific endpoints the same signing key for all the tenants, but varies the issuer name in the security tokens to represent each tenant. This is an optimization notably for scale where applications do not need to trust many millions of different signing keys.In terms of discovery, Azure AD indeed publishes a federation metadata document for applications that are configured to accept the security tokens that Azure AD issues. A tenant-specific federation metadata document is published via a single discovery endpoint to integrate your directory into the application you’re developing or the SaaS applications your organization is subscribing to: domain name>/FederationMetadata/2007-06/FederationMetadata.xmlFor example, the Azure AD testing directory tenant corpfabrikam. (90995f16-6b12-4032-8b87-fd59566ed917) corresponds to: The tenant-specific federation metadata includes information about the tenant, including tenant-specific issuer and endpoint information. Applications that restrict access to a single tenant use tenant-specific endpoints.NoteThe federation metadata follows the general syntax and semantics of metadata are defined in the OASIS Web Services Federation Language (WS-Federation) Version 1.2. the OASIS Web Services Federation Language (WS-Federation) Version 1.2. For more information, see the Microsoft MSDN article Federation Metadata.The tenant-specific federation metadata defines 2 tenant-specific endpoints for applications:A passive tenant-specific endpoint for Web clients (browser) based on the WS-Federation protocol, as follows: domain name>/wsfedFor our directory tenant corpfabrikam., this corresponds to: is the endpoint to which applications that restrict access to a single tenant should send sign-on and sign-out requests when using the WS-Federation protocol. Authentication responses will be sent to the Reply URL for the application.Another passive endpoint for Web clients (browser) for the SAML 2.0 protocol, as follows: domain name>/saml2For our directory tenant corpfabrikam., this corresponds to: is the endpoint to which applications that restrict access to a single tenant should send sign-on requests when using the SAML 2.0 protocol. Authentication responses will be sent to the Reply URL for the application.NoteFor more information, see the Microsoft MSDN article SAML Protocol Reference.login. also publishes OAuth 2.0 tenant-specific endpoints to enable registered applications that have a service principal declared in the targeted directory tenant to obtain a bearer access token (as per RFC 6750) to access target resources through an API over HTTP or other protocols, for example with the Azure AD Graph API to query the targeted directory.To sustain the several flows defined in OAuth 2.0, 2 public endpoints are published by Azure AD:One endpoint at which applications can obtain an access token using OAuth 2.0, as follows: domain name>/oauth2/tokenFor our directory tenant corpfabrikam., this corresponds to: After an application is authenticated, Azure AD will issue the application an access token that allows the application to call the requested web API.And another endpoint at which an application can obtain an authorization token using OAuth 2.0, as follows: domain name>/oauth2/authorizeFor our directory tenant corpfabrikam., this corresponds to: more information, see the Microsoft MSDN article OAuth 2.0 in Azure AD.Finally, login. also publishes additional tenant-specific endpoints in complement of the above OAuth 2.0 endpoints to sustain the OpenID Connect 1.0 protocol as an OpenID provider.To sustain the several flows defined in OpenID Connect 1.0, 4 public endpoints are indeed published by Azure AD:One endpoint at which applications can obtain the OpenID provider configuration information, as follows: domain name>/.well-known/openid-configurationFor our directory tenant corpfabrikam., this corresponds to: endpoint at which applications can obtain user information, as follows: domain name>/openid/userinfoFor our directory tenant corpfabrikam., this corresponds to: sign-out endpoint as follows: domain name>/oauth2/logoutFor our directory tenant corpfabrikam., this corresponds to: endpoint that helps applications checking if the current user session is active, as follows: domain name>/oauth2/checksessionFor our directory tenant corpfabrikam., this corresponds to: more information, see the Microsoft MSDN article OpenID Connect 1.0.The following diagram synthetizes the above endpoints:As noticed before, the now legacy login. endpoints are still honored and redirect to the equivalent login. endpoint. As an illustration, and as far as OpenID Connect 1.0 is concerned, the discovery endpoint continues to return legacy login. based endpoints. Those endpoints then follow the appropriate redirects. The aforementioned actual discovery endpoint returns equivalent login. endpoints. As a result, the following diagram synthetizes all the above endpoints:In the interest of being thorough, the following items have not changed: The behavior of both token endpoints remain precisely the same. The value of the "issuer" both in metadata and in tokens issued by Azure AD remain the same – it continues to be based. Tenant-independent endpointsTenant-independent endpoints provide information that is common to all Azure AD tenants. This information is shared across tenants. Tenant-independent endpoints are recommended for multi-tenant applications, since they are not associated by nature with any particular tenant (expected the one in which the application is initially registered, see later in this document).Azure AD publishes the exact same tenant-independent endpoints as tenant-specific endpoints depicted in the previous section. Only the URL slightly differs where <tenant domain name>should be replaced by common. In lieu of the tenant-specific endpoints domain name>/<protocol>, the tenant-independent endpoints ; enables multi-tenant applications to know which tenant the user is in during sign-in. Azure AD signs the user in and figures out their tenant, handling this way for you the Home Real Discovery (HRD) or Where Are You From? (WAYF).On additional endpoint is published for the OpenID Connect protocol to allow the relying party applications to get the signing keys in order to validate signatures from the OpenID provider. This is the following endpoint that enables to download a JSON keys.json file: noticed before, the now legacy login. endpoints are still honored and redirect to the equivalent login. endpoint. The following diagram synthetizes all the above tenant-independent endpoints:Leveraging the Active Directory Authentication Library (ADAL)In order to easily interact with the above endpoints, Microsoft provides identity libraries for Azure AD. These libraries fall into the following categories:Libraries meant to enable clients to acquire security tokens from Azure AD, so that they can be used for accessing remote protected resources. This is what the ADAL libraries are for. These ADAL libraries are available on GitHub at for a variety of platforms: OSes or development stacks. They are further depicted in this sectionLibraries that help you to protect your resources ((multi-tenant) web applications, web API). Those are covered in the next section.Note For more information, see the blog post Identity Libraries: Status as of 03/23/2015.Note Microsoft leverage to work with the developer community on supporting Azure AD and its identity libraries and SDKs. Consequently, it’s highly recommend you ask your questions on . You can use the "adal" tag so we can see it. The latest Q&A on for ADAL is available at 2.xThe ADAL 2.x library provides easy to use authentication functionality for your .NET client, Windows Store, and Windows phone 8.1 applications by notably taking advantage of Azure AD. Note For more information, see the blog posts Active Directory Authentication Library (ADAL) v2 for .NET/Windows Store/Windows Phone–General Availability! and Getting Started with ADAL for .NET–Quick Video Tutorial.The ADAL library enables the following two key scenario types:Authenticating users of a client application to a remote web API. ADAL can be used to facilitate authentication with Azure AD, either by fully delegating the authentication experience to ADAL and Azure AD, or by explicitly handling user credentials. Authenticating a server application to a remote web API. ADAL can be used to facilitate authentication with Azure AD, by explicitly handling the application’s credentials. In both cases, the authentication results in an access token, and ADAL makes it easy to obtain this token and use it to make calls to the web API. For that purpose, it handles the sign-in experience to Azure AD and manage token caching (including on middle tier applications) and automatic token refresh operations. Note For more information on token caching, see the blog post The New Token Cache in ADAL v2.Note A multi-resource refresh token (MRRT) can be used to get access token to a different service if delegation exists. For more information (on multi-resources) refresh tokens that can be issued by Azure AD, see the blog post ADAL, Azure AD and Multi-Resource Refresh Tokens.If the .NET Framework 4.5 is targeted for the above web APIs, one can use the JSON Web Token Handler for the Microsoft .NET Framework 4.5 (JWT handler) to validate JWT tokens obtained via ADAL. (See below.)Note For more information, see the blog posts ADAL for Windows Phone 8.1 – Deep Dive.As of this writing, the latest stable version is 2.19.208020213 available as NuGet package for the Visual Studio development environment. To install the package, run the following command in the Package Manager Console:PM> Install-Package Microsoft.IdentityModel.Clients.ActiveDirectory -Version 2.16.204221202NoteFor more information on the above namespace, see the Microsoft MSDN article Microsoft.IdentityModel.Clients.ActiveDirectory Namespace.As previously indicated, the library source code is available as Open Source code on the GitHub.Note For more information, see the blog post ADAL for .NET/Windows Store/Windows Phone Is Now Open Source!.ADAL 3.0 PreviewThis library as its name indicates currently in preview as of this writing (e.g. Preview March Refresh) provides a Portable Class Library (PCL) with easy to use authentication functionality for your .NET client on various platforms including Windows desktop, Windows Store, Windows Phone, Xamarin iOS and Xamarin Android by notably taking advantage of Azure AD. Note For more information, see the blog posts ADAL .NET v3 Preview: PCL, Xamarin iOS and Android Support and ADAL v3 Preview – March Refresh.The binaries of the library are available as a NuGet package for the Visual Studio development environment. ADAL for Android 1.0Similarly to the ADAL for .NET library, this library wraps OAuth 2.0 protocols implementation, needed for a native Android app to authenticate with the Azure AD. As such, it provides simple functionality to get token, refresh token, and use cache.The source code is available as open source code on the GitHub.The Azure AD native client for Android sample also available on GitHub shows how to build an Android application that uses the ADAL for Android library to do the interactive OAuth 2.0 authorization code flow with public client.Note For more information, see the blog post Azure Active Directory SDK’s for iOS, Android and OSX.ADAL for iOS 1.0 Similarly to the ADAL for .NET library, this library gives your native iOS application the full functionality of Azure AD, including industry standard protocol support for OAuth 2.0, web API integration with user level consent, and multi-factor authentication support. It also provides simple functionality to get token, refresh token, and use cache.The source code is available as Open Source code on the GitHub. The Azure AD native client for iOS (iPhone/iPad) sample also available on GitHub shows how to build an iOS application that calls a web API that requires an Azure AD account for authentication. This sample uses the ADAL for iOS library to do the interactive OAuth 2.0 authorization code flow with public client.ADAL for JavaScript 1.0The ADAL for JavaScript library 1.0 helps you to use Azure AD for handling authentication in your single page (SPA) applications. This library is optimized for working together with AngularJS.Note For more information, view the Channel 9 video AngularJS Module for Microsoft Azure Active Directory Authentication, or for a deep dive, see the blog post Introducing ADAL JS v1.The source code is available as Open Source code on the GitHub. This Single Page App sample also available on GitHub demonstrates the use of ADAL for JavaScript library for securing an AngularJS based single page application, implemented with an web API backend.Leveraging other librariesThis section covers additional libraries available for developing modern business applications that use Azure AD notably for protecting resources your resources ((multi-tenant) web applications, and web APIs). Beyond these libraries, code samples in other languages are also provided on GitHub. (See later in this document). Azure AD Passport.js plug-inThe extremely flexible and modular Passport authentication middleware for Node.js. can be unobtrusively dropped in to any Express-based or Restify web application. NoteExpress is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications. NoteRestify is a REST framework specifically meant for RESTful web service intentionally borrows heavily from Express as that is more or less the de facto API for writing web applications on top of node.js.A comprehensive set of strategies support various authentication methods. The Azure AD Passport.js plug-in provides a collection of strategies for Azure AD for the OpenID Connect 1.0, WS-Federation, and SAML 2.0 protocols. This plug-in takes care of all of the ugly details of crafting authentication messages, validating tokens from Azure AD, and maintaining user session. All that remains is to give your users a way to sign in, sign out, and gather additional info on the logged in user.This plug-in enables you to integrate your Node.js web application with Azure AD so you can use its many features outlined in this document, including web single sign-on. Note For more information, see the project Azure AD Passport.js plug-in in GitHub.Restify-OAuth2 moduleTo stay with Node.js, the open-source Restify-OAuth2 package available on GitHub provides a very simple OAuth 2.0 endpoint for the aforementioned Restify framework. In particular, it implements the OAuth 2.0 client credentials and resource owner password credentials flows only. Windows Identity Foundation 4.5The Windows Identity Foundation (WIF) 4.5 enables externalizing the identity logic from the application, improving developer productivity, enhancing application security, and enabling interoperability. WIF is now a part of the .NET Framework, and has been updated for .NET 4.5. WIF is typically leveraged by based applications for the WS-Federation protocol support.Note Web applications targeting earlier versions of the .NET Framework (3.5 and 4.0) can take advantage of an earlier version of WIF which was released out of band as a standalone library. This library can be downloaded from the Microsoft Download Center.Note For more information, see the Microsoft MSDN article Windows Identity Foundation.Open Web Interface for .NET (OWIN)OWIN is a specification which describes a standard interface between .NET web servers and .NET applications: by decoupling the two, OWIN makes it possible to write very portable code which is independent from the host it is going to be run on. Note For more information, see the project’s web site.Project Katana is a collection of NuGet packages, which i) makes it possible to run the OWIN middleware on classic IIS and ii) provides various useful features in form of OWIN components.Note For more information, see the article An Overview of Project Katana, the video available on Channel 9 as well as the MSDN Magazine article Getting Started with the Katana Project.It adds the necessary security middleware from the Microsoft OWIN components to handle Azure AD authentication and generate the necessary initialization code to validate incoming tokens according to the Azure AD tenant of choice.As an example, the WS-Federation OWIN middleware (Microsoft.Owin.Security.WsFederation) enables an application to use WS-Federation for authentication. This middleware is available as NuGet package for the Visual Studio development environment. To install the package, run the following command in the Package Manager Console:PM> Install-Package Microsoft.Owin.Security.WsFederationLikewise, the OpenID Connect OWIN middleware (Microsoft.Owin.Security.OpenIdConnect) enables an application to use OpenID Connect for authentication. This middleware is available as NuGet package for the Visual Studio development environment. To install the package, run the following command in the Package Manager Console:PM> Install-Package Microsoft.Owin.Security. OpenIdConnectNoteFor more information on how to use the OWIN components with Azure AD, see the MSDN Magazine article Secure Web API with Azure AD and Microsoft OWIN Components along with the blog posts Using Claims in your Web App is Easier with the new OWIN Security Components, OpenID Connect and WS-Fed OWIN Components: Design Principles, Object Model and Pipeline, and Use OWIN & Azure AD to Secure Both MVC UX and Web API in The Same Project.JSON Web Token Handler for the Microsoft .NET Framework 4.5The package adds the JSON Web token (JWT) format as a first-class citizen in the .NET programming model. The JWT handler indeed provides a collection of classes for deserializing, validating, manipulating, generating, issuing and serializing JWT tokens. It then enables the .NET developers to use the JWT format both as part of existing workloads (such as web single sign-on) and within new scenarios (such as the REST-based solutions made possible by the above ADAL libraries) with the same ease they’d experience when using security token formats supported out of the box, such as SAML 2.0. The JWT handler can be used within the WIF pipeline or standalone, with no direct dependencies on WIF configuration. NoteFor more details on how to use the JWT handler, including some concrete examples, please refer to the blog post Introducing the Developer Preview of the JSON Web Token Handler for the Microsoft .NET Framework 4.5.This package is available as NuGet package for the Visual Studio development environment. To install the package, run the following command in the Package Manager Console:PM> Install-Package System.IdentityModel.Tokens.JwtThe source code of the JWT handler is available on GitHub. Microsoft Token Validation Extension for Microsoft .NET Framework 4.5 The package extends as its name indicates, token validation to check that the signer of a token and the issuer of the token are a valid pair. This capability can be applied both within the WIF token processing pipeline and standalone, without any dependency on WIF’s configuration.This package is available as NuGet package for the Visual Studio development environment. To install this package, run the following command in the Package Manager Console:PM> Install-Package System.IdentityModel.Tokens.ValidatingIssuerNameRegistryAccessing the directory dataLeveraging the Azure AD Graph APIAzure AD provides a query model for applications to access an Azure AD directory tenant. Applications can be cloud, SaaS/multi-tenant, mobile, etc. applications. Applications can also publish information to the directory tenant subject to access control. (This will be later described in this document with the notion of service principal and applications.) For that purpose, and as outline before, Azure AD exposes a directory programming surface for querying and updating the directory, and thus sustaining the identities lifecycle management as a whole via a RESTful API called Azure AD Graph API. Note For more information, see the Microsoft MSDN article Azure AD Graph API. This primary directory access protocol supports today the management of users, groups, etc. as well as service licensing and directory tenant administration. It represents a new way for application to connect to the directory through the use of REST/HTTP interfaces.For that purposes, Azure AD publishes a tenant-specific Azure AD Graph API endpoint as follows: domain name>/<entity>?api-version=<version>[&<filter>]Where:<tenant domain name> can be: A registered domain name of an Azure AD directory tenant, for example corpfabrikam..The immutable tenant id of the domain, such as 90995f16-6b12-4032-8b87-fd59566ed917 Such as: ; represents a specific entity type, such as users, groups, contacts, tenantDetails, roles, devices, applications, etc.<version> is the Azure AD Graph API version. Since the general availability, and as of today, the following four versions are supported: 2013-04-05, 2013-11-08, 1.5, 1.6, beta.The beta version provides an endpoint where you can try out the latest preview features, and provide Microsoft with feedback, Note For more information, see the Microsoft MSDN articles Azure AD Graph API Versioning and Graph API versioning and the new beta version.<filter> is optional OData query arguments (see below). An authorized application via OAuth 2.0 can then operate with the obtained access token on information in the directory through a URL such as: Azure AD Graph API supports CRUD operations.Note For a list of common queries with your directory tenant see the MSDN article Azure AD Graph Common Queries.Note The Azure AD Graph API provides full text search capabilities in preview. Until now, searching Azure AD entities was limited to $filter searches and had a number of limitations developers found constraining. With this preview functionality, more powerful search mechanisms are added to the Graph API.??For more details, see the blog post Full Text Search Capabilities in Azure AD Graph API (preview).Note The Microsoft MSDN Azure AD Graph REST APIs reference enables you to try out some of the available operations (currently only on user and group entities, and the me alias) and see the request and responses inline, right from within the online documentation.Note Activity and Events Reporting data of your Azure AD tenant is now available in preview to developers through the Azure AD Graph API.??For more details, see the blog post Announcing the preview of Graph Reports and Events API, the Microsoft MSDN article Azure AD Reports and Events (Preview), as well as the articles Azure AD access and usage reports and Getting started with the Azure AD Reporting API.For testing purposes of the various capabilities, you can use the Graph Explorer application that enables you to run queries against a demo domain GraphDir1. without the need to obtain an access token. This application acts as a wrapper on top of Azure AD Graph API. For that reason, the API version isn’t required in the URL.Interestingly, the app provides a support for the /me and /myorganization aliases: You simply need to click Use Demo Company, to type in your request, and press ENTER to see the result below. (To help you if needed, the app has autocomplete capability for entities.)As an example, the following URL: direct access to objects, here a user, in the directory tenant. For example, an HTTP GET to this URL will provide the following JSON response (abbreviated for readability):{ "odata.metadata": "$metadata#directoryObjects/Microsoft.WindowsAzure.ActiveDirectory.User/@Element", "odata.type": "Microsoft.WindowsAzure.ActiveDirectory.User", "objectType": "User", "objectId": "3fe5689d-323a-4920-b2fb-07148723a541", "accountEnabled": true, "assignedLicenses": [ { "disabledPlans": [], "skuId": "078d2b04-f1bd-4111-bbd4-b4b1b354cef4" } ], "assignedPlans": [ { "assignedTimestamp": "2014-12-22T15:17:56Z", "capabilityStatus": "Enabled", "service": "MultiFactorService", "servicePlanId": "8a256a2b-b617-496d-b51b-e76466e88db0" }, { "assignedTimestamp": "2014-12-22T15:17:56Z", "capabilityStatus": "Enabled", "service": "AADPremiumService", "servicePlanId": "41781fb2-bc02-4b7c-bd55-b576c07bb09d" } ], "city": null, "country": null, "department": null, "dirSyncEnabled": null, "displayName": "Philippe Beraud", "facsimileTelephoneNumber": null, "givenName": "Philippe", "jobTitle": null, "lastDirSyncTime": null, "mail": null, "mailNickname": "philber", "mobile": "+33 157751234", "otherMails": [ "philber@fabrikam.fr" ], "passwordPolicies": "None", "passwordProfile": null, "physicalDeliveryOfficeName": null, "postalCode": null, "preferredLanguage": "en-US", "provisionedPlans": [], "provisioningErrors": [], "proxyAddresses": [], "state": null, "streetAddress": null, "surname": "Beraud", "telephoneNumber": null, "usageLocation": "FR", "userPrincipalName": "philber@corpfabrikam."}This kind of Internet-friendly interface makes it easy for developers - building on any platform to integrate their applications with Azure AD. Using standard HTTP requests, a developer can access any “thing” in the directory (for instance, users), and they can access relationships between things. Continuing with the example above, you can see that it is easy to access a user’s groups by using the URL: ?Sending an HTTP GET to this URL would return the following JSON response (abbreviated for readability) that provides a list of groups for the user who’s the user principal name (UPN) is philber@corpfabrikam.:?{ "odata.metadata": "$metadata#directoryObjects", "value": [ … { "odata.type": "Microsoft.WindowsAzure.ActiveDirectory.Group", "objectType": "Group", "objectId": "66c1ac42-2df3-4645-8947-a8973afb6cfc", "description": "Engineering Team", "dirSyncEnabled": null, "displayName": "Engineering", "lastDirSyncTime": null, "mail": null, "mailNickname": "BposMailNickName", "mailEnabled": false, "provisioningErrors": [], "proxyAddresses": [], "securityEnabled": true }, … ]}Because Azure AD Graph API is built using standard REST semantics, NO special protocols or libraries are necessary to access your directory tenant information. HTTP is enough.Furthermore, Azure AD Graph API supports differential query requests. A differential query request returns all changes made to specified entities during the time between two consecutive requests. For example, if you make a differential query request an hour after the previous differential query request, only the changes made during that hour will be returned. This functionality is especially useful when synchronizing directory tenant data with an application’s data store.A differential query request URL is created by appending deltaLink in the query string to the tenant-specific endpoint: domain name>/<entity>?api-version=<version>&deltaLink=Such as: The deltaLink parameter with no assigned value indicates that this is an initial differential query request. Differential query paged responses contain all changes that occurred on the tenant until last page of changes is returned:{? "odata.metadata": "$metadata#directoryObjects",?? "aad.nextLink": "... [Truncated]",? "value": [??? {????? "odata.type": "Microsoft.WindowsAzure.ActiveDirectory.User",????? "objectType": "User",????? "objectId": "dca803ab-bf26-4753-bf20-e1c56a9c34e2",????? "accountEnabled": true,????? "displayName": "John Smith",????? "givenName": "John",????? "mailNickname": "johnsmith",????? "passwordPolicies": "None",????? "surname": "Smith",????? "usageLocation": "US",????? "userPrincipalName": "johnsmith@corpfabrikam."??? }? ]}The aad.nextLink property indicates that there are more changes on the tenant and that the application should perform subsequent differential query request right away and pass aad.nextLink property value from the response as?deltaLink parameter value:... [Truncated]?When sending an HTTP GET to this URL, if the response contains aad.deltaLink property, it indicates that no more changes exist on the directory tenant.{? "odata.metadata": "$metadata#directoryObjects",? "aad.deltaLink": "... [Truncated]", "value": [??? {????? "odata.type": "Microsoft.WindowsAzure.ActiveDirectory.Group",????? "objectType": "Group",????? "objectId": "7373b0af-d462-406e-ad26-f2bc96d823d8",????? "description": "IT Administrators",????? "displayName": "Administrators",????? "mailNickname": "Administrators",????? "mailEnabled": false,????? "securityEnabled": true??? }? ]}Subsequent?differential query response will?contain no changed entities until more changes are made on the tenant.NoteFor more information, see the MSDN article Azure AD Graph Differential Query. The approach of using standard REST interfaces to operate over a graph containing entities (nodes) and relationships (arcs) between entities - often referred to as a graph interface - is very common on the Internet nowadays. ?NoteFor more information on networks and graphs, we advise you reading the book entitled Networks, Crowds, and Markets: Reasoning About a Highly Connected World published by Cambridge University Press.Developers can build on this simple direct URL based access to take advantage of the sophisticated filtering and metadata operations that are available via Open Data Protocol (OData). ?NoteFor more information, see the blog post Enhancing Graph API queries with additional OData supported queries.OData is a very rich protocol, and not all of it is applicable to the directory – the directory supports a subset. The directory publishes it schema and the attributes that can be used in filter expressions for scale and performance reasons.Built on standards such as HTTP, JSON and AtomPub, OData is a web protocol for unlocking and sharing data — freeing it from silos that exist in some software applications today. The OData protocol supports serialization in multiple popular formats, including JSON and Atom/XML. With OData, developers are able to build cross-platform Web and mobile applications. It benefits from a strong ecosystem of OData producers, consumers and libraries — several of them open source — including Java, PHP, Drupal, Joomla, Node.js, Microsoft .NET, etc.The OData protocol initially released under the Microsoft Open Specification Promise to allow anyone to freely interoperate with OData implementations is now an OASIS standard (from the OASIS Open Data Protocol (OData) TC). This allows to benefit from an open data protocol for sharing data and exposing data models interoperable on the Web:"To accomplish the goal of open data for the open Web, we have seen a push for support to enable access to and use of data across platforms, applications and devices. Taking steps to standardize OData through OASIS allows developers to act on the data in a more well-defined way."Jean Paoli, Président de Microsoft Open Technologies Inc.We are convinced that developers will find the Azure AD Graph API straightforward to write applications that integrate with Azure AD and also potentially with other cloud solutions that operate with graph interfaces. The article Using the Graph API to Query Azure AD describes how to build a web application that uses the Azure AD Graph API to query directory entities.Leveraging the Azure AD Graph API custom schema extensionStarting with version 1.5, Azure AD Graph API supports custom schema extensibility capability that allows augmenting existing object with additional custom attributes without requiring an external data store. A common example may consists in storing a payroll number for the user.For that purpose, Azure AD Graph API provides REST interfaces for an application to register, unregister, enumerate, read, write, and filter by extension properties. As of this writing, the User, Group, TenantDetail, Device, Application and ServicePrincipal objects can be extended with “Binary”, “Boolean”, “DateTime”, “Integer”, “LargeInteger”, and “String” type single-valued attributes. Extension properties are registered on the Application object that corresponds to the application within the directory via the following URL: domain name> can be: A registered domain name of an Azure AD directory tenant, for example corpfabrikam..The immutable tenant id of the domain, such as 90995f16-6b12-4032-8b87-fd59566ed917 Such as: object Id> represents the GUID of the Application object that registers the extension property.For example, to register the above payroll number in application whose GUID is 269fc2f7-6420-4ea4-be90-9e1f93a87a64 in the domain corpfabrikam., you simply do a POST as follows:POST HTTP/1.1{ "name": "payrollNumber", "dataType": "String", "targetObjects": [ "User" ]}The application must be granted write access to register an extension property. 100 extension properties (across ALL types and ALL applications) can be written to any single object.If the operation was successful, it will return an HTTP 201 Created status code along with the fully-qualified extension property name, which can be used for writing values to the target type:HTTP/1.1 201 Created...{ "odata.metadata": "$metadata#directoryObjects/Microsoft.WindowsAzure.ActiveDirectory.ExtensionProperty/@Element", "odata.type": "Microsoft.WindowsAzure.ActiveDirectory.ExtensionProperty", "objectType": "ExtensionProperty", "objectId": "dc893d45-a75b-4ccf-9b92-ce7d80922aa7", "name": "extension_ab603c56068041afb2f6832e2a17e237_payrollNumber", "dataType": "String", "targetObjects": [ "User" ]}The property is added to the target directory type and becomes immediately accessible in the directory. For a multi-tenant application, when the application is granted consent by a user in another organization (see later in this document), the extension properties become immediately accessible on the target directory type in the other organization’s directory. If an organization consents to “read only” permissions for an application with registered extensions, the properties will still become accessible in the other organization’s directory. Additionally, extension properties are accessible by any consented application in an organization, not just for the application to which they are registered. Other consented applications in that organization can read or write values for the new extension property if they have sufficient permissions.If the application is deleted or consent is removed in the other organization’s directory, the extension property is removed on the target directory object. If the extension is deleted by the application, it is removed on the target directory object. If a multi-tenant application adds additional extension properties after consent was granted, these properties will also become immediately accessible in the other organization’s directory.The two samples available on GitHub cover the use extension properties:WebApp-GraphAPI-DirectoryExtensions-PHP. This sample PHP application calls the Azure AD Graph API to manage Azure AD custom schema extensions. It demonstrates how to first register new extensions, then shows the application reading, updated and deleting values in the Extension attribute.WebApp-GraphAPI-DirectoryExtensions-DotNet. This sample MVC application queries the Azure AD Graph API to generate a simple company organization chart. Managers and Direct Reports are represented as links, and can easily be queried to show an organization's management structure. It allows reading extension values right out of the box.Note For more information, see the Microsoft MSDN article Azure AD Graph API Directory Schema Extensions.Leveraging the Azure AD Graph Client LibraryThe Azure AD Graph API Client Library represents a client library as its name indicates intended for the?Azure AD Graph API?that provides read, write, update, and delete methods for the various Azure AD entities like users, groups, group membership, roles, tenant information, service principals, applications, etc.This library is available as NuGet package for the Visual Studio development environment. To install the package, run the following command in the Package Manager Console:PM> Install-Package Microsoft.Azure.ActiveDirectory.GraphClientThe following two samples available on GitHub cover the use of the library:ConsoleApp-GraphAPI-DotNet. This sample console application uses the Graph API Client library to demonstrate common read calls to the Azure AD Graph API. The second part of the sample app demonstrates common write, update, and delete options on users, groups, and shows how to execute user license assignment, updating a user's thumbnail photo and links, etc. WebApp-GraphAPI-DotNet. This sample MVC Web application shows how to make RESTful calls to the Azure AD Graph API to access Azure Active Directory data. Beyond this library, it includes use of the aforementioned OWIN libraries to authenticate/authorize using Open ID connect.Supporting automatic provisioning (Azure AD Premium only)The Premium edition of Azure AD provides an automatic account provisioning capability that is as of this writing in preview. This capability is based on the support of the Cross-domain Identity Management (SCIM) 2.0 standard, i.e. an open API for managing identities and provisioning workloads.NoteFor more information, see the blog posts Azure AD Premium now supports SCIM 2.0! and Azure AD: Helping you adding SCIM support to your applications.Such a capability can be used with an application to enable beyond single sign-on an automatic user provisioning for an application. For that purpose, the application must provide or be fronted by a SCIM-based fa?ade/web service. In other words: The application can support SCIM right out-of-the-box. If such an application us capable of accepting an access token from Azure AD, it will work with Azure AD of the box.- or -A SCIM-based fa?ade can be built to translate between Azure AD’s SCIM endpoint and whatever API, interface, or mechanism the application supports for user provisioning.NoteTo ease the development, Common Language Infrastructure (CLI) libraries are provided as a NuGet package (Microsoft.SystemForCrossDomainIdentityManagement) to build a SCIM endpoint and translate SCIM messages. In addition, a series of sample code packages to implement a SCIM-based provisioning fa?ade and demonstrate the automatic provisioning capability is available on GitHub. Theses sample code packages illustrate how to use the CLI libraries with "Bringing Your Own Application" (BYOA) for the provisioning scenarios.NoteFor more information, see the article Using SCIM to enable automatic provisioning of users and groups from Azure Active Directory to applications.Leveraging the various available code samples on GitHubMicrosoft provides a full suite of sample applications and documentation on GitHub at to help you get started with learning the Azure AD system. As illustrated in the previous pages, this includes tutorials for native clients such as Windows, Windows Phone, iOS, OSX, Android, and Linux. Interestingly enough, full walkthroughs for authentication flows such as OAuth 2.0, OpenID Connect 1.0, Azure Graph API, etc. are also provided. The Microsoft MSDN article Azure Active Directory Code Samples links you to these code samples that show you how it's done and code snippets that you can use in your applications. On the code sample page on GitHub, you'll find detailed read-me topics that help with requirements, installation and set-up. And the code is commented to help you understand the critical sections.NoteTo understand the basic scenario for each sample type, see the Microsoft MSDN article Authentication Scenarios for Azure AD.Adding a web application for Single Sign-On (SSO) (and more)Applications – both composite single tenant type and the multi-tenant SaaS applications are first class citizens in the Azure AD directory tenant. Applications you’re developing can be easily integrated with your directory and granted access to that directory so that you can easily provide single sign-on capabilities (sign in and sign out), manage the user authorization, etc. without the additional cost, burden, and hassle of having to acquire and manage new user credentials. If you’re a developer or a cloud ISV, you can allow for external users a web application that you've previously registered in your Azure AD directory and consequently make it available with one click for use by any other Azure AD customer. With one click, those customers can in turn add your application to their own tenant giving it a clearly called out set of privileges. They get the benefit of using Azure AD to administer access to your application. You get the benefit of offering world class enterprise directory capabilities that can be easily connected to your customers existing on-premises directory infrastructure. This section details the registration process in directory tenant(s) and how to (build and) configure such applications to provide sign up for multi-tenant applications, single sign-on, and more.Adding a single tenant web applicationWeb applications are by far the most popular business application types. From corporate portals to collaboration solution, including custom LOB web applications, the ease of distribution (no client distribution required), the flexibility of the application updates and the user familiarity with the browser put this application model firmly on top of the list.The topology is the usual: there is a web front-end of some sort which relies on some sort of middle-tier in Azure or in another cloud (connected to the on-premises infrastructure).For all of those aforementioned applications, whatever they are, the ability to sign-in a user is an essential identity service. However, while essential, it is typically perceived by both end users and developers as a “speed bump” the user must cross before being productive. Emphasis is thus placed on making sign-in unobtrusive but without compromising security. The support for Azure AD can essentially be seen as an exercise in adding incremental capability.The integration of your single tenant web application with your directory entails three steps:Registering the web application in your directory,Configuring a web project for single sign-on (and single sign-out) support with Azure ADQuerying your directory data using the Azure AD Graph API.The following sections further describe each step. Registering the web application in your directory In order to establish single sign-on between your web application and your directory tenant, your web application needs to be “registered” to your directory to gain access to it – this is a common practice accessing protected services.In effect, in a directory, and as covered in the white paper Active Directory from on-premises to the Cloud, every entity that can be accessed is defined as a security object (a user account for example) and every entity that can actively access those objects is represented as a principal.Consequently, each web application that needs to access a directory tenant must have a principal, more specifically a service principal, associated with it in that directory. The service principal represents an instance of the web application, or in the case of multi-tenant application (see later in this document), a logical instance of the application. The web applications will later use this service principal to authenticate itself when it will try to access your directory.Service principals are completely analogous to users in that: They are identified by a fixed naming schema, i.e. a service principal name (SPN), much like users are identified by a user principal name (UPN). Azure AD uses here a comparable naming schema as the one used in Active Directory where the SPN helps to identify a specific service class/type, where it is running, and so on.The SPN is a multi-valued attribute of the principal object. The SPN value also referred as an identifier URI (ID URI), is a logical identifier that represents the web application and its host. It will be used as part of the application’s service principal. It does not need to resolve to an Internet address and you can derive its value from what you know about the web application you are provisioning.As a result, such an ID URI can be considered as logically having up to 3 parts: service class/hostname[@tenant domain name] as explained below:The service class that represents the (type of the) application. This parallels the notion of service class in the SPN model for WSAD.The hostname that identifies a unique instance (or deployment) of the cloud application. This parallels the notion of hostname in the SPN model for WSAD. This is the hostname of the web application, for example for an app being developed in Visual Studio, <your application>. for an web application hosted on Azure Web Apps, etc. NoteWhen using SSL/TLS connections, the hostname is also the identity that the web application can prove to the client by means of an SSL/TLS certificate. In many cases, bearer security tokens are used to access protected resources. Since these tokens do not carry proof of possession keys, they are susceptible to man-in-the-middle replay attacks. An attacker fools the client into obtaining a token and handing it to the attacker who them immediately replays it to the real protected resource and obtains access to that resource. The use of the hostname in service principals, and requiring it to be sent to the Azure AD STS, when requesting a security token, provides a means of verifying that a particular web application effectively resides at that hostname. The client must also verify, via SSL/TLS, that the target service is using the same hostname.The tenant domain name component that identifies the directory of the web application when accessing a multi-tenant application. This said, at the simplest form if you don’t want to adhere to the above schema, the ID URI’s value can be just the web application endpoint, i.e. the URL of a web page where users can sign in and use the web application.There are a set of credentials on the principal. A client ID along with a secret symmetric key that is shared between the Azure AD STS (login. or for backward compatibility login.) for the realm and the web application are used as a credentials. The domain owner has control over the key that is used to authenticate the service principal.A service principal belongs to a set of Azure AD roles that determines what the application is allowed to do in terms of directory access (single sign-on, single sign-on + read access, and single sign-on + read/write access).A service principal can be enabled or disabled much like users. If a service principal is disabled, then the Azure AD STS refuses access tokens to the service and thus access to the service is disallowed. The account is also not allowed to authenticate to any other service.A web application can specify its own principal, using its ID URI, when it is acting as a client to access a web API in the context of its service principal. (See later in this document).Finally, a service principal has a reply URL associated with it. To prevent security exposure when using browser authentication flows, this service principal address is indeed required on the service principal, so that the Azure AD STS can verify that the reply URL supplied in the query string (such as the wreply parameter in the WS-Federation protocol) matches the service principal address in the service principal; otherwise the browser authentication flows as per WS-Federation, SAML 2.0, or OpenID Connect 1.0 protocols are open to an elevation of privilege attack. The reply URL is the application endpoint that the user will be redirected to after the single sign-on is complete; for example, for an app being developed in Visual Studio, for an web application hosted on Azure Web Apps, etc.The directory tenant administrator creates the service principal at behest of developer. When Azure AD was first launched, the only way to provision service principals in your directory tenant was by using the Azure AD Module for Windows PowerShell cmdlets. With the General Availability (GA) release, Azure AD introduced a further abstraction level, which decouples high level application definition operations from the low-level provisioning of service principals.An object of type Application now describes the main application coordinates (such as the app ID URI to identify the app and the URL to use for web single sign-on, etc.) along with some configuration settings (such as the directory access level).The Application object serves as a blueprint for creating a service principal in the directory for the web application, the service representing an instance of the web application. The application object was largely made available to ease things in multi-tenant application scenarios. (More on this later in this document. Thus, the service principal will have the same above coordinates (ID URI, URLs, etc.) as the corresponding Application object instance as well as the directory access level you’ve established at creation time. Note For more information, see the Microsoft MSDN article Application Objects and Service Principal Objects.With a few simple steps, you can add your web application under the APPLICATIONS tab in the ACTIVE DIRECTORY section of the Azure Management portal.Note For more information, see the MSDN article Adding, Updating, and Removing an App .To add your web application, and thus creating the application and the service principal objects in the directory, proceed with the following steps:Sign into the Azure management portal as the administrator of the directory to configure.Click ACTIVE DIRECTORY on the left menu, and then click the name of the organization’s directory for which you want to register the web application.On the top menu, click APPLICATIONS. If no apps have been added to your directory, this page will only show the ADD AN APP link. Click on the link, or alternatively you can click ADD at the tray of the bottom. A What do you want do? dialog brings up.Click Add an application my organization is developing.On the Tell us about your application page, specify a name for your web application. This used as human-readable moniker to refer to the application. Select WEB APPLICATION AND/OR WEB API. Click the arrow icon on the bottom-right hand corner of the page.On the App properties page, provide the URL of a web page where users can sign in and use the web application in APP URL, and the ID URI to use to logically identify the web application in APP ID URI, then click the check mark icon on the bottom-right hand corner of the page.You are redirected to the Quick Start page for the web application. Different options are displayed on how to add additional capabilities to the web application. You can now begin updating your web application to enable users to sign in, access web APIs in other applications, or configure a multi-tenant application, which allows other organizations to access your web application (see later in this document)By default, the newly created web application is configured to allow users from your directory to sign in to the application.Configuring a web project for single sign-on (and single sign-out) support with Azure ADThis section focusses on the protocol and coding aspects of the web project to support single sign-on (and single sign-out).The next step consists in establishing a trust relationship between the web application and the single sign-on endpoint of the directory, which is one of the tenant-specific endpoints exposed by the Azure AD STS.As previously described, the relevant tenant-specific federation metadata documents and the related endpoint(s) differ from one protocol to another. The next sections consider the WS-Federation, the SAML 2.0, and the OpenID Connect 1.0 protocols for the web project to configure.Using the directory coordinates to configure the web project with WS-federationA tenant-specific federation metadata document is published via a single discovery endpoint to integrate your directory into the application you’re developing: domain name>/FederationMetadata/2007-06/FederationMetadata.xmlFor example, our directory corpfabrikam. (90995f16-6b12-4032-8b87-fd59566ed917) corresponds to: For backward compatibility, the login. based discovery endpoint is still exposed: domain name>/FederationMetadata/2007-06/FederationMetadata.xmlThe above endpoint is listed in FEDERATION METADATA DOCUMENT URL in ENABLE USERS TO SIGN ON in the Quick Start page for the web application.The tenant-specific federation metadata includes information about the tenant, including tenant-specific issuer and endpoint information. Web applications that restrict access to a single tenant use tenant-specific endpoints.Any web application that supports the WS-Federation protocol can consume these metadata to ease the trust configuration on its side. For example, based applications typically leverage for that purpose the Windows Identity Foundation (WIF) pipeline or now the WS-Federation OWIN middleware.To view the related tenant-specific endpoints exposed for your web application, proceed with the following steps:On the Quick Start page for the web application, click VIEW ENDPOINTS at the tray of the bottom. An App Endpoints dialog brings up.Click the checkmark icon on the bottom-right corner of the page.Various developer tooling automates the establishment of the trust on the web application side based on the above federation metadata.As an example, for developers using Visual Studio 2012, the Identity and Access Tool for Visual Studio 2012 can be leveraged with based web project for configuring the web project for Azure AD sign on. The tool can be downloaded and installed from the Visual Studio Gallery.It indeed enables you to secure your based web application with claims based identity and accept users from your directory tenant. This extension adds a context sensitive project Identity and Access... menu entry within Visual Studio 2012 to easily add such identity capabilities to your web application. This provides you with capabilities for developing and testing your application with a local development STS, connecting to Azure AD in the context of this paper. It does this by updating the web.config file with the proper settings to enable WIF in the Microsoft .NET Framework 4.5 and adding the necessary configuration for your directory based on the aforementioned federation metadata. The realm you specify in the wizard for your application should match the app ID URI value you enter when creating the application otherwise the token will be rejected by the web application.Similarly, for developers using Visual Studio 2013, the and Web Tools for Visual Studio 2013 extends the project templates and tooling experience to integrate Azure AD authentication and management features right at project creation time. The and Web Tools for Visual Studio 2013 are bundled in the main installer of along with the Web Platform Installer (WebPI) for installation.Once installed, when you create a new project, Visual Studio 2013 offers several authentication options for the Web Forms, MVC, and Web API templates, the default option being the Individual User Accounts, i.e. an Identity (formerly known as membership).To configure your web project for using your Azure AD directory’s organizational accounts, proceed with the following steps: Click Change Authentication. An eponym Change Authentication dialog brings up.Select Organizational Accounts on the left side.Select Cloud – Single Organization to enable authentication for user accounts that are defined in your directory tenant, for example, the corpfabrikam. tenant in our illustration.In Domain, enter the domain that you want to set up the web application in, for example, the default domain corpfabrikam. in our illustration. If you have defined in your directory a custom federated Internet domain such in lieu of corpfabrikam., you can specify that domain. In Access Level, if your web application needs to query or update directory information by using the Azure AD Graph API, choose Single Sign-On, Read Directory Data or Single Sign-On, Read and Write Directory Data. Otherwise, choose Single Sign-On.By default, the template creates an application ID URI for you by appending the project name to the specified domain. For example, if the project name is WebApp and the domain is corpfabrikam., the application ID URI becomes you want to manually specify the application ID URI, expand More Options.Enter the application ID URI in the text box. The application ID URI must begin with “https://”.Note By default, if an application that is already provisioned in the directory – as we’ve done above - has the same application ID URI as the one that Visual Studio 2013 is using for the project, the web project will be connected to the existing application instead of provisioning a new one. If you want a new application to be provisioned in that case, clear Overwrite the application entry if one with the same ID already exists. If you clear the check box is cleared, and Visual Studio finds an existing application with the same application ID URI, it creates a new URI by appending a number to the URI it was going to use. With the above illustration, a new application will be provisioned with an application ID URI like /WebApp_20131213330903.Click OK. An ADAL Sign in dialog brings up.Important noteYou must sign in with an organizational account: the and Web Tools for Visual Studio 2013 can create for you the entry in your directory, and to do so, the tools invoke the Azure AD Graph API and use it to write the necessary entities in the directory. That requires the tools to access the Graph as a Global Administrator in the tenant. For more information, see the blog post Setting Up an Project with Organizational Authentication Requires an Organizational Account.Enter the credentials for your organizational account with administrative privileges and click Sign in. Once authenticated and the application configured in the directory, the Change Authentication dialog closes and the web application is fully configured for validating SAML security tokens issued by Azure AD for your authenticated directory’s organizational accounts.Click OK to finalize the configuration of the web project.As illustrated above, the wizard simplifies the configuration and makes it really very simple to enable single sign-on for your web application using your directory. You just need to specify your directory and authenticate accordingly.Press F5 to run the project in debug mode When redirected to the Azure AD sign-in page, sign in with your organizational account.Note If you have configured company branding in your Azure AD tenant, the sign-in page starts by showing a generic branding, then fades in your organization’s branding after users enter their username. You can “accelerate” users to your organization’s sing-in page by passing a domain hint to Azure AD, effectively stating “I’ve already established that the user who’s about to sign in is from <this organization>.” To do this with the WS-Fed protocol, you simply need to add the following query string parameter to the sign-in URL “&whr=” where is the realm of the users who are expecting to sign in. For additional information, see the blog post Using Azure AD to land users on their custom login page from within your app. This blog post also discusses what you will have to with the SAML 2.0 and the OpenID Connect 1.0 protocols as covered later in this document. And voilà.The auto-generated configuration is all you need for taking advantage of Azure AD for web single sign-on with your web application: you don’t need to write any authentication-specific code in the application itself. NoteFor more information, see the blog post Easy Web App Integration with Azure Active Directory, & Visual Studio. Important noteThe above tooling leverages the legacy login. based endpoints as they have been shipped before the change occurs. The forthcoming release of Visual Studio 2015 will bring similar capabilities with new 4.6 projects templates and tools. NoteFor more information, see the blog post Identity Updates for Web Developers in Visual Studio 2015 CTP6. From a protocol perspective, the flow is as follows:Once configured, when a user signs in to the web application with their organizational account, such as by clicking the above sign-in button, the user's browser will be redirected to the Azure AD STS for your organization’s realm. Once signed in, the Azure AD STS will return a sign-in response to the application such as in our configuration with the WS-Federation protocol:Redirection to , And then redirection to . The sign-in response to the application conveys a security tokens that contains a collection of claims, aka attributes describing the current user as asserted by the authority that authenticated him/her. Azure AD issues a fixed set of claims for the authenticated users. Below there’s a quick reference of all the claims you can expect from Azure AD:Tenant ID. Immutable tenant identifier:: 90995f16-6b12-4032-8b87-fd59566ed917Name. For display only:: philber@corpfabrikam.First Name. For display only:: PhilippeLast Name. For display only:: BeraudObject ID. Immutable security identifier:: 85143067-d315-4c23-b1b6-a2a33a4f0d9bNote For more information, see the Microsoft TechNet article Supported Token and Claim Types.Starting from .NET 4.5, every identity in .NET is represented with a ClaimsPrincipal. With WIF as being possibly used here, the ClaimsPrincipal is constructed during the validation of the incoming SAML security token issued by Azure AD and presented to the application at sign-in time. Every ClaimsPrincipal contains a collection of claims, reflecting the claims received in the tokens. Thus, you can easily query the claims in the ClaimsPrincipal.Current if you want to access user identity’s information.Similarly to WIF and the above illustration of the experience with the and Web Tools for Visual Studio 2013, the aforementioned WS-Federation OWIN middleware (Microsoft.Owin.Security.WsFederation) provides a great level of abstraction to construct a ClaimsPrincipal.Current based on the WS-Federation sign-in response. NoteFor more information, see the blog post Using Claims in your Web App is Easier with the new OWIN Security Components.After being initialized by simply passing to it the App ID URI of the application and the URL of the Azure AD tenant where the web application is registered, the middleware takes care of:Downloading the above Azure AD metadata, finding the signing keys, and finding the issuer name for the tenant.Processing the WS-Federation sign-in response by validating the SAML security token (signature, issuer, and audience), extracting the user's collection if claims, and putting it on ClaimsPrincipal.Current.Integrating with the session cookie OWIN middleware (Microsoft.Owin.Security.Cookies) to establish a session for the user.Note For more information, see the blog post WS-Federation in Microsoft OWIN Components–a quick start.A ready-to-use sample code available on GitHub describes how to build a single tenant web MVC application with the WS-Federation OWIN middleware.Note PHP developers who want to use the WS-Federation for their applications cans refer to the article Web Single Sign-On with PHP and Azure Active Directory. The related code source is available on GitHub. Likewise, Java developers can refer to the article Web Single Sign-On with Java and Azure Active Directory. The related code source is also available on GitHub.The next two sections provide additional information regarding the use of the SAML 2.0 or the OpenID Connect 1.0 protocols in lieu of WS-Federation.Using the directory coordinates to configure the web project with SAML 2.0A tenant-specific federation metadata document is published via a single discovery endpoint to integrate your directory into the web application you’re developing with SAML 2.0: domain name>/FederationMetadata/2007-06/FederationMetadata.xmlFor example, our directory corpfabrikam. (90995f16-6b12-4032-8b87-fd59566ed917) corresponds to: This is the same endpoint as the one discussed above with WS-Federation. Likewise, for backward compatibility, the login. based discovery endpoint is still exposed.The tenant-specific federation metadata includes information about the tenant, including tenant-specific issuer and endpoint information. Applications that restrict access to a single tenant use tenant-specific endpoints.Similarly to WS-Federation, any web application that supports the SAML 2.0 protocol can consume these metadata to ease the trust configuration on its side. In terms of configuration, the entityID value in the federationmetadata.xml XML metadata file will map to the issuer in the SAML 2.0 response from your Azure AD directory tenant. <?xml version="1.0" encoding="utf-8"?><EntityDescriptor ID="_822e7d2a-2dc5-49bb-ad27-54255cec5e59" entityID="" xmlns="urn:oasis:names:tc:SAML:2.0:metadata">...</EntityDescriptor>This value is ““ in our illustration.Likewise, you will find at the end of the document information related to SAML 2.0 under the IDPSSODescriptor element and notably the SAML 2.0 sign-on and sign-out endpoints:<?xml version="1.0" encoding="utf-8"?><EntityDescriptor ID="_822e7d2a-2dc5-49bb-ad27-54255cec5e59" entityID="" xmlns="urn:oasis:names:tc:SAML:2.0:metadata">... <IDPSSODescriptor protocolSupportEnumeration="urn:oasis:names:tc:SAML:2.0:protocol"> <KeyDescriptor use="signing"> <KeyInfo xmlns=""> <X509Data> <X509Certificate>MIIDPjCCAiqgAwIBAgIQsRiM0jheFZhKk49YD0SK1TAJBgUrDgMCHQUAMC0xKzApBgNVBAMTImFjY291bnRzLmFjY2Vzc2N vbnRyb2wud2luZG93cy5uZXQwHhcNMTQwMTAxMDcwMDAwWhcNMTYwMTAxMDcwMDAwWjAtMSswKQYDVQQDEyJhY2NvdW50cy5hY2Nlc3Njb250cm9 sLndpbmRvd3MubmV0MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAkSCWg6q9iYxvJE2NIhSyOiKvqoWCO2GFipgH0sTSAs5FalHQosk 9ZNTztX0ywS/AHsBeQPqYygfYVJL6/EgzVuwRk5txr9e3n1uml94fLyq/AXbwo9yAduf4dCHTP8CWR1dnDR+Qnz/4PYlWVEuuHHONOw/blbfdMjh Y+C/BYM2E3pRxbohBb3x//CfueV7ddz2LYiH3wjz0QS/7kjPiNCsXcNyKQEOTkbHFi3mu0u13SQwNddhcynd/GTgWN8A+6SN1r4hzpjFKFLbZnBt 77ACSiYx+IHK4Mp+NaVEi5wQtSsjQtI++XsokxRDqYLwus1I1SihgbV/STTg5enufuwIDAQABo2IwYDBeBgNVHQEEVzBVgBDLebM6bK3BjWGqIBr BNFeNoS8wLTErMCkGA1UEAxMiYWNjb3VudHMuYWNjZXNzY29udHJvbC53aW5kb3dzLm5ldIIQsRiM0jheFZhKk49YD0SK1TAJBgUrDgMCHQUAA4I BAQCJ4JApryF77EKC4zF5bUaBLQHQ1PNtA1uMDbdNVGKCmSf8M65b8h0NwlIjGGGy/unK8P6jWFdm5IlZ0YPTOgzcRZguXDPj7ajyvlVEQ2K2ICV TYiRQqrOhEhZMSSZsTKXFVwNfW6ADDkN3bvVOVbtpty+nBY5UqnI7xbcoHLZ4wYD251uj5+lo13YLnsVrmQ16NCBYq2nQFNPuNJw6t3XUbwBHXpF 46aLT1/eGf/7Xx6iy8yPJX4DyrpFTutDz882RWofGEO5t4Cw+zZg70dJ/hH/ODYRMorfXEW+8uKmXMKmX2wyxMKvfiPbTy5LmAU8Jvjs2tLg4rOB cXWLAIarZ </X509Certificate> </X509Data> </KeyInfo> </KeyDescriptor> <KeyDescriptor use="signing"> <KeyInfo xmlns=""> <X509Data> <X509Certificate>MIIC4jCCAcqgAwIBAgIQQNXrmzhLN4VGlUXDYCRT3zANBgkqhkiG9w0BAQsFADAtMSswKQYDVQQDEyJhY2NvdW50cy5hY2N lc3Njb250cm9sLndpbmRvd3MubmV0MB4XDTE0MTAyODAwMDAwMFoXDTE2MTAyNzAwMDAwMFowLTErMCkGA1UEAxMiYWNjb3VudHMuYWNjZXNzY29 udHJvbC53aW5kb3dzLm5ldDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALyKs/uPhEf7zVizjfcr/ISGFe9+yUOqwpel38zgutvLHmF D39E2hpPdQhcXn4c4dt1fU5KvkbcDdVbP8+e4TvNpJMy/nEB2V92zCQ/hhBjilwhF1ETe1TMmVjALs0KFvbxW9ZN3EdUVvxFvz/gvG29nQhl4QWK j3x8opr89lmq14Z7T0mzOV8kub+cgsOU/1bsKqrIqN1fMKKFhjKaetctdjYTfGzVQ0AJAzzbtg0/Q1wdYNAnhSDafygEv6kNiquk0r0RyasUUevE Xs2LY3vSgKsKseI8ZZlQEMtE9/k/iAG7JNcEbVg53YTurNTrPnXJOU88mf3TToX14HpYsS1ECAwEAATANBgkqhkiG9w0BAQsFAAOCAQEAfolx45w 0i8CdAUjjeAaYdhG9+NDHxop0UvNOqlGqYJexqPLuvX8iyUaYxNGzZxFgGI3GpKfmQP2JQWQ1E5JtY/n8iNLOKRMwqkuxSCKJxZJq4Sl/m/Yv7TS 1P5LNgAj8QLCypxsWrTAmq2HSpkeSk4JBtsYxX6uhbGM/K1sEktKybVTHu22/7TmRqWTmOUy9wQvMjJb2IXdMGLG3hVntN/WWcs5w8vbt1i8Kk6o 19W2MjZ95JaECKjBDYRlhG1KmSBtrsKsCBQoBzwH/rXfksTO9JoUYLXiW0IppB7DhNH4PJ5hZI91R8rR0H3/bKkLSuDaKLWSqMhozdhXsIIKvJQ == </X509Certificate> </X509Data> </KeyInfo> </KeyDescriptor> <SingleLogoutService Location="" Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect"/> <SingleSignOnService Location="" Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect"/> <SingleSignOnService Location="" Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST"/> </IDPSSODescriptor></EntityDescriptor>The tenant-specific SAML 2.0 sign-on and sign-out endpoint, which is of interest for the web application, is in the above illustration: web application should have logic to validate assertions signed with any of the valid advertised keys. As you can see in the above XML snippet, two signing X.509 certificate are specified. See section § REF _Ref405905568 \h \* MERGEFORMAT Handling the automatic key material refresh later in this document for more detailed guidance on Azure AD key rollover. Moreover, if you recall the App properties dialog when you’ve registered the application, the audience value you expect to see inside the SAML 2.0 response from Azure AD is what you’ve specified in APP ID URI. This should be the same as the issuer value you send Azure AD in your AuthnRequest request. (The SIGN-ON URL should correspond to your SAML 2.0 applications “Consumer Service URL”. This will be the destination of the SAML 2.0 response issued by Azure AD.)Using the directory coordinates to configure the web project with Open ID ConnectA tenant-specific JSON metadata document is published via a single endpoint to integrate your directory into the web application you’re developing with OpenID Connect 1.0: domain name>/.well-known/openid-configurationFor example, our directory corpfabrikam. (90995f16-6b12-4032-8b87-fd59566ed917) corresponds to: of the Azure AD specific endpoint and keys can be found from this JSON metadata document.? For your first application with OpenID Connect 1.0, you can get started by including the parameters in the following table to the tenant-specific OAuth 2.0 authorization endpoint: domain name>/oauth2/authorizeFor example, our directory corpfabrikam. (90995f16-6b12-4032-8b87-fd59566ed917) corresponds to: is an example of an OpenID Connect Authorize request: 273a01b1-c73d-49fa-a1f7-7c75d817fd72 scope=openid&nonce=393b61fa-8cc3-4c52-a167-472ae18fe934&response_mode=form_post&redirect_uri=https%3a%2f%2fwebapp1%2fWhere:”response_type” can be code, id_token, or code+id_token depending on your preference for protocol flow. Details on these flows can be found in the Authentication section of the OpenID Connect 1.0 core specification.“clientid” corresponds to the Client ID attributed by Azure AD when you’ve registered your web application (see section § REF _Ref405915694 \h \* MERGEFORMAT Registering the web application in your directory above). The Client ID value can be retrieved from the application properties page.You can access this page from the Quick Start page for the web application by clicking CONFIGURE.“scope” is required by the standard to set to the openid value.“nonce” is a random GUID used for preventing some classes of attack. Correct processing is described in the ID Token Validation section of the OpenID Connect 1.0 specification. “response_mode” is used to receive an HTTP POST at your application. You can also choose to receive a URI fragment response by omitting the parameter or using the value fragment.“redirect_uri” specifies the URL to which you want the user to return after signing in.NoteFor more information, see the Microsoft MSDN Article Authorization Code Grant Flow that describes the token endpoint requests and responses in detail.A sample code on GitHub describes how to build a single tenant web MVC application that uses OpenID Connect 1.0 via the OpenID Connect OWIN middleware (Microsoft.Owin.Security.OpenIdConnect) to sign-in users to a single Azure AD tenant. Similarly to the developer’s experience provided by the aforementioned WS-Federation OWIN middleware, the middleware is initialized by simply passing it the Client ID of the application and the URL of the Azure AD tenant where the application is registered. The middleware then takes care of:Downloading the Azure AD metadata, finding the signing keys, and finding the issuer name for the tenant.Processing OpenID Connect sign-in responses by validating the signature and issuer in an incoming JWT, extracting the user's claims, and putting them on ClaimsPrincipal.Current.Integrating with the session cookie OWIN middleware (Microsoft.Owin.Security.Cookies) to establish a session for the user. Handling the automatic key material refreshThe above current configuration reflects the current Azure AD state but the key information used at authentication time to validate that the incoming token actually originated from your directory tenant WILL change over the time. Issued tokens for all tenants are signed by same key and key are published via metadata documents as already covered, for instance: more information, see the Microsoft TechNet Article Important Information About Signing Key Rollover in Azure AD.It is indeed common security practice to regularly renew cryptographic keys, and Azure AD signing keys are no exception: at fixed time intervals the old keys will be retired, and new ones will take their place in the issuer’s signing logic and in your tenant’s metadata document. In case of emergency keys might be renewed off-cycle, with little or no warning.Every time the signing key is rolled, your application settings must be changed accordingly. With the above tooling, that would mean re-running the tool to read the new metadata document and refresh the related web.config entries accordingly.To minimize downtime, you should embed a self-healing key material refresh logic directly into your web application so that you can consume the metadata document programmatically and react to key rolling without the need of operator’s intervention. Such a logic should consist in:Caching in your code the necessary protocol coordinates for connecting to the intended Azure AD endpoints, Saving the key information - those are the issuer name representing your tenant and the public key (in form of X.509 certificate) that should be used to verify the token’s signature – and handling multiple keys,Regularly obtaining, for instance, when the application starts, the tenant-specific federation metadata document and updating the key information settings accordingly.Important noteThere are some extra precautions you need to apply when auto-refreshing the key information from the application. The main threat you need to mitigate is DNS hijacking, where an attacker uses malware to point you to a malicious metadata document and induce your app to trust the wrong keys. In , if you don’t override the .NET defaults for handling HTTP requests, such a scenario is already mitigated thanks to the fact that metadata documents are hosted on HTTPS endpoints. A DNS hijacking can redirect requests to a malicious endpoint, but such endpoint cannot pass the HTTPS server validation: not actually owning the domain on which metadata document are hosted, the attacker cannot obtain an issued certificate for it, hence the client will be able to detect an issue with the server and avoid being misdirected.The libraries (see sections § REF _Ref405971528 \h \* MERGEFORMAT Leveraging the Active Directory Authentication Library (ADAL) and REF _Ref405971539 \h \* MERGEFORMAT Leveraging other libraries) and related samples (see section § REF _Ref405971618 \h \* MERGEFORMAT Leveraging the various available code samples on GitHub) provided by Microsoft do the above automatically. Handling single sign outThe web single sign-on protocols in use today often include provisions for performing distributed sign out operations: those are flows in which not only the current application cancels its current user’s session, but it also reaches out to the authority to signal that a sign out command should be propagated to all the other applications’ sessions that might have been established by the same authority. Both SAML 2.0 and WS-Federation protocols are no exception, and offer a complete sign out flow. One way of adding sign out to your web application consists in:Adding a gesture for it in the user interface.Adding a logic for generating a SAML 2.0 or a WS-Federation sign-out message.Sending the sign-out message to the tenant-specific sign-out endpoint and handling the rest of the flow.Once the sign-out message is generated, WIF will for instance do all the rest for you for the WS-Federation protocol, the related sign out flow being fully implemented in WIF's object model.The above MVC template used as illustration with the and Web Tools for Visual Studio 2013 provides an AccountController.cs controller and a SignOutCallback.cshtml view to handle out-of-the-box the sign-out flow with the WS-Federation.The OWIN components take care of that for you.You can pretty much get this done on any development platform, beyond .NET, the aforementioned examples on Java and PHP on GitHub to give you an idea of that. Same is true for node.js etc. Querying your directory data using the Azure AD Graph APIWhile the security token obtained during sign in contains user information like a name through the supplied collection of claims (see above), your web application may need additional information such as group memberships or the name of the user's manager. As already illustrated at the beginning of this document, such an information can be obtained from your directory by using Azure AD Graph API, instead of LDAP v3 as you will do with Active Directory on-premises. Configuring the desired permissions with the consent frameworkFirst of all, you should configure via the consent framework the permissions your web application requires to access data in your directory by using Azure AD Graph API depending on what you intend to do.You can select from two types of permissions:Application Permissions. Your web application needs to access Azure AD Graph API directly as itself (, i.e. the “app identity”) with no user context. This type of permission requires administrator consent.Delegation Permissions. Your web application needs to access Azure AD Graph API as the signed-in user (, i.e. the user’s identity, i.e. the “app + user identity” (or delegated identity)), but with access limited by the selected permission. This type of permission can be granted by a user unless the permission is configured as requiring administrator consent.?Your web application is enabled by default for single sign-on with Azure AD plus the ability to read the profiles of signed-in users, such as their email address and contact information using the Azure AD Graph API as listed the dashboard of the application. This corresponds to the Enable sign-on and read user’s profile delegated permission.To update the desired set of permissions for the web application to access Azure AD Graph API, proceed with the following steps:Select in Azure management portal the application created above in the single sign-on part. Expand the?ACCESS WEB APIS IN OTHER APPLICATIONS?under CONFIGURE.Click Configure it now?under SELECT PERMISSIONS. The application properties page will appear.Scroll down to the?Permissions to other applications?section. Add application allows you to select thanks to the consent framework from the available applications in your directory that expose a web API (See section § REF _Ref405553583 \h \* MERGEFORMAT Defining the web API permissions later in this document). By default, you can choose permissions from Azure AD Graph API (Windows Azure Active Directory).NoteIf your directory also has a subscription to Office 365, then Office 365 APIs and permissions for Exchange Online, SharePoint Online, and Power BI are also available for selection in addition to Azure AD Graph API and the Azure Service Management API. To see the permission scopes exposed by Office 365, see the Microsoft MSDN article Office 365 app authentication as well as the blog post Using Azure AD to build daemon applications that call Office 365 APIs. Consider the already existing entry for Azure AD Graph API (Windows Azure Active Directory). As mentioned above, your application is already configured for the Enable sign-on and read user’s profile delegated permission with:Select the appropriate application and delegation permissions exposed by Azure AD Graph API. NoteOnce an application is selected in the first column, you can select application and delegation permissions that the selected web API exposes.The following table lists the available permissions with the Azure AD Graph API.Permission nameDescriptionPermission typeEnable sign-on and read users' profilesAllow users to sign in to the application with their organizational accounts and let the application read the profiles of signed-in users, such as their email address and contact information.Delegation permission only. Can be consented by users. Access your organization's directoryAllow the application to access your organization's directory on behalf of the signed-in user.Delegation permission only. Can be consented by users in a native client and only by an administrator for web applications.Read directory dataAllow the application to read data in your organization's directory, such as users, groups and applicationsDelegation and application permission. Must be consented by an administrator.Read and write directory dataAllow the application to read and write data in your organization's directory, such as users and groupsDelegation and application permission. Must be consented by an administrator.NoteSetting the Read directory data and Read and write directory data application permissions through the new Permissions to other applications control is equivalent to the previous Manage Access wizard that exits prior to the consent framework and as formerly documented in version 1.0 of this document.Once selected, click SAVE?at the bottom of the tray.You’re now in a position to invoke the Azure AD Graph API, but, before your web application read (or read and write) the directory data with the Azure AD Graph API, it must authenticate itself against the Azure AD STS and obtain an access token to secure the calls to the Azure AD Graph API.? Directly relating to the above two types of permission, the web application calls to the Azure AD Graph API can be made under an application identity, or a delegated user identity.In order to authenticate and call the Azure AD Graph API, the web application can use its own identity, i.e. the “app identity” or the user’s identity, i.e. the “app + user identity” (or delegated identity):In the former case, the OAuth 2.0 client credentials grant flow with a confidential client (as described in the OAuth 2.0 specification) is used: a confidential client (e.g. the web application) wishes to access a protected resource (e.g. Azure AD Graph API) under the security context of its own identity. The web API trusts that the web application authenticated the user. For this reason, this pattern is called a trusted subsystem.In the latter case, you will choice the choice to use the OAuth 2.0 authorization code grant with a confidential client or the OpenID Connect 1.0 protocol.We illustrate hereafter the OAuth 2.0 client credentials grant flow (where grant_type=client_credentials). Please see later in this document with the web APIs for the OAuth 2.0 authorization code grant flow with a confidential client and the OpenID Connect 1.0 protocol.As illustrated, your web application should send a (POST) request to the Azure AD OAuth 2.0 token, which corresponds to the OAuth 2.0 token tenant-specific endpoint of Azure AD. The application must authenticate itself by providing a Client ID for the application and the related credential in the form of an application key. The application key is used as a password to authenticate the web application.To manually configure an application key in your web application, proceed with the following steps:In the Quick Start page for the web application, expand ACCESS WEB APIS IN OTHERS APPLICATIONS.Copy the supplied Client ID (UPDATE YOUR CODE WITH YOUR CLIENT ID) for your application in the directory.Under CREATE A KEY, click Configure key. The application properties page appears.Scroll down to keys.Add a key by selecting the key’s lifespan (default 1 year). This will generate a key value that is your application’s password as stated above and will be used in the application configuration.Click SAVE at the tray of the bottom.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 web application can have multiple keys, for example, you may want one or more for testing and production.The above MVC template auto-create the application key for you and save it in the web.config file along with the client ID:… <appSettings> <add key="webpages:Version" value="3.0.0.0" /> <add key="webpages:Enabled" value="false" /> <add key="ClientValidationEnabled" value="true" /> <add key="UnobtrusiveJavaScriptEnabled" value="true" /> <add key="ida:FederationMetadataLocation" value="" /> <add key="ida:Realm" value="" /> <add key="ida:AudienceUri" value="" /> <add key="ida:ClientID" value="8b28072d-cd6c-4df9-aa38-1f8b54fd3f5e" /> <add key="ida:Password" value="L5X3opVtvGmeDQ2wIawhPMUM8BlII+OHA132E074BBY=" /> </appSettings>…At this point, you have:Configured read permissions (or read and write permissions) for your web application.A client ID and a key.If we come back to the second step of the OAuth 2.0 client credentials grant flow, you can now request a token from the OAuth 2.0 token tenant-specific endpoint of Azure AD, using the tenant domain name obtained from the signed on user’s tenant ID claim (see above), the Client ID and the key to authenticate. Once the request is successfully processed, you get back an HTTP 200 along with a JWT access token in the body. As outlined before, JWT is indeed a compact token format that is especially apt for REST-based development. ?Note You can use the JSON Web Token (JWT) Decoder to decode a JWT token.The header of the JWT token request consists of two fields that indicate the signing algorithm (“alg”) and the format of the assertion (“typ”). The implementation relies on the HMAC SHA-256 algorithm and the JWT token format. As a result, the JSON representation of the header is as follows: {"alg":"HS256","typ":"JWT"} The body of the JWT access token request contains a set of the desired claims as a JSON object that is base64url encoded, and notably:“aud” that identifies the audience that the token is intended for in form of an URI, for example in our illustration.“iss” that identifies the issuer of the token.{ "aud": "", "iss": ", …}Note For more information, see the Microsoft TechNet article Supported Token and Claim Types.The body is “signed” with the HMAC SHA-256 algorithm using the above application key to produce an HMAC.The JWT token can then be used in calls (step 4) to the Azure AD Graph API (see above step 4), which is inserted in the Authorization header of subsequent requests. Content-Type: application/json; odata=minimalmetadataAuthorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik5HVEZ2ZEstZnl0aEV1T….It is recommended that the JWT token be cached by the web application for subsequent calls. We advise to check the JWT token expiration before making an Azure AD Graph API call. If the token is expired, then a new token should be acquired. If a call to the Azure AD Graph API is made with an expired token, An HTTP 401 Unauthorized error response will be returned, and the application should request a new token.A proxy class could be created for the calls to the Azure AD Graph API. Such a proxy class should:Create an organization’s tenant-specific Azure AD Graph API endpoint, for example in our configuration: Use the endpoint to instantiate the proxy to call the Azure AD Graph API.Add the 2 above HTTP headers.On Microsoft platforms, and as already mentioned, this can be easily achieved through the client-side library ADAL. One can also leverage Azure AD Graph API Helper Library.For the developers using non-Microsoft platforms, the directory can be queried in the same way using their existing favorite stacks thanks to the RESTful based interface provided by the Azure AD Graph API. Once the JWT token is obtained, it is indeed simply passed to the Azure AD Graph API as an HTTP Authorization header as part of the REST calls. NotePHP developers cans refer to the code source PHP Sample App for Azure Active Directory Graph. Likewise, Java developers can refer to the article Java Sample App for Azure Active Directory Graph API (REST API). Finally, Node.je developers can refer to the detailed walkthroughs available in the Azure Active Directory Authentication Library Wiki for using Passport.js to add web single sign-on to a Node.js app.NoteFor more information, see the MSDN documentation of the Azure AD Graph API. Using Azure AD for authorizationIn addition to what we’ve covered so far, you can also use Azure AD for authorization purposes in your web application, that is, restricting access to secured resources. To enforce authorization on specific actions, the web application can use Azure AD groups (security groups or distribution lists) and group claims. A group is a collection of users and groups that can be managed as a single unit. Users and groups that belong to a particular group are referred to as group members.NoteFor more information, see the Microsoft TechNet article Group management.Once groups claim is enabled for the web application, the application can be able to determine which actions a user is allowed to do based on their group membership, which is indicated by the groups claim that the application receives on user sign in. The following table lists the sign-in flows for which the groups claim is issued.NoteTo ensure that the token containing groups claim doesn’t exceed the query string size limits of browsers, Azure AD emits the groups claim only in the sign-in flows in which the token travels over POST.ProtocolGroups claim issued?WS-FederationYes in the SAML token in the attribute name ‘’. This is a multi-valued attribute.SAML 2.0. Response over POST bindingYes in the SAML token in the attribute name ‘’. This is a multi-valued attribute.OpenID Connect 1.0 (id token). Response over POST bindingYes in the id token in the "groups” node.OpenID Connect 1.0 (id token) Response over query string or fragmentNoNoteFor more information, see the blog posts Azure Active Directory, now with Group Claims and Application Roles! and Authorization in Cloud Applications using AD Groups.A code sample available in GitHub illustrates how this can be achieved in a web application. This sample indeed shows how to build an MVC web application that uses group claims for authorization. This sample uses the OpenID Connect OWIN middleware and the ADAL for .NET library.In addition to groups and groups claims, Azure AD provides application roles and role claims for role based access control (RBAC) to model authorization. When using RBAC with role claims, an administrator grants permissions to roles, not to individual users or groups. The administrator can then assign roles to different users and groups to control who has access to what content and functionality.The application can thus be able to determine which actions a user is allowed to do based on their roles, which is indicated by the role claim that the application receives on user sign in. The following table lists the sign-in flows for which the role claim is issued.ProtocolGroups claim issuedWS-FederationYes in the SAML token in the attribute name ‘’. This is a multi-valued attribute.SAML 2.0Yes in the SAML token in the attribute name ‘’. This is a multi-valued attribute.OpenID Connect 1.0 (id token)Yes in the id token in the "groups” node.NoteFor more information, see the blog posts Azure Active Directory, now with Group Claims and Application Roles! and Roles based access control in cloud applications using Azure AD.As an illustration, you can consider another code sample available on GitHub.Groups and application roles are by no means mutually exclusive - they can be used in tandem to provide even finer grained access control. This is all in your hands.Enabling groups claimFrom a practical standpoint, enabling groups claim in the web application is a two steps process.Firstly, this supposes to enable groups claim in the application manifest, which is a JSON file that represents your application’s identity configuration.Secondly, you must add a delegated permission for the web application to query Azure AD Graph API.To start by configuring the application manifest, proceed with the following steps:From the Azure management portal, click ACTIVE DIRECTOY?on the left pane, and then click on the desired directory.Click?APPLICATIONS, and then click the application you want to configure. The Quick Start page appears with single sign-on and other configuration information.Click MANAGE MANIFEST at the bottom of the, and select?Download Manifest. A Download Manifest dialog pops up. Select?Download manifest. Click Save to locally save the application manifest file.Open the application manifest file with a text editor of your choice.{ "appId": "273a01b1-c73d-49fa-a1f7-7c75d817fd72", "appRoles": [], "availableToOtherTenants": false, "displayName": "WebApplication1", "errorUrl": null, "groupMembershipClaims": null, "homepage": "", "identifierUris": [ "" ], "keyCredentials": [], "knownClientApplications": [], "logoutUrl": null, "oauth2AllowImplicitFlow": false, "oauth2AllowUrlPathMatching": false, "oauth2Permissions": [ { "adminConsentDescription": "Allow the application to access WebApplication1 on behalf of the signed-in user.", "adminConsentDisplayName": "Access WebApplication1", "id": "a5c7a741-15c7-4008-a208-afdc348b7a95", "isEnabled": true, "type": "User", "userConsentDescription": "Allow the application to access WebApplication1 on your behalf.", "userConsentDisplayName": "Access WebApplication1", "value": "user_impersonation" } ], "oauth2RequirePostResponse": false, "passwordCredentials": [], "publicClient": null, "replyUrls": [ "" ], "requiredResourceAccess": [ { "resourceAppId": "00000002-0000-0000-c000-000000000000", "resourceAccess": [ { "id": "311a71cc-e848-46a1-bdf8-97ff7156d8e6", "type": "Scope" } ] } ], "samlMetadataUrl": null, "extensionProperties": [], "objectType": "Application", "objectId": "8ca48146-ae80-4810-b311-265d9d0089a4", "deletionTimestamp": null, "createdOnBehalfOf": null, "createdObjects": [], "manager": null, "directReports": [], "members": [], "memberOf": [], "owners": [], "ownedObjects": []}Locate the groupMembershipClaims?node. As introduced before, when a user signs into the web application, Azure AD emits a groups claim that will contain the identifiers of all groups based on the user and their group membership.Set its value to either: “SecurityGroup”. The groups claim will contain the identifiers of all security groups of which the user is a member. – or – “All”. The groups claim will contain the identifiers of all security groups and all distribution lists of which the user is a member.Once set, save the modified application manifest file.Click MANAGE MANIFEST at the bottom of the, and select?Upload Manifest. An Upload Manifest dialog pops up. Click BROWSE FOR FILE and point to the modified application manifest file.Click the check mark icon to save the modified JSON application manifest file.Next, you must add a delegated permission for the web application to query Azure AD Graph API. This implies to check the Read directory data permissions for Azure AD Graph API in the Permissions to other applications?section of the application properties page. (See section § REF _Ref406076564 \h \* MERGEFORMAT Configuring the desired permissions with the consent framework earlier in this document.)Defining application rolesFrom a practical standpoint, application roles are defined by also configuring the application manifest.To define the applications roles for the web application, proceed with the following steps:From the Quick Start page of the application in the Azure management portal, download the application manifest file if not already done.Open the application manifest file with a text editor of your choice.{ "appId": "273a01b1-c73d-49fa-a1f7-7c75d817fd72", "appRoles": [], "availableToOtherTenants": false, "displayName": "WebApplication1", "errorUrl": null, "groupMembershipClaims": null, "homepage": "", "identifierUris": [ "" ], "keyCredentials": [], "knownClientApplications": [], "logoutUrl": null, "oauth2AllowImplicitFlow": false, "oauth2AllowUrlPathMatching": false, "oauth2Permissions": [ { "adminConsentDescription": "Allow the application to access WebApplication1 on behalf of the signed-in user.", "adminConsentDisplayName": "Access WebApplication1", "id": "a5c7a741-15c7-4008-a208-afdc348b7a95", "isEnabled": true, "type": "User", "userConsentDescription": "Allow the application to access WebApplication1 on your behalf.", "userConsentDisplayName": "Access WebApplication1", "value": "user_impersonation" } ], "oauth2RequirePostResponse": false, "passwordCredentials": [], "publicClient": null, "replyUrls": [ "" ], "requiredResourceAccess": [ { "resourceAppId": "00000002-0000-0000-c000-000000000000", "resourceAccess": [ { "id": "311a71cc-e848-46a1-bdf8-97ff7156d8e6", "type": "Scope" } ] } ], "samlMetadataUrl": null, "extensionProperties": [], "objectType": "Application", "objectId": "8ca48146-ae80-4810-b311-265d9d0089a4", "deletionTimestamp": null, "createdOnBehalfOf": null, "createdObjects": [], "manager": null, "directReports": [], "members": [], "memberOf": [], "owners": [], "ownedObjects": []}Locate the appRoles?node and insert in it your own application roles.The following JSON snippet is an example of how to define an application role, here the “Admin” one. "appRoles": [ { "allowedMemberTypes": [ "User" ], "description": "Admins can manage roles and perform all task actions.", "displayName": "Admin", "id": "81e10148-16a8-432a-b86d-ef620c3e48ef", "isEnabled": true, "origin": "Application", "value": "Admin" } ],As introduced before, when a user signs into the web application, Azure AD emits a role claim for each role that has been granted based on the user and their group membership. The role claim is set to the value field, for example “Admin” in the above illustration.The following table lists the possible values for the appRoles portion of the application manifest file.Element nameDescriptionallowedMemberTypesSpecifies whether this application role definition can be assigned to users and groups, or to other applications (that are accessing this application in daemon scenarios (see later in this document), or to both. Can be one of the following values:“User”: may be assigned to end users and groups“Application”:?may?be assigned to others applications (see later in this document)descriptionHelp description for the application role in the admin app assignment and consent experiencesdisplayNameFriendly name for the application role shown in the admin consent and app assignment experiences.idGUID exposed by the web application for the application role. It must be unique amongst all application roles for the web application.isEnabledAlways set to true when creating or updating an application role. If you wish to delete an application role, you must first set this value to false, and upload the manifest. Then you may remove the application role in a subsequent manifest upload.originReserved for future use. Always set to “application”.valueValue placed in the?role?claim if the user has been assigned to this particular application role. The web application can use this value to scope the level of access that the user has when accessing the application. It must not contain any white spaces and must be unique amongst all application roles in the web application.NoteFor more information, see the Microsoft MSDN article AppRole. Once the desired application roles are defined for the web application to accommodate your RBAC approach, save the modified application manifest file and upload it for the web application.You can expose additional application roles later as necessary.Assigning/Removing users to your application rolesOnce the application roles have been defined through the upload of the modified JSON application manifest file, you can then assign various users and groups to the application roles. To assign various users to the application roles for the web application, proceed with the following steps:From the Quick Start page of the web application in the Azure management portal, click CONFIGURE.Scroll down to USER ASSIGNEMENT REQUIRED TO ACCESS APP.Select YES, and then click SAVE at the bottom of the tray.From the Quick Start page of the web application in the Azure management portal, click USERS.Important noteIf you have enabled the Basic or the Premium editions of Azure AD, click USERS AND GROUPS instead. For more information, see the Microsoft TechNet article Azure Active Directory Editions.Select any user and click ASSIGN in the bottom tray to assign an application role. (Conversely, use REMOVE to remove an application role). Important noteIf you have enabled the Azure Active Directory Premium, next to SHOW, select All Users in the drop-down list.Then click the check mark icon. You can then proceed as instructed is step 2.An Assign Users dialog pops up.Select the appropriate role.Click the check mark icon in the bottom right to assign the user to the application role. Repeat this process for any users you would like to have access to the application role in the web application.Assigning/Removing groups to your application rolesTo assign various groups to the application roles for the web application, proceed with the following steps:Click USERS AND GROUPS under the application in the Azure management portal. Important noteThis feature is only available when you enable Azure Active Directory Premium. For more information, see the Microsoft TechNet article Azure Active Directory Editions.Next to SHOW, select Groups in the drop-down list. Next to STARTING WITH, optionally specify the first characters of the name of the group, and, then click the check mark icon. Select any group and click ASSIGN in the bottom tray to assign an application role. (Conversely, use REMOVE to remove an application role). An Assign Groups dialog pops up.Select the appropriate role.Click the check mark icon in the bottom right to assign the user to the application role. Repeat this process for any users you would like to have access to the application role in the web application.Developing a multi-tenant web applicationEven if this is not mandatory, and as mentioned before, the vast majority of SaaS applications are multi-tenant web applications. Multi-tenant web applications are application instances accessed by multiple customers. Although there is only one application (regardless of the tangible aspects of how the application is partitioned, how many VMs it is running on in the cloud, etc.), every tenant has the illusion of accessing its own exclusive instance, customized accordingly and isolated from any other concurrent user from other tenants. This is a very popular model thanks to the good utilization of the underlying resources; in the market right now you can find a wide array of solutions at different level of maturity. However, it is also a challenging one, as proper tenant isolation and provisioning flows can be non-trivial and the field is still relatively new, and the support of identity makes no exception to that with the identity management itself, the provisioning, the role management, the authentication, etc.In such a context, Azure AD represents for (cloud) ISVs a compelling service offering that can be easily integrated with their solution, rather than having to implement those capabilities into their platform. It’s all the more so that such an integration can directly leverage the customer organization’s directory so that no prior synchronization is needed and the user’s authentication is directly handled by Azure AD for the considered directory. Integrating with Azure AD indeed allows your customers to sign up and sign in to your multi-tenant application using an identity management system that they already maintain, which reduces or eliminates the need to do separate identity management tasks with your application. This functionality gives your customers a more seamless experience when using your application, and it frees up the time spent doing management tasks.Multi-tenant web applications need to be provisioned in each directory where they will be used, which requires user or administrator consent to register them.If you are writing a multi-tenant web application that you want to make available to your customers (or partners) outside of your organization, you’ll simply need to update the application definition in the Azure management portal compared to what we covered for the web application. This also requires to adapt the application.As a result, developing a multi-tenant application that leverages Azure AD basically entails for additional steps:Promoting the application entry in Windows AD to allow access to external users.Granting access for the application.Promoting the application entry in Windows AD to be externally availableThis step revisits the application’s entry in the Azure management portal by extending the availability of the existing application to directory tenants other than your own in which the application has been added.To enable access to your app for external users, proceed with the following steps:Sign into the Azure management portal as the administrator of the directory to configure.Click ACTIVE DIRECTORY on the left menu, and then click the name of the organization’s directory in which is located the web application you want to configure.Click APPLICATIONS from the top menu, then click the application to configure. The Quick Start page appears with single sign-on and other configuration information.Click CONFIGURE MULTI-TENANT APPLICATION under CONFIGURE.Click Configure it now under ENABLE ACCESS. The application properties page appears.Scroll down to APPLICATION IS MULTI-TENANT.Click YES next to APPLICATION IS MULTI-TENANT, Click SAVE at the tray of the bottom.NoteWhen activating the multi-tenancy, you must ensure that your application’s APP ID URI belongs in a verified domain. Additionally, the Reply URL must begin with you have made the change above, users and administrators in other organizations will be able to grant your application access to their directory and other data. (See later in this document).Granting access for the applicationThe consent framework that has been shortly discussed with the use of the Azure AD Graph API has been introduced earlier this year on March 12, 2014. By fully leveraging the potential of the OAuth 2.0 protocol, it allows much more powerful applications compared to what the previous consent experience allowed. Beyond the richness of the applications roles and the set of permissions that can be defined, it enables to build multi-tenant applications not only for the web applications being discussed here but also for the daemon and the server application. It also enables users to consent to these applications instead of just administrators.The consent experience prior to March 12, 2014, which can be considered somehow as legacy, is still supported. Since you have the choice, we will cover both options. Granting access with the new consent frameworkWith the new consent framework, the application must request authorization using OAuth 2.0.If you do offer a sign-up experience, it is expected that the user will click on a sign up (or sign-in button). When they sign up for your application, they will redirect to the OAuth2.0 authorize endpoint (or an OpenID Connect userinfo endpoint) of Azure AD as previously depicted, and will be presented with a dialog that shows the permissions the application requires, and then the option to consent. These endpoints allow the application to get information about the new user by inspecting the?id_token.Depending on the required permissions (administrator-level permissions vs. user-level permissions), an administrator in the other organization may be required to give consent. Alternatively, the application may also thus offer an experience that allows administrators to “sign up my company”. This experience would also redirect the user to the Azure AD OAuth 2.0 authorize endpoint. The following is an example valid consent request URL to send a consent (authorization code) request to the OAuth 2.0 authorization tenant-specific endpoint of Azure AD for the directory corpfabrikam.: illustrated above, you can pass prompt=admin_consent?parameter to trigger the administrator consent experience, where the administrator will grant consent on behalf of their organization. On successful consent, the response will contain?admin_consent=true. When redeeming an access token, you’ll also receive an?id_token?that will provide information on the organization and the administrator that signed up for your application.When the user or administrator consents, the application is registered in their directory.NoteFor more information, see the Microsoft TechNet article Adding, Updating, and Removing an Application.Granting access with the consent experience prior to March 12, 2014The "legacy" consent experience allows you to only grant the following permissions:Sign on users from their organization.Sign on users and read the their organization’s directory data (as the application only)Sign on users and read and write their organization’s directory data (as the application only)In order to be effective, this implies to:Prepare the application’s project to handle multiple tenantsAdd sign-up capabilities to the applicationThe article Developing Multi-Tenant Web Applications with Azure AD outlines how to build a multi-tenant web MVC 4 application that can be used by organizations that have Azure AD.Important noteThis illustration will be removed soon. A sample code that addresses a similar scenario is available GitHub.The rest of this chapter illustrates the two above steps for the legacy consent experience.Preparing the application’s project to handle multiple tenants (legacy)Adjusting the web single sign-on (and single sign-out) protocol coordinates in the configurationAs previously mentioned, in lieu of the tenant-specific endpoints domain name>/<protocol>, the tenant-independent endpoints ; enables the application to know which tenant the user is in during sign-in. Azure AD signs the user in and figures out their tenant, handling this way for you the Home Real Discovery (HRD) or Where Are You From (WAYF).You should consequently adapt the endpoint(s) being used in your application accordingly. Likewise, the authentication response must be processed to check user is from a consented tenant. For that purpose, you must validate the audience that relates to the various consented tenant. Important noteAzure AD will issue a token to a user only if the recipient application has been granted access within the user’s directory. Using the tenant-independent endpoint does not weaken the access constraints established at the directory level; it just adds generality to the sign-on process.A list of the consented tenant domain name should be typically maintained by the application as part of the sign-up process. (See below.)As far as the sign-out is concerned, it can use either the tenant-specific of the tenant-independent sign-out endpoints.The MVC template in Visual Studio 2013 handles all of this for you as illustrated above. To come back to our previous illustration with the MVC template in Visual Studio 2013, the wizard can handle such configuration for at the project creation time. If you recall the Change Authentication dialog, you can simply select Cloud – Multiple Organizations in lieu of Cloud – Single Organizations.The rest of the procedure is similar and the auto-generated configuration is all you need for taking advantage of Azure AD for web single sign-on with a multi-tenant application.Querying the customer’s directory dataCalls to Azure AD Graph API tenant-specific endpoint must be based on the sign in user’s directory tenant. This supposes to:Get the current tenant from the signed in user’s tenant.Get the OAuth 2.0 access token from the user’s tenant.Use that token to access the tenant-specific Azure AD Graph API endpoint.Beyond the above operations, there is no specific differences compared to what has been covered in this area with the single tenant web application. The MVC template in Visual Studio 2013 handles all of this for you as illustrated above.Adding sign-up capabilities to the application (legacy)If you are building an application that can be used by users outside your organization, it must not only be registered in your company’s directory, but also must be registered in each organization’s directory that will be using the application. To make the application available in their directory, sign-up capabilities must be added to the application for your customers that enables them to consent to your application. Requesting consent for your applicationThis sign-up flow is integrated within Azure AD and is part of the multi-tenant application’s transaction with your customers.Before a customer can use your multi-tenant application integrated with its organization’s directory, a tenant administrator of that organization must consent (e.g. authorize) to use your multi-tenant application. This sends the sign-up tenant administrator through a consent flow: this starts with a consent request from your application to Azure AD, which generates a response that must be handled by your application. Your application requires the consent of the administrator of the customer’s directory tenant to be able to single sign-in and access the directory data.The following interaction typically demonstrates the process of requesting consent for your application:In order for external users (e.g. customers and/or partners) to sign up for your application using their Azure AD organizational accounts, you’ll need to update your app to show a link or a button that links to the consent page on Azure AD that enables them to grant access. For example, the customer (with directory administrative privileges) clicks a "Sign up for this application" link in your application, which redirect them to a Sign Up page.Note For branding guidance for this sign up link or button, see the Microsoft MSDN article Branding Guidelines for Integrated Apps.When Sign Up is clicked, you redirect the customer to the Azure AD consent page with your application's information and the requested permission appended to the request.The Azure AD consent page displays your app name, logo, and the publisher details. The customer either grants or denies consent for your application.Azure AD redirects the customer’s directory administrator to your specified consent return URL. This URL is specified when you expose the already registered application to external users. The redirect request indicates the result of the consent request, including information about their tenant if consent was granted.At this point, the end-users of the newly subscribed customer can now sign-in to the multi-tenant application:To generate the redirect request in step 2 above, you must append query string parameters to the following URL for the Azure AD consent page: The query string parameters are described below:ClientID. The Client ID value is generated when your multi-tenant application is registered in your ISV’s directory.RequestedPermissions. The permissions that must be granted to your application by the customer’s directory tenant. There are three possible values for this parameter:None. This setting enables single sign-on but disables access to directory data.DirectoryReaders. This setting enables single sign-on and grants permission to read directory data, such as user accounts, groups, and information about the customer’s organization.DirectoryWriters. This setting enables single sign-on and grants permission to read and write data, such as users, groups and information about the customer’s organization.ConsentReturnURL. Optional. The URL in your application to which the consent response must be returned. This value must be URL-encoded and must be under the same domain as the Reply URL configured in your application definition. If not supplied, the grant access response will be redirected to your configured Reply URL.Note Specifying a ConsentReturnURL value separate from the Reply URL value will allow your multi-tenant application to implement separate logic that can process the response on a different URL from the Reply URL (which normally processes SAML tokens for sign on as per WS-Federation or SAML 2.0 protocols).?You may also specify additional parameters in the ConsentReturnURL encoded URL; these will be passed back as query string parameters to your application upon redirection.? This mechanism can be used to maintain additional info or to tie your application’s request for an access grant to the response from Azure AD.The following is an example valid consent request URL to send a consent request to Azure AD: is C24f8f1fe-e8b1-4201-b891-684048adf3a5,RequestedPermissions equals DirectoryReaders,And the ConsentReturnURL is the consent responseAfter a customer has granted or denied consent for your application, Azure AD sends a consent response to your application's consent return URL. This response contains the following query string parameters:TenantId. The unique GUID for the directory that has authorized your application. This parameter will only be specified if the customer has authorized your application.Consent. The value will be set to Granted if the application has been authorized, or Denied if the request has been rejected.Note Additional parameters like a ContextID will be returned to the multi-tenant application if they were specified as part of the ConsentReturnURL encoded URL.Note The access grant response doesn’t contain a security token for the user; the multi-tenant application must sign the user in separately.The following is an example valid response to the consent request that indicates the application has been authorized: equals GrantedAnd TenantId is 90995f16-6b12-4032-8b87-fd59566ed917 (corpfabrikam.)This results in the consent flow ending.Your application will need to maintain context such that the request sent to the Azure AD consent page is tied to the response (and would reject any responses without an associated consent request).After a customer has granted consent to your application, it's important to associate and store the consented tenant in your application with the tenant ID returned by the consent response. This value will be used for future sign-in requests.On the customer’s side, the application is displayed in the Azure management portal:From the application page, you can click MANAGE ACCESS at the tray of the bottom.Promoting the applicationIn terms of application listing, the Azure marketplace can increase the discoverability of your multi-tenant application and consequently the lead generation.NoteFor more information on how to integrate with Azure AD and be listed in the Azure AD Applications gallery, see the article Listing your application in the Azure Active Directory application gallery.This topic that is orthogonal with the objectives of this document is no further covered.Adding a web API for Single Sign-On (SSO)Developing and calling a web API that leverages Azure AD basically entails for the following steps: REF _Ref405553599 \h Registering the web API in the directory tenant. REF _Ref405553591 \h Configuring the web API project for Azure AD. REF _Ref405553583 \h Defining the web API application roles and permissions. REF _Ref406079547 \h Enabling the client application to access the web API.Registering the web API in the directory tenantAs before with a web application, the directory tenant administrator creates the service principal at behest of developer.To register a web API, proceed with the following steps:Sign into the Azure management portal as the administrator of the directory to configure.Click ACTIVE DIRECTORY on the left menu, and then click the name of the organization’s directory for which you want to register the web API.On the top menu, click APPLICATIONS. If no apps have been added to your directory, this page will only show the ADD AN APP link. Click on the link, or alternatively you can click ADD at the tray of the bottom. A What do you want do? dialog brings up.Click Add an application my organization is developing.On the Tell us about your application page, specify a user friendly name for your web API. This name will enable it to be easily identified when looking at registered client applications in your directory. Select WEB APPLICATION AND/OR WEB API. Click the arrow icon on the bottom-right hand corner of the page.On the App properties page, provide the information for the web API. Specify the address of the web API in APP URL, as well as in APP ID URI to logically identify the web API.NoteWith a web application, the address specified in APP URL is used to know to where the token representing successful authentication should be sent. In the case of a web API, however, the return URL is handled by the client of the web API. Hence, you can enter here whatever valid URL you like and that won’t have impact on the process. This said, this is usually a good idea to put the correct URL anyway, given that you never know how you’ll want to evolve this web API in the future...Click the check mark icon on the bottom-right hand corner of the page.You are redirected to the Quick Start page for the web API.At this point, your web API is now listed among the other registered applications of your directory. Let’s configure it for Azure AD.Configuring the web API project for Azure AD As illustrated with the web application, you use the directory tenant coordinates to configure the web API project. For web APIs developed with the .NET Framework 4.5, you can leverage the JSON Web Token Handler for the Microsoft .NET Framework along with the Microsoft Token Validation Extension for Microsoft .NET Framework 4.5to handles the JWT processing at the service. For developers using Visual Studio 2013, the aforementioned and Web Tools for Visual Studio 2013 enables to create a web API project secured by your directory tenant right from the start. The experience is in line with the one provided for web applications (with the notable absence of the return URL, which would make no sense here).To configure your web API project for using your Azure AD directory’s organizational accounts, proceed with the following steps: Click Change Authentication. An eponym Change Authentication dialog brings up.Select Organizational Accounts on the left side.Select Cloud – Single Organization to enable authentication for user accounts that are defined in your directory tenant, for example, the corpfabrikam. tenant in our illustration.In Domain, fill in the domain of your tenant that you want to set up the web API in, for example, the default domain corpfabrikam. in our illustration. If you have defined in your directory a custom federated Internet domain such in lieu of corpfabrikam., you can specify that domain. In Access Level, if your web application needs to query or update directory information by using the Azure AD Graph API, choose Single Sign-On, Read Directory Data or Single Sign-On, Read and Write Directory Data. Otherwise, choose Single Sign-On.By default, the template creates an ID URI for you by appending the project name to the specified domain. For example, if the project name is WebAPI and the domain is corpfabrikam., the application ID URI becomes previously illustrated, if you want to manually specify the application ID URI, expand More Options.Click OK. An ADAL Sign in dialog brings up.Enter the credentials for your organizational account with administrative privileges and click Sign in. Once authenticated and the web API configured in the directory, the Change Authentication dialog closes and the web API is fully configured for validating JWT tokens issued by Azure AD for your authenticated directory’s organizational accounts.Click OK to finalize the configuration of the web API project.The and Web Tools for Visual Studio 2013 actually performs two tasks:It reaches out to the selected directory and add an entry describing the web API being created.It emits code for the web API project using the OAuth 2.0 OWIN middleware (Microsoft.Owin.Security.OAuth). As noticed before, it adds the necessary security middleware from the Microsoft OWIN components to handle Azure AD authentication and generate the necessary initialization code to validate incoming tokens according to the Azure AD tenant of choice.At the stage, you get a web API project fully configured using the OWIN middleware. The project template only takes care of the web API side.NoteFor more information on how to build and register a client, see the blog post Securing a Web API with Azure AD and Katana.The .NET and Web Tools for Visual Studio 2013 leverage both the JSON Web Token Handler for Microsoft .Net Framework and the Microsoft Token Validation Extension for Microsoft .Net Framework 4.5 to authenticate calls to the web API RESTful service.Once the web API is added in the directory tenant and configured for Azure AD, regardless of the language, and the platform being used, it can be invoked by clients using a variety of devices, languages, and platforms. Before doing that, you will need to define the set of permissions to expose in order to enable a client application to access the web API.Defining the web API application roles and permissionsTo expose a web API to other applications, you first have to configure for the web API applications roles and/or a set of permissions to expose. On that basis, a correctly configured web API is made available just like the other Microsoft web APIs, including the Graph API and the Office 365 APIs. Defining application roles for the web API will enable to set corresponding application permission at the client application level. Likewise, defining a set of permissions for the web API will enable to set corresponding delegated permissions at the client application level. See later in this document.From a practical standpoint, your web API is made available by configuring an application manifest as covered before with the application roles definition.Defining the web API application rolesTo define the applications roles for the web API, proceed with the following steps:From the Quick Start page of the application in the Azure management portal, download the application manifest file if not already done.Open the application manifest file with a text editor of your choice.{ "appId": "05ffbc00-d8c7-4362-bae3-301b51f3f339", "appRoles": [], "availableToOtherTenants": false, "displayName": "WebApi1", "errorUrl": null, "groupMembershipClaims": null, "homepage": "", "identifierUris": [ "" ], "keyCredentials": [], "knownClientApplications": [], "logoutUrl": null, "oauth2AllowImplicitFlow": false, "oauth2AllowUrlPathMatching": false, "oauth2Permissions": [ { "adminConsentDescription": "Allow the application to access WebApi1 on behalf of the signed-in user.", "adminConsentDisplayName": "Access WebApi1", "id": "fa4aad5a-4b1e-4e51-a493-8e830b64911f", "isEnabled": true, "type": "User", "userConsentDescription": "Allow the application to access WebApi1 on your behalf.", "userConsentDisplayName": "Access WebApi1", "value": "user_impersonation" } ], "oauth2RequirePostResponse": false, "passwordCredentials": [], "publicClient": null, "replyUrls": [ "" ], "requiredResourceAccess": [ { "resourceAppId": "00000002-0000-0000-c000-000000000000", "resourceAccess": [ { "id": "311a71cc-e848-46a1-bdf8-97ff7156d8e6", "type": "Scope" } ] } ], "samlMetadataUrl": null, "extensionProperties": [], "objectType": "Application", "objectId": "205be13e-9c25-4f33-b387-b1f074ba0881", "deletionTimestamp": null, "createdOnBehalfOf": null, "createdObjects": [], "manager": null, "directReports": [], "members": [], "memberOf": [], "owners": [], "ownedObjects": []}Locate the appRoles?node and insert in it your own application roles.The following JSON snippet is an example of how to define an application role, here the “Reader” one. "appRoles": [ { "allowedMemberTypes": [ "Application" ], "description": "Readers can perform all read actions.", "displayName": "Reader", "id": "81e10148-16a8-432a-b86d-ef620c3e48ef", "isEnabled": true, "origin": "Application", "value": "Reader" } ],Once the client application is appropriately configured to request access to your web API and calls the web API, it will present an OAuth 2.0 JWT access token that has the role claim for each role that has been granted to the application. The role claim is set to the value field, for example “Reader” in the above illustration.Once the desired application roles are defined for the web API to accommodate your RBAC approach, save the modified application manifest file and upload it for the web API.You can expose additional application roles later as necessary.Defining the web API permissionsTo define the set of permissions for the web API, proceed with the following steps:From the Azure management portal, click ACTIVE DIRECTOY?on the left pane, and then click on the desired directory.Click?APPLICATIONS, and then click the application you want to configure. The Quick Start page appears with single sign-on and other configuration information.Click EXPOSE WEB APIS TO OTHERS APPLICATIONS under CONFIGURE.Click MANAGE MANIFEST at the bottom of the tray, and select?Download Manifest to download the application manifest file if not already done.Open the application manifest file with a text editor of your choice.{ "appId": "05ffbc00-d8c7-4362-bae3-301b51f3f339", "appRoles": [ { "allowedMemberTypes": [ "Application" ], "description": "Readers can perform all read actions.", "displayName": "Reader", "id": "81e10148-16a8-432a-b86d-ef620c3e48ef", "isEnabled": true, "origin": "Application", "value": "Reader" } ], "availableToOtherTenants": false, "displayName": "WebApi1", "errorUrl": null, "groupMembershipClaims": null, "homepage": "", "identifierUris": [ "" ], "keyCredentials": [], "knownClientApplications": [], "logoutUrl": null, "oauth2AllowImplicitFlow": false, "oauth2AllowUrlPathMatching": false, "oauth2Permissions": [ { "adminConsentDescription": "Allow the application to access WebApi1 on behalf of the signed-in user.", "adminConsentDisplayName": "Access WebApi1", "id": "fa4aad5a-4b1e-4e51-a493-8e830b64911f", "isEnabled": true, "type": "User", "userConsentDescription": "Allow the application to access WebApi1 on your behalf.", "userConsentDisplayName": "Access WebApi1", "value": "user_impersonation" } ], "oauth2RequirePostResponse": false, "passwordCredentials": [], "publicClient": null, "replyUrls": [ "" ], "requiredResourceAccess": [ { "resourceAppId": "00000002-0000-0000-c000-000000000000", "resourceAccess": [ { "id": "311a71cc-e848-46a1-bdf8-97ff7156d8e6", "type": "Scope" } ] } ], "samlMetadataUrl": null, "extensionProperties": [], "objectType": "Application", "objectId": "205be13e-9c25-4f33-b387-b1f074ba0881", "deletionTimestamp": null, "createdOnBehalfOf": null, "createdObjects": [], "manager": null, "directReports": [], "members": [], "memberOf": [], "owners": [], "ownedObjects": []}Locate the oauth2Permissions?node. A unique access permission is exposed by default. The related JSON snippet constitutes an example of how to expose a permission scope known as “user_impersonation”. "oauth2Permissions": [ { "adminConsentDescription": "Allow the application to access WebApi1 on behalf of the signed-in user.", "adminConsentDisplayName": "Access WebApi1", "id": "fa4aad5a-4b1e-4e51-a493-8e830b64911f", "isEnabled": true, "type": "User", "userConsentDescription": "Allow the application to access WebApi1 on your behalf.", "userConsentDisplayName": "Access WebApi1", "value": "user_impersonation" } ],Specify in it your own set of permissions.Once a client application is appropriately configured to request access to the web API (see below) and calls the web API, it will present an OAuth 2.0 JWT access token that has the scp (scope)?claim set to the value field, for example “user_impersonation” in the above illustration.The following table lists the possible values for the oauth2Permissions portion of the Application Manifest JSON file.Element nameDescriptionadminConsentDescriptionHelp description in the administrator’s consent dialog and in the consented application’s properties pageadminConsentDisplayNameFriendly name for the permission shown in the application and/or delegation permission scope dropdowns in the Azure management portal, and to administrators during consent, and in the application’s properties page.idGUID exposed by the web API for the permission scope. It must be unique amongst all permissions for the web API.isEnabledAlways set to true when creating or updating a permission scope. If you wish to delete a permission, you must first set this value to false, and upload the manifest. Then you may remove the permission in a subsequent manifest upload.originReserved for future use. Always set to “application”.typeCan be one of the following values:“User”: may be consented to by end users“Admin”:?must?be consented to by a company administratoruserConsentDescriptionHelp description in the user’s consent dialog.userConsentDisplayNameFriendly name for the permission shown to end-users during consent.valueValue placed in the?scp?claim of the OAuth 2.0 JWT access token if this particular permission has been consented to by the user. The web API can use this value to scope the level of access that the client application has when impersonating the user. It must not contain any white spaces and must be unique amongst all permissions in the application.Once the desired permission scopes are defined for the web API to accommodate the variety of different functions exposed by the web API, save the modified application manifest file and upload it for the web API.You can expose additional permission scopes later as necessary.Enabling the client application to access the web APIUsing the consent framework, you can then configure a client application to require permissions to access data exposed by web APIs in your directory. The client application can be a web application as covered in the above sections, a daemon or a server application, or a native client. These exposed permissions can be used to limit the client application’s access to the web API’s resources: the role claim or the scp claim in the received JWT access token can be used for that purpose in the web API code.At this point, we have to deal with two cases for the client application in terms of single-sign-on scenarios:The client application uses its own identity, i.e. the “app identity”.-or-The client application uses the user’s identity, i.e. the “app + user identity” (or delegated identity).Consequently, and as described with the Azure AD Graph API, you can potentially define from two types of permissions for accessing the desired web API, and of course depending on the application roles and/or the set of permissions exposed by the web API and their types:Application Permissions. Your client application needs to access the web API directly as itself (no user context). This type of permission that corresponds the application roles requires administrator consent and is also not available for native client applications.Delegation Permissions. Your client application needs to access the web API as the signed-in user, but with access limited by the selected permission. This type of permission can be granted by a user unless the permission is configured as requiring administrator consent.?To enable a client application to access the web API, proceed with the following steps: From the Azure management portal, click ACTIVE DIRECTOY?on the left pane, and then click on the desired directory.Click?APPLICATIONS, and then click the application you want to configure. The Quick Start page will appear with single sign-on and other configuration information.Click ACCESS WEB APIS IN OTHER APPLICATIONS?under CONFIGURE.Click Configure it now?under Select permissions. The application properties page shows up.Scroll down to Permissions to other applications. As already described for Azure AD Graph API, the first column allows you to select from the available applications in your directory that expose a web API. Click Add application. A Permissions to other applications pops up.Select All Apps in SHOW, and then click the checkmark on the right.Select the web API to call, for example WebAPI1 in our illustration, and then click the checkmark at the bottom on the right.Once added, select the appropriate application and/or delegation permissions that the web API exposes, for example in our illustration “Reader” as an application permission,or “Access WebApi1” as a delegated permission.Once selected, click SAVE?at the bottom of the tray.The next sections describe the protocols and the flows that correspond the application client calls to the web API using its own identity or the user identity. For the moment, let’s consider the web application, the daemon and the server application. We will covered the native client in a specific section later in this document.Understanding web application calls to web API using own identityIn this scenario, as the title of the section indicates, the web application calls the web API using its own identity, i.e. the “app identity”. When using an application identity, the web API can only detect that the web application is calling it, as the web API does not receive any information about the user. If the application receives information about the user, it will be sent by the web application but it is not signed by Azure AD. The web API trusts that the web application authenticated the user. For this reason, this pattern is called a trusted subsystem. For that purpose, the web application uses OAuth 2.0 client credentials grant flow with a confidential client (as described in the OAuth 2.0 specification): a confidential client (e.g. the web application) wishes to access a protected resource (e.g. the web API) under the security context of its own “app identity”. The prerequisites of this flow are: The configuration of a client credential that the confidential client employs to authenticate itself, And the configuration of a permission in Windows AD allowing the confidential client to access the resource service. As an illustration, you can consider a code sample available in GitHub. This sample is an example of the trusted subsystem model, where the web API trusts the web application to have authenticated the user, and receives no direct evidence from Azure AD that the user was authenticated.Understanding web application calls to web API using user’s identityUnlike the previous scenario, the web application calls web API using the user’s identity, i.e. the “app + user identity” (or delegated identity). In this scenario, the web application obtains an access token for the user, which proves to the web API that the user successfully authenticated to the web application and that the web application was able to obtain a delegated user identity to call the web API. This access token is sent in the request to the web API, which authorizes the user and returns the desired resource.This scenario can be accomplished in two ways: with OAuth 2.0 authorization code grant or with the OpenID Connect 1.0 protocol.Let’s consider the two different flows and the implied differences. Using the OAuth 2.0 authorization code grant flowWith the OAuth 2.0 authorization code grant flow with a confidential client (as described in the OAuth 2.0 specification), a confidential client (e.g. the web application) receives consent (in the form of an authorization code) from a resource owner to access a protected resource (e.g. the web API) on their behalf. The client then redeems the authorization code for an access token and a refresh token, to access the protected resource. The prerequisites of this flow are: The configuration of a permission/delegation in Azure AD allowing the client to access the resource service, The configuration of a reply address of the client where the authorization code is posted (over TLS), And finally the configuration of a client credential in the case of confidential clients. As an illustration, you can consider a code sample available on GitHub. In this sample, an existing web application with its own way of signing in users adds the ability to call an Azure AD protected web API, in this case the Azure AD Graph API. This sample uses the OAuth 2.0 authorization code grant with confidential client and the ADAL to obtain access tokens for the web app to call the Azure AD Graph API with the user's identity.Note For more information, see the blog post Using OAuth2 Authorization Code Grant for delegated access of Directory via AAD Graph.Getting the Authorization codeNow that the permission object has been set up, the web application can initiate the flow to call the web API as illustrated hereafter.The user signs in in step 1.NoteAs the authentication of the resource owner happens using a web user interface, this leg of the flow allows arbitrary interaction, and is consequently well-suited to federated web single sign-on authentication (with the on-premises identity infrastructure if any), multi-factor authentication mechanisms like Azure Multi-Factor Authentication, account compromise detection… and more stuff not yet anticipated.In step 2, the web application employs the user’s browser to send a consent (authorization code) request to the OAuth 2.0 authorization (tenant-specific or tenant-independent) endpoint of Azure AD.For that purpose, the request needs to specify the Client ID for the client web application (8ed7dd71-1d25-4030-a037-012d3329fd10), the Redirect URI (), and the App ID URI for the web API (). The user will be redirected to the Azure AD login page and the user will be redirected back to the Redirect URI we specified in the request parameter after a successful login. The following is an example valid consent request URL to send a consent (authorization code) request to the OAuth 2.0 authorization tenant-specific endpoint of Azure AD for the directory corpfabrikam.: redirect URI will have the Authorization code. The sample response shown below is the redirect request to the application after a successful login. The client_id and redirect_uri in the request below comes from the above step when you created permission for this application. the end of this leg of the flow, the authorization code can be extracted in step 3.Getting an access token with the authorization codeThe obtained authorization code can now be used in conjunction with the Client ID, the credentials key, etc. to fetch the access token. The access token can be used to call the web API and the permissions that the App gets will be based on the role that the User belongs to and the Role that was used in Scope parameter when creating the Permission object for this application. To get an access token, the web application does a GET to the OAuth 2.0 token (tenant-specific or tenant-independent) endpoint of Azure AD, for example for the directory corpfabrikam.: endpoint will return an access token to the web application provided the right data is passed as the request parameters.?The following is an example valid request URL to the OAuth 2.0 token tenant-specific endpoint of Azure AD for the directory corpfabrikam.: DhjYU…kqqyHiqNm/PY=&Code=AAAAAAAA...............P5qd1L7x2BAP6bxxyD9KMgAAAs illustrated, the web application need to pass the following data in URL Form-Encoded format:The grant type (authorization code),The web application client ID previously obtained via the Graph Explorer,The redirect URI,The web application credentials key previously obtained via the Graph Explorer, And the (authorization) code previously received.As part as the above step 4, that data is posted to the above URL and provided it’s all valid, the web application will get in step 5 (in JSON format) i) a JWT access token needed to call the web API and ii) a refresh token that can be used to request (behind the scenes without any user interaction) a new access token when that expires: { "access_token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik5HVEZ2CzkwXeiVQ", token_type":"Bearer", "expires_in":"28799", "expires_on":"1368676551", "refresh_token":"AAAAAAAADENAfM5UpyznQ8EHSHp0GI8GTGXonaBFZHZADR1Kf...-Q9SAA", "scope":"62e90394-69f5-4237-9190-012177145e10"}Where:“access_token” is the JWT needed to call the web API RESTful service.“token_type” specifies what the type of token received by the application is, in this case Bearer as per RFC 6750.“expires_in” specifies how long until the JWT access tokens expires.“expires_on” specifies when does the JWT access token expires.“refresh_token” is the token can be used to request (behind the scenes without any user interaction) a new access token when that expires.“scope” defines what the scope of the user permission is.At this point, the web application has everything it needs to call the web API in step 6. As illustrated, an HTTP Authorization header must be set with the value:? Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik5HVEZ2CzkwXeiVQGetting an access token with the refresh tokenThe refresh token has a life-span longer than that of the access token. The client persists the refresh token and redeems it for a new access token (and optionally a refreshed refresh token) when the existing access token expires.To get an access token, the web application does a GET to the OAuth 2.0 token (tenant-specific or tenant-independent) endpoint of Azure AD, for example for the directory corpfabrikam.: endpoint will return an access token to the web application provided the right data is passed as the request parameters.?The following is an example valid request URL to the OAuth 2.0 token tenant-specific endpoint of Azure AD for the directory corpfabrikam.:…kqqyHiqNm/PY=&refresh_token= AAAAAAAADENAfM5UpyznQ8EHSHp0GI8GTGXonaBFZHZADR1Kf...-Q9SAAAs illustrated, the web application need to pass the following data in URL Form-Encoded format:The grant type (refresh token),The web application client ID,The web application credentials key, And the refresh token previously received.As part as the above step 4, that data is posted to the above URL and provided it’s all valid, the web application will get in step 5 (in JSON format) i) a new JWT access token needed to call the web API and ii) a refresh token that can be used to request a new access token when that expires: { "access_token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik5HVEZ2CzkwXeiVQ", "token_type":"Bearer", "expires_in":"28799", "expires_on":"1368676551", "refresh_token":"AAAAAAAADENAfM5UpyznQ8EHSHp0GI8GTGXonaBFZHZADR1Kf...-Q9SAA", "scope":"62e90394-69f5-4237-9190-012177145e10"}Using the OpenID Connect 1.0 protocolThe above approach is useful if you want to add a web API calling ability to an existing web application that authenticates Azure AD users using WS-Federation.This said, OpenID Connect 1.0 provides today a more efficient way to get access tokens for a user to call a web API, by obtaining an authorization code for the user at the time they sign in. This also means your web application can skip having logic for sending OAuth 2.0 authorization requests and processing OAuth 2.0 authorization responses.As an illustration, you can consider a code sample available on GitHub. This sample shows how to build an MVC web application that uses Azure AD for sign-in using the OpenID Connect 1.0 protocol, and then calls a web API under the signed-in user's identity using tokens obtained via OAuth 2.0. This sample uses the OpenID Connect OWIN middleware and ADAL.Signing to the web application and getting an authorization codeA user is signed in to a web application using Azure AD as already covered. If the user of the web application has not yet consented to allowing the web application to call the web API on its behalf, the user will need to consent. The web application will display the user-level permissions it requires.When the user signed in, the web application received an ID token with information about the user, as well as an authorization code.Getting an access token with the authorization codeUsing the authorization code issued by Azure AD, the web application sends a request that includes the authorization code, details about the client application (Client ID and Redirect URI), and the desired resource (application ID URI for the web API) to (tenant-specific or tenant-independent) token endpoint of Azure AD.The endpoint will return an access token to the web application provided the right data is passed as the request parameters.?The web application uses the returned JWT access token to add the JWT string with a “Bearer” designation in the Authorization header of the request to the web API. The web API then validates the JWT access token, and if validation is successful, returns the desired resource.Before considering the scenarios that relate to native applications, let’s deal with the scenarios of a daemon or server application that calls a web API.Understanding daemon calls to web API using own identity User interaction is not possible with a daemon application. The daemon can be a batch job, an operating system service running in the background, code in a factory device, at truck, anything without human interaction for sign-in.The daemon consequently has to have its own identity and calls the web API using its own identity. For that purpose, it uses OAuth 2.0 client credentials grant flow. This is the exact same to the above scenario where the web application calls to web API using own identity.It requests an access token by using its own identity and presenting its client ID, credential (password or certificate), and application ID URI to Azure AD. After successful authentication, the daemon receives an access token from Azure AD, which is then used to call the web API.As an illustration, you can consider two code samples available on GitHub that demonstrate how to use the aforementioned ADAL for .NET library to secure service calls from a server side process to a web API. The ADAL library handles the above OAuth 2.0 code flow and provides in this context token caching capabilities as well as automatic token refresh. It also demonstrates how to authenticate calls to a web API by leveraging the JWT handler that handles the JWT processing at the service. Understanding server application calls to web API using user’s identityThe server application calls web API using the user’s identity. Imagine that a user has authenticated on a web application or native application, and this application needs to call a web API. Azure AD issues a JWT access token to call the web API. If this first-tier web API needs to call another downstream web API, it can use the “On_Behalf_Of” flow to delegate the user’s identity and authenticate to the second-tier web API.Since no user with browser is present, the OAuth 2.0 client credentials grant flow cannot be used. The OAuth 2.0 "On_Behalf_Of" token exchange draft RFC aims at addressing this situation.The flow hereafter assumes that a user has been authenticated on another application (e.g. a web application or native application), and their user identity has been used to acquire an access token to the first-tier web API.The application sends the user’s JWT access token to the first-tier web API.The first-tier web API sends a request to Azure AD’s token endpoint, providing its Client ID and credentials, as well as the user’s JWT access token. In addition, the request is sent with an on_behalf_of parameter that indicates the web API is requesting new tokens to call a downstream web API on behalf of the original user.Azure AD verifies that the first-tier web API has permissions to access the second-tier web API and validates the request, returning a JWT access token and a JWT refresh token to the first-tier web API.Over HTTPS, the first-tier web API then calls the second-tier web API by appending the token string in the Authorization header in the request. The first-tier web API can continue to call the second-tier web API as long as the access token and refresh tokens are valid.As an illustration, you can consider a code sample available on GitHub. In this sample, a native client calls a web API and then the web API calls another downstream web API after obtaining a token to act On Behalf Of the original user. The sample uses the ADAL in the native client to obtain a token for the user to call the first-tier web API, and also in the first-tier web API to get a token to act on behalf of the user to call the downstream second-tier web API. Both flows use the OAuth 2.0 protocol to obtain the tokens.Adding a native application for Single Sign-On (SSO)Azure AD provides support for registering a native application. A native application is an application that is installed on a device such as a phone or computer. The combined influence of growing presence of devices in business environments with the Consumerization of IT and the Bring Your Own Device (BYOD) trends, and success of the various marketplace (iTunes, Google Play, Windows (Phone) Store make this form factor one of the fastest growing ones. The main areas of native application revolve around mobile workforce scenarios (sales people, pharmaceutical promoters, etc.), scenarios in which mobility and free hands are of essence (manufacturing, logistic, healthcare services) and the like.More and more native applications make use of a cloud-based back-end for the notifications, storage, etc. Consequently, native client applications can be integrated with Azure AD to access web APIs on behalf of a user in an Azure AD directory.This functionality corresponds to the following example scenario: a developer has created a native client application that needs to call a web API. As previously covered in this document, the web API is secured by Azure AD, which uses OAuth 2.0 to allow authenticated users and authorized applications to call it. To enable this scenario, both applications (the native application and the web API) are registered in Azure AD, and the native application is configured with permissions to call the web API on behalf of an authenticated user. In other words, the native application calls the web API using the user’s identity, i.e. the “app + user identity” (or delegated identity). The registration of a web API has been covered in the last section. Let’s consider the registration of the native application.Registering the native application in the directory tenantThe directory tenant administrator creates the service principal at behest of developer.To register a native application, proceed with the following steps:Sign into the Azure management portal as the administrator of the directory to configure.Click ACTIVE DIRECTORY on the left menu, and then click the name of the organization’s directory for which you want to register the web API.On the top menu, click APPLICATIONS. If no apps have been added to your directory, this page will only show the ADD AN APP link. Click on the link, or alternatively you can click ADD at the tray of the bottom. A What do you want do? dialog brings up.Click Add an application my organization is developing.On the Tell us about your application page, specify a user friendly name for your native application. This name will enable it to be easily identified when looking at registered client applications in your directory. Select NATIVE CLIENT APPLICATION. Click the arrow icon on the bottom-right corner of the page.On the Application information page, specify the redirect URI for your native application in REDIRECT URI. This is the location where Azure AD will redirect in response to an OAuth 2.0 request. Depending on the platform on which you develop the native client, you might have to deal with different constraints. For example, a Windows Store client application would require you to use the “ms-app://” protocol schema if you want to use certain features.Note For more information, see the article How Web authentication broker single sign-on works on the Windows Dev Center. Click the check mark icon in the bottom-right hand corner of the page.Your native application has now been added to the directory. You now need to reflect the registration information in your native application’s code.Updating the native application’s codeTo update your code with the application’s coordinates, proceed with the following steps:From the Quick Start page of the newly added application, click UPDATE YOUR CODE under GET STARTED.Copy the string next to REDIRECT URI and the value next to CLIENT ID.Reflect them in your code wherever appropriate as the redirect URI respectively client ID to use.From an implementation perspective in terms of code, an available sample on GitHub demonstrates a Windows Store client application calling a simple web API that is secured using Azure AD. The Windows Store client application uses the aforementioned ADAL for .NET 2.x library to obtain a JWT access token through the OAuth 2.0 protocol. The access token is then sent to the web API to authenticate the userLikewise, another code sample available on GitHub demonstrates a Windows Presentation Foundation (WPF) client application for the same scenario.Furthermore, for the authenticated calls to the web API RESTful service, these 2 code samples demonstrate how to leverage the JSON Web Token Handler for Microsoft .Net Framework 4.5. The same web API RESTful service is being used here. It leverages the JSON Web Token Handler for Microsoft .Net Framework 4.5. The JSON Web Token Handler for Microsoft .Net Framework 4.5 handles the JWT processing at the service. In both cases, the ADAL for .NET library handles the above OAuth 2.0 code flow in the application.The available code samples on GitHub?provides walkthrough instructions for iOS and Android applications.Enabling the native application to access a web API in the same directoryBoth the native application and the web API must be registered in the same directory in Azure AD. Furthermore, and as already covered, the web API must be configured to expose a set of permissions (see section § REF _Ref405553583 \h \* MERGEFORMAT Defining the web API permissions earlier in this document). You then have for select the desired permissions for the native from the Permissions to Other Applications drop-down menu in the Azure management portal.To enable the native application to access the web API, proceed with the following steps: From the Quick Start page of the newly added application, click CONFIGURE ACCESS TO WEB APIS IN OTHER APPLICATIONS under GET STARTED.Click Configure it now. The application properties page shows up.Scroll down to permissions to other applications. As already described, the first column allows you to select from the available applications in your directory that expose a web API. Click Add application. A Permissions to other applications pops up.Select All Apps in SHOW, and then click the checkmark on the right.Select the web API to call, for example WebAPI1 in our illustration, and then click the checkmark at the bottom on the right.Once added, select the delegation permissions that the web API exposes, for example “Access WebApp1” in our illustration.Once selected, click SAVE?at the bottom of the tray.The result of the above process is that the native client is authorized to call the web API on behalf of a user of the client. At a deeper level, the client is authorized to call the web API because after a user of the client authenticates with Azure AD, a JWT access token is returned that contains a scp claim, with in our illustration for example the “user_impersonation” value.Enabling a native application to access a multi-tenant web APIThe native application is configured to indicate the permissions it requires to be functional. This list of required permissions is shown in a dialog when a user or administrator in the destination directory gives consent to the application, which makes it available to their organization. Some applications require just user-level permissions. Other applications require administrator-level permissions. Only an administrator of the directory administrator can give consent to applications that require the latter level of permissions. When the user or administrator consents, only the web API is registered in their directory. As an illustration, you can consider a code sample available on GitHub. This sample demonstrates a Windows Store application calling a multi-tenant web API that is secured using Azure AD. The Windows Store application uses the ADAL to obtain a JWT access token through the OAuth 2.0 protocol. The access token is sent to the web API to authenticate the user. The web API project demonstrates how to structure your RESTful services for being accessed by users coming from multiple Azure AD tenants. The Windows Store application shows how to handle in-up sign up for a new service and sign in from any Windows Azure tenant.Understanding native application calls to web API using user’s identityAs stated above, a native application calls a web API using the user’s identity, i.e. the “app + user identity” (or delegated identity). Unsurprisingly, that native application uses for that purpose the OAuth 2.0 authorization code grant flow with a public client (as described in section § 4.1 of the OAuth 2.0 specification): a public client (e.g. the native application) receives consent (in the form of an authorization code) from a resource owner to access a protected resource (e.g. the web API) on their behalf. The client then redeems the authorization code for an access token and a refresh token, to access the protected resource. As previously outlined, the prerequisites of this flow are: The configuration of a permission/delegation in Azure AD allowing the client to access the resource service, And the configuration of a reply address of the client where the authorization code is posted (over TLS). The prerequisites are already fulfilled with the above steps.Getting an authorization code In step 1, the native application employs the resource owner/user’s browser to send a consent (authorization code) request to the OAuth 2.0 authorization (tenant-specific or tenant-independent) endpoint of Azure AD. The following is an example valid consent request URL to send a consent (authorization code) request to the OAuth 2.0 authorization tenant-specific endpoint of Azure AD for the directory corpfabrikam.:httpslogin.corpfabrikam.oauth2/authorize?response_type=code&resource= &redirect_uri= URL comprises the login URL, our domain (corpfabrikam.), the response type we’re looking for (code), the resource we want to access (), our client ID (the alphanumeric string 91498461-d9b9-4766-84ef-0b149f18f934), and our redirect URI () when the native application was added in the directory.This results in step 2 in the authentication of the resource owner/user if they are not already authenticated. The native application sign-in user interface is the same sign-in user interface as web application sign-in. NoteAs the authentication of the resource owner happens using a web user interface, this leg of the flow allows arbitrary interaction, and is consequently well-suited to federated web single sign-on authentication (with the on-premises identity infrastructure if any), multi-factor authentication mechanisms like Azure Multi-Factor Authentication, account compromise detection… and more stuff not yet anticipated.The native application employs a browser pop-up for this leg of the flow, from which the authorization code can be extracted in step 3. The redirect will be to a URL that looks like this: important part here is the (authorization) code that comes back and that you need to pull out.Getting an access token with the authorization codeTo get an access token, the native application does a post to the OAuth 2.0 token (tenant-specific or tenant-independent) endpoint of Azure AD, for example for the directory corpfabrikam.: endpoint will return an access token to the native application, provided the right data is passed into the body as a POST, and as opposed to asking a user to authenticate.?To this tenant-specific endpoint URL, the native application need to pass the following data in URL Form-Encoded format:The grant type (authorization code)The native application client ID,The redirect URI (this just has to match up with what we sent previously and isn’t used as a redirect),The (authorization) code previously received.In terms of HTTP headers, the native application also needs to specify that it expects application/json as the response type and that it send over application/x-www-form-urlencoded data as the HTTP Content-Type.?As part as the above step 4, that data is posted to the above URL and provided it’s all valid, the native application will get in step 5 the following data back (in JSON format):{ "access_token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik5HVEZ2CzkwXeiVQ", token_type":"Bearer", "expires_in":"28799", "expires_on":"1368676551", "refresh_token":"AAAAAAAADENAfM5UpyznQ8EHSHp0GI8GTGXonaBFZHZADR1Kf...-Q9SAA", "resource":"AAAAAAAADENAfM5UpyznQ8EHSHp0GI8GTGXonaBFZHZADR1Kf...-Q9SAA", "scope":"62e90394-69f5-4237-9190-012177145e10"}Where:“access_token” is the JWT needed to call the web API RESTful service.“token_type” specifies what the type of token received by the application is, in this case Bearer as per RFC 6750.“expires_in” specifies how long until the JWT access tokens expires.“expires_on” specifies when does the JWT access token expires.“refresh_token” is the token can be used to request (behind the scenes without any user interaction) a new access token when that expires.“scope” defines what the scope of the user permission is.At this point, the application has everything it needs to call the web API in step 6. As illustrated, an HTTP Authorization header must be set with the value:? Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik5HVEZ2CzkwXeiVQGetting an access token with the refresh tokenAs previously mentioned, the refresh token has a life-span longer than that of the access token. The client persists the refresh token. Now the native client application is able to access the web API on behalf of an authenticated user of the native application, and calls made to the downstream web API are authorized with the user’s credentials.When the existing access token expires, the client redeems the refresh token for a new access token (and optionally a refreshed refresh token).Allowing external identities with your applicationIn today’s world, in addition to providing their employees and mobile workforce with an access to the required applications, organizations often also have to share resources with business partners and deliver applications to business and consumers.NoteThe word “consumer” is used here to refer to the ultimate consumer, customer, client, citizen, retiree, or a supporter of a business, government or charity, someone who is acting as an individual, and not as a representative of an organization.Depending on what you try to achieve with these external users (business partners and supply chains, individual consumers), Azure AD offers specific purpose tailored options for:Developing applications, such as a payroll service, for businesses. As previously described, Azure AD already provides an identity platform that allows you to build modern applications that seamlessly integrate with millions of organizations that have already configured Azure AD as part of deploying Office 365 or other enterprise services.You should use for that purpose the Azure AD’s multi-tenanted application model discussed earlier in this document. Enabling business partner access to your corporate resources, such as a Line-Of-Business application. As recently announced, Azure AD extends its capabilities to manage partner identities with a new capability for Business-to-Business (B2B): Azure AD B2B, now in public preview.Without impacting the current app model, Azure AD B2B collaboration, an additional functionality available on all the aforementioned Azure AD editions, now enables your corporate administrators to grant external users (who may or may not exist in Azure AD) single sign on (SSO) access to your applications. This improves security as users lose access when they leave the partner organization, while you control access policies within your organization. This also simplifies administration as you don’t need to manage an external partner directory or per partner federation relationships.NoteFor additional information on Azure AD B2B, see the whitepaper Introducing Azure AD B2B in the same series of paper.Developing consumer-facing (web and mobile) applications, such as a retail store front. This is what the new recently announced service Azure AD B2C should be used for Business-to-Consumer (B2C) in order to meet the growing needs organizations looking to connect their consumers via such applications. For example, as an alternative to manage these users accounts directly within their solution, many organizations want to enable people to sign-up/sign-up using the social identity accounts that they already have. Azure AD B2C provides such capabilities.Azure AD B2C gives individual consumer a choice between “Bringing their own Identities” (BYOI) by using one of their existing social accounts, such as Facebook, Google+, Amazon, or LinkedIn), or creating a new local account (arbitrary email address / username with password). Note As of this writing, Microsoft Account (MSA) personal identities are not yet supported due to the work implied by the converged programming model underway, but they will be soon. For additional information, see next section.NoteFor additional information on Azure AD B2C, see the whitepaper An overview of Azure AD B2C in the same series of paper.The above options allow to accommodate many different requirements – thus the need for B2B and B2C technologies that interact but are honed to specific problems. In fact, Azure AD B2B and Azure AD B2C can be thought of as a continuum, so approaches need to be able to be mixed and deployed flexibly.From a programming perspective, one should note that Azure AD B2C conforms to Azure AD’s next generation app model currently in public preview, i.e. the app model v2.0 preview. Let’s consider what v2.0 means and how this differs from what we’ve covered so far in this document.Introducing the App model v2.0A public preview of a converged programming model for Microsoft Account (MSA) and Azure AD identities has been recently announced: the app model v2.0 preview, which constitutes the Azure AD’s next generation app model compared to the current app model covered so far in this document. NoteFor additional information, see the blogpost Now in public preview: The Converged Microsoft Account and Azure Active Directory Programming Model and the article App model v2.0 preview: Sign-in Microsoft Account & Azure AD users in a single app.The app model v2.0 gives you the ability to write your application completely account-agnostic. it can be ignorant of the type of account that the user signs in with, i.e. personal MSA accounts vs. work or school Azure AD accounts. Of course, you can make your application aware of the type of account being used in a particular session, but you don't have to.A new registration processRegistration is still required. However, the registration process has been simplify compared to what we’ve covered earlier in this document. Indeed, you no longer need to make separate registrations for a web application and a back-end web API, a native client and a back-end web API, etc. If this constitutes one logical application - native client, web application, and web API - then it can all be represented by a single Application ID. All you need is a single application registration and a single Application ID. You can then add several platforms to each registered application, and provide the appropriate data for each added platform. You can register as many applications as you want to fulfill your requirements. This said, in the majority of situations, only one application will suffice. Since the registration process has greatly evolved, the v2.0 app model thus requires you to register your application in a new location: in lieu of the Azure AD extension in the Azure management portal. For now, this portal only works for the app model v2.0. To register an application, proceed with the following steps:Open a browsing session and navigate to the new portal at . Sign-in with either a personal account or a work or school account. This is the beauty of the app model.Click Add an app. A New Application Registration pops up.Provide a name for the application, for example “Corpfabrikam” to continue with our fictitious organization used throughout this document. Click Create application. The basic registration is complete, and your application has an Application ID. Let's say this particular application will consist of a web application, web API, and a mobile application. Next you would register each of these platforms. Under Platforms, click Add Platform. An Add Platform dialog pops up. Click Web. Under Redirect URIs, enter your web application's redirect URI, i.e. the location where authentication responses will be posted.For mobile application, click Add Platform, and then click Mobile application this time.Simply copy down the default redirect URI automatically created for you. The above Click here for help integrating your application with Microsoft links in the screenshots take you to the developer guide where you will find quick start samples for several languages.Click Save at the bottom of the page. Et voila! That's all it takes to get registered! NoteFor additional information, see the article App model v2.0 preview: How to register an app with Microsoft.Let's now take a look at the implication in terms of types of applications.A support for a variety of modern application architecture Compared to our previous discussion on the primary scenarios supported by the current app model (see section REF _Ref430790806 \h \* MERGEFORMAT Authenticating against the directory), the app model v2.0 encompasses the same primary scenarios with some differences that are outlined hereafter:NoteFor additional information, see the article App model v2.0 preview: Types of apps.Web browser to web application with OpenID Connect 1.0. A user needs to sign in to a web application (written in .NET, PHP, Java, Ruby, Node.js, etc.) that is secured by Azure AD. For that purpose, the application issues an OpenID Connect 1.0 authentication request to Azure AD and obtain in return an ID token. Web application to web API with OAuth 2.0 authorization code flow. A web application needs to get resources from a web API secured by Azure AD. The application performs in this case a combined OpenID Connect 1.0 and OAuth 2.0 flow, and acquires tokens using authorization codes and refresh tokens. All components, i.e. the web application and the web API, share a single Application ID as previously illustrated.Single Page Application (SPA) with the OAuth 2.0 implicit flow (coming soon). A single page application (primarily written in JavaScript, and often using dedicated frameworks like AngularJS, Durandal, Ember.js, etc.) that uses Azure AD to secure its web APIs back end. This scenario isn’t yet available in app model v2.0 but will be in a short order. Mobile and native application to web API with OAuth 2.0 authorization code flow. A mobile or native application that runs on a phone, tablet, or PC needs to authenticate a user to get resources from a web API that is secured by Azure AD. All components of the application, i.e. the mobile or native application and the web API, share a single Application ID as previously illustrated.Daemon or server side processes to web API with the OAuth 2.0 client credentials flow (coming soon). A daemon application or a server side process with no web user interface needs to get resources from a web API secured by Azure AD. Such applications can authenticate and get tokens using an application’s identity (rather than using a user’s delegated identity) with the OAuth 2.0 client credentials flow. This scenario isn’t yet available in the app model v2.0. Support for the client credentials flow will be added in the near future. In terms of modern protocols in the app model v2.0, you can observe that OAuth 2.0 and OpenID Connect 1.0 are at the heart of all the authentication and authorization flows. Taking into account the feedbacks received on the implementation of OAuth 2.0 and OpenID Connect 1.0, some updates you should be aware of have been made in the app model v2.pared the previously discussed tenant-independent endpoints (see eponym section earlier in this document), an application communicates with Azure AD by sending requests the v2.0 endpoints: "v2.0" in the above paths denotes the app model v2.0. Important noteApplications that are registered in the Azure management portal under the current app model don't work with the v2.0 endpoints. Similarly, v2.0 applications registered in the new portal don't work with the current endpoints. Beyond that, the most important difference from the current app model is the usage of the scope parameter: Previously you had to declare what permissions your application needed at registration time (See section REF _Ref406079547 \h \* MERGEFORMAT Enabling the client application to access the web API). With the app model v2.0, you request permissions at run time using the scope parameter. This allows your application to ask for permissions incrementally as they are needed, instead of requiring a user to consent to everything up front. The service determines the target of the token using the scope parameter instead of the resource parameter. The resource parameter is no longer required. Finally, to receive a refresh token, your application must specify the offline_access scope. NoteFor additional information, see the articles App model v2.0 preview: What's different?, App model v2.0 preview: Protocols - OAuth 2.0 & OpenID Connect, and App model v2.0 preview: Token reference.The app model v2.0 allow you to make protocol calls directly by constructing the HTTP messages necessary to communicate with the Azure AD endpoints. This makes identity management possible on virtually almost every platform and device. This said, and like for the current app model, (preview) versions of the ADAL libraries and server-side SDKs that take care of the protocol details for you are available to ease the development. For the .NET version of ADAL, this means that you two versions in preview simultaneously:The ADAL for .NET 3.0 Preview version that uses the current app model.And the experimental v4 version that uses the app model v2.0.While the app model v2.0 preview is experimented, the protocols, client libraries and server-side SDKs, and tools of the current app model previously covered in the core of this document remain fully supported. Microsoft is currently working on how modern applications written to the current app model can evolve to the app model v2.0. For example, people who have apps registered in Azure AD in the current model should be able to take full advantage of the new registration portal. Important noteif needed, and beyond and above information, you can get help on Stack Overflow using the azure-active-directory or adal tags.NoteYou can also share your thoughts and/or feature suggestions on the app model v2.0 preview using User Voice with the phrase" AppModelv2:" in the title of your post so that it can be found.This concludes this paper and our guided tour of the capabilities provided by Azure AD for the development of modern applications. We hope you enjoy your ”journey”.The information contained in this document represents the current view of Microsoft Corporation on the issues discussed as of the date of publication. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information presented after the date of publication.This white paper is for informational purposes only. Microsoft makes no warranties, express or implied, in this plying with all applicable copyright laws is the responsibility of the user. Without limiting the rights under copyright, no part of this document may be reproduced, stored in, or introduced into a retrieval system, or transmitted in any form or by any means (electronic, mechanical, photocopying, recording, or otherwise), or for any purpose, without the express written permission of Microsoft Corporation.Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual property rights covering subject matter in this document. Except as expressly provided in any written license agreement from Microsoft, the furnishing of this document does not give you any license to these patents, trademarks, copyrights, or other intellectual property.? 2016 Microsoft Corporation. All rights reserved.The example companies, organizations, products, domain names, e-mail addresses, logos, people, places, and events depicted herein are fictitious. No association with any real company, organization, product, domain name, e-mail address, logo, person, place, or event is intended or should be inferred. Microsoft, list Microsoft trademarks used in your white paper alphabetically are either registered trademarks or trademarks of Microsoft Corporation in the United States and/or other countries.The names of actual companies and products mentioned herein may be the trademarks of their respective owners. ................
................
In order to avoid copyright disputes, this page is only a partial summary.
To fulfill the demand for quickly locating and searching documents.
It is intelligent file search solution for home and business.
Related download
- 05072018 build scott guthrie part 1
- an overview of azure active directory
- university of florida thesis or dissertation
- community psychology fall 04 section 2 phd seminar
- also keep an eye out for maxwell school of citizenship
- leverage azure ad for modern business applications
- replace with the title of your dissertation
- althauser robert p 1989 internal labor markets
Related searches
- post my ad for free
- post ad for free online
- free ad for employment
- craigslist place ad for sale
- grants for home business for women
- sample newspaper ad for employment
- grants for small business for coronavirus
- azure database for mysql backup
- best modern business card designs
- post a ad for free
- another word for modern technology
- business plan for small business start up