Leverage Azure AD for modern business applications

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 http://example.com/resources/
  • the 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:

  1. Web applications and web APIs on Azure or in other clouds such Amazon Web Services (AWS),
  1. SaaS applications or multi-tenant applications such as the Microsoft Office 365, which relies on it for its identity infrastructure (or not),
  2. Mobile and native applications (with or without a back-end in the cloud like the one proposed through the Azure Mobile Apps),

Note    With 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.

Note    The 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 paper

As 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:

  1. 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.
  1. 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.
  2. Understand the various protocol flows that sustain the aforementioned single sign-on and single sign-out capabilities.
  3. 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.
  4. 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 paper

This 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 capability.

Organization of this paper

To cover the aforementioned objectives, this document is organized by themes which are covered in the following sections:

  • Providing identity and access management to your (new) applications.
  • Adding a web application for Single Sign-On (SSO) (and more).
  • Adding a web API for Single Sign-On (SSO).
  • Adding a native application for Single Sign-On (SSO).
  • Allowing external identities with your application.
  • Introducing the App model v2.0.

About the audience

This 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) applications

Azure 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.

Note    This 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 https://account.windowsazure.com/PremiumOffer/Index?offer=MS-AZR-0110P&whr=azure.com.

Note    Independently of any Microsoft Online Services subscriptions, you can sign-up for your free Windows AD tenant and trial Azure account by following the link https://account.windowsazure.com/signup?offer=MS-AZR-0044P.

  • 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.

Note    The 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.

Note    To sign up and start using this edition, see the MSDN article Getting started with Azure AD Premium.

Note    For 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 directory

Azure 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.

Note    Single 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.

Note    For 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) protocols

Usual 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.

Note    For 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:

These two protocols use SAML security tokens.

Note    For 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.

Note    These 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.

Note    Protocol 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.

Note    For 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.

Note    For 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.

Note    For more information, see the Microsoft MSDN article OpenID Connect 1.0.

OpenID Connect 1.0 provides:

  1. 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.
  2. 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.

Note    For 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.

Note    The 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 STS

As 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:

  1. The login.microsoftonline.com sign in service.
  2. And login.windows.net, which was the de-facto facade for modern business applications.

In this past service configuration, the login.microsoftonline.com 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.windows.net the policy and claims generation steps for modern application. Application authentication was thus handled directly by login.windows.net. login.windows.net acted as a federation provider, which trusted a single authority: the login.microsoftonline.com sign-in service.

As of today, all authentication requests can now be served directly by the login.microsoftonline.com 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 note    Applications that send requests to login.windows.net continue to be supported. The redirect to login.microsoftonline.com 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.

Note    For more information, see the blog post Simplifying our Azure AD Authentication Flows.

Tenant-specific endpoints

Azure 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:

https://login.microsoftonline.com/<tenant domain name>/<protocol>

Where <tenant domain name> can be:

  • A registered domain name of an Azure AD directory tenant, for example corpfabrikam.onmicrosoft.com.
  • The immutable tenant id of the domain, such as
    90995f16-6b12-4032-8b87-fd59566ed917

And <protocol> refers to a supported security protocols such as saml2 for the SAML 2.0 protocol support.

login.microsoftonline.com 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:

https://login.microsoftonline.com/<tenant domain name>/FederationMetadata/2007-06/FederationMetadata.xml

For example, the Azure AD testing directory tenant corpfabrikam.onmicrosoft.com (90995f16-6b12-4032-8b87-fd59566ed917) corresponds to:

https://login.microsoftonline.com/90995f16-6b12-4032-8b87-fd59566ed917/federationmetadata/2007-06/federationmetadata.xml

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.

Note    The 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:

  1. A passive tenant-specific endpoint for Web clients (browser) based on the WS-Federation protocol, as follows:

https://login.microsoftonline.com/<tenant domain name>/wsfed

For our directory tenant corpfabrikam.onmicrosoft.com, this corresponds to:

https://login.microsoftonline.com/90995f16-6b12-4032-8b87-fd59566ed917/wsfed

This 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.

  1. Another passive endpoint for Web clients (browser) for the SAML 2.0 protocol, as follows:

https://login.microsoftonline.com/<tenant domain name>/saml2

For our directory tenant corpfabrikam.onmicrosoft.com, this corresponds to:

https://login.microsoftonline.com/90995f16-6b12-4032-8b87-fd59566ed917/saml2

This 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.

Note    For more information, see the Microsoft MSDN article SAML Protocol Reference.

login.microsoftonline.com 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:

  1. One endpoint at which applications can obtain an access token using OAuth 2.0, as follows:

https://login.microsoftonline.com/<tenant domain name>/oauth2/token

For our directory tenant corpfabrikam.onmicrosoft.com, this corresponds to:

https://login.microsoftonline.com/90995f16-6b12-4032-8b87-fd59566ed917/oauth2/token

After an application is authenticated, Azure AD will issue the application an access token that allows the application to call the requested web API.

  1. And another endpoint at which an application can obtain an authorization token using OAuth 2.0, as follows:

https://login.microsoftonline.com/<tenant domain name>/oauth2/authorize

For our directory tenant corpfabrikam.onmicrosoft.com, this corresponds to:

https://login.microsoftonline.com/90995f16-6b12-4032-8b87-fd59566ed917/oauth2/authorize

Note    For more information, see the Microsoft MSDN article OAuth 2.0 in Azure AD.

Finally, login.microsoftonline.com 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:

https://login.microsoftonline.com/<tenant domain name>/.well-known/openid-configuration

For our directory tenant corpfabrikam.onmicrosoft.com, this corresponds to:

https://login.microsoftonline.com/90995f16-6b12-4032-8b87-fd59566ed917/.well-known/openid-configuration

  • One endpoint at which applications can obtain user information, as follows:

https://login.microsoftonline.com/<tenant domain name>/openid/userinfo

For our directory tenant corpfabrikam.onmicrosoft.com, this corresponds to:

https://login.microsoftonline.com/90995f16-6b12-4032-8b87-fd59566ed917/openid/userinfo

  • One sign-out endpoint as follows:

https://login.microsoftonline.com/<tenant domain name>/oauth2/logout

For our directory tenant corpfabrikam.onmicrosoft.com, this corresponds to:

https://login.microsoftonline.com/90995f16-6b12-4032-8b87-fd59566ed917/oauth2/logout

  • One endpoint that helps applications checking if the current user session is active, as follows:

https://login.microsoftonline.com/<tenant domain name>/oauth2/checksession

For our directory tenant corpfabrikam.onmicrosoft.com, this corresponds to:

https://login.microsoftonline.com/90995f16-6b12-4032-8b87-fd59566ed917/openid/oauth2/checksession

Note    For 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.windows.net endpoints are still honored and redirect to the equivalent login.microsoftonline.com endpoint. As an illustration, and as far as OpenID Connect 1.0 is concerned, the discovery endpoint https://login.windows.net/90995f16-6b12-4032-8b87-fd59566ed917/.well-known/openid-configuration continues to return legacy login.windows.net based endpoints. Those endpoints then follow the appropriate redirects. The aforementioned actual discovery endpoint https://login.microsoftonline.com/90995f16-6b12-4032-8b87-fd59566ed917/.well-known/openid-configuration returns equivalent login.microsoftonline.com 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 https://sts.windows.net/ based.
Tenant-independent endpoints

Tenant-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 https://login.microsoftonline.com/<tenant domain name>/<protocol>, the tenant-independent endpoints https://login.microsoftonline.com/common/<protocol> 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:

https://login.microsoftonline.com/common/discovery/keys

As noticed before, the now legacy login.windows.net endpoints are still honored and redirect to the equivalent login.microsoftonline.com 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 https://github.com/AzureAD/ for a variety of platforms: OSes or development stacks. They are further depicted in this section

  • Libraries 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 stackoverflow.com 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 stackoverflow.com. You can use the "adal" tag so we can see it. The latest Q&A on stackoverflow.com for ADAL is available at http://stackoverflow.com/questions/tagged/adal.

ADAL for.NET 2.x

The ADAL for.NET 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:

  1. 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.
  2. 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.204221202

Note    For 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 for.NET 3.0 Preview

This 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.0

Similarly 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.0

The 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 ASP.NET web API backend.

Leveraging other libraries

This 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-in

The extremely flexible and modular Passport authentication middleware for Node.js. can be unobtrusively dropped in to any Express-based or Restify web application.

Note    Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications.

Note    Restify 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 module

To 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.5

The 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 ASP.NET 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 ASP.NET/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.WsFederation

Likewise, 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. OpenIdConnect

Note    For more information on how to use the OWIN components with Azure AD, see the MSDN Magazine article Secure ASP.NET 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.5

The 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.

Note    For 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.Jwt

The 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.ValidatingIssuerNameRegistry

Accessing the directory data

Leveraging the Azure AD Graph API

Azure 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:

https://graph.windows.net/<tenant 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.onmicrosoft.com.
    • The immutable tenant id of the domain, such as
      90995f16-6b12-4032-8b87-fd59566ed917

Such as:

https://graph.windows.net/corpfabrikam.onmicrosoft.com/

  • <entity> 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:

https://graph.windows.net/corpfabrikam.onmicrosoft.com/users?api-version=1.6

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.onmicrosoft.com 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:

  • https://graph.windows.net/me
  • https://graph.windows.net/myorganizations/users

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:

https://graph.windows.net/corpfabrikam.onmicrosoft.com/users/philber@corpfabrikam.onmicrosoft.com?api-version=2013-04-05

provides 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": "https://graph.windows.net/corpfabrikam.onmicrosoft.com/$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.onmicrosoft.com
}

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:

https://graph.windows.net/corpfabrikam.onmicrosoft.com/users/philber@corpfabrikam.onmicrosoft.com/memberOf?api-version=2013-04-05  

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.onmicrosoft.com:

{
"odata.metadata": "https://graph.windows.net/corpfabrikam.onmicrosoft.com/$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:

https://graph.windows.net/<tenant domain name>/<entity>?api-version=<version>&deltaLink=

Such as:

https://graph.windows.net/corpfabrikam.onmicrosoft.com/directoryObjects?api-version=2013-04-05&deltaLink=

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": "https://graph.windows.net/corpfabrikam.onmicrosoft.com/$metadata#directoryObjects",
"aad.nextLink": "https://graph.windows.net/corpfabrikam.onmicrosoft.com/directoryObjects?deltaLink=XARBN7ivjcS6QIhSZDQR3OkT15SO1eeY-01BZSS0sOct6sh5oEyqOLLKRVhRmBMLHhePUF... [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.onmicrosoft.com
}
]
}

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:

https://graph.windows.net/corpfabrikam.onmicrosoft.com/directoryObjects?api-version=2013-04-05&deltaLink=XARBN7ivjcS6QIhSZDQR3OkT15SO1eeY-01BZSS0sOct6sh5oEyqOLLKRVhRmBMLHhePUF... [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": "https://graph.windows.net/corpfabrikam.onmicrosoft.com/$metadata#directoryObjects",
"aad.deltaLink": "https://graph.windows.net/corpfabrikam.onmicrosoft.com/directoryObjects?deltaLink=2O3f9hvaK62A-wIr-oj5sAUMnVNv21k-kIPYZymYDryWzrd0sQrB72EX6TpzPBep2n8v... [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.

Note    For 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.

Note    For 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).

Note    For 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 extension

Starting 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:

https://graph.windows.net/<tenant domain name>/applications/<application object Id>/extensionProperties?api-version=1.5

Where:

  • <tenant domain name> can be:
    • A registered domain name of an Azure AD directory tenant, for example corpfabrikam.onmicrosoft.com.
    • The immutable tenant id of the domain, such as
      90995f16-6b12-4032-8b87-fd59566ed917

Such as:

https://graph.windows.net/corpfabrikam.onmicrosoft.com/

  • <application 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.onmicrosoft.com, you simply do a POST as follows:

POST https://graph.windows.net/corpfabrikam.onmicrosoft.com/applications/269fc2f7-6420-4ea4-be90-9e1f93a87a64/extensionProperties?api-version=1.5 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": "https://graph.windows.net/contoso.onmicrosoft.com/$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:

  1. 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.
  1. 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 Library

The 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.GraphClient

The 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.

Note    For 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.

Note    To 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.

Note    For 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 GitHub

Microsoft provides a full suite of sample applications and documentation on GitHub at https://github.com/AzureADSamples
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.

Note    To 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 application

Web 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:

  1. Registering the web application in your directory,
  2. Configuring a web project for single sign-on (and single sign-out) support with Azure AD
  3. Querying 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:

  1. 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:

  1. The service class that represents the (type of the) application. This parallels the notion of service class in the SPN model for WSAD.
  2. 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 https://localhost:44301 for an app being developed in Visual Studio, <your application>.azurewebsites.net for an ASP.NET web application hosted on Azure Web Apps, etc.

Note    When 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.

  1. 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.

  1. 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.microsoftonline.com or for backward compatibility login.windows.net) 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.
  2. 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).
  3. 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.
  4. 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, https://localhost:44301/ for an app being developed in Visual Studio, https://fabrikamportal.azurewebsites.net/ for an ASP.NET 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 AD

This 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-federation

A tenant-specific federation metadata document is published via a single discovery endpoint to integrate your directory into the application you're developing:

https://login.microsoftonline.com/<tenant domain name>/FederationMetadata/2007-06/FederationMetadata.xml

For example, our directory corpfabrikam.onmicrosoft.com (90995f16-6b12-4032-8b87-fd59566ed917) corresponds to:

https://login.microsoftonline.com/90995f16-6b12-4032-8b87-fd59566ed917/federationmetadata/2007-06/federationmetadata.xml

For backward compatibility, the login.windows.net based discovery endpoint is still exposed:

https://login.windows.net/<tenant domain name>/FederationMetadata/2007-06/FederationMetadata.xml

The 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, ASP.NET 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 ASP.NET 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 ASP.NET 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 ASP.NET and Web Tools for Visual Studio 2013 extends the ASP.NET project templates and tooling experience to integrate Azure AD authentication and management features right at project creation time. The ASP.NET and Web Tools for Visual Studio 2013 are bundled in the main installer of ASP.NET along with the Web Platform Installer (WebPI) for installation.

Once installed, when you create a new ASP.NET 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 ASP.NET Identity (formerly known as ASP.NET membership).

To configure your web project for using your Azure AD directory's organizational accounts, proceed with the following steps:

  1. Click Change Authentication. An eponym Change Authentication dialog brings up.
  2. Select Organizational Accounts on the left side.

  1. Select Cloud – Single Organization to enable authentication for user accounts that are defined in your directory tenant, for example, the corpfabrikam.onmicrosoft.com tenant in our illustration.
  2. In Domain, enter the domain that you want to set up the web application in, for example, the default domain corpfabrikam.onmicrosoft.com in our illustration. If you have defined in your directory a custom federated Internet domain such fabrikam.com in lieu of corpfabrikam.onmicrosoft.com, you can specify that domain.
  3. 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.
  4. 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.onmicrosoft.com, the application ID URI becomes https://corpfabrikam.onmicrosoft.com/WebApp.

If 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 https://corpfabrikam.onmicrosoft.com /WebApp_20131213330903.

  1. Click OK. An ADAL Sign in dialog brings up.

Important note    You
must sign in with an organizational account: the ASP.NET 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 ASP.NET Project with Organizational Authentication Requires an Organizational Account.

  1. 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.

  1. 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=corpfabrikam.com" where corpfabrikam.com 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.

Note    For
more information, see the blog post Easy Web App Integration with Azure Active Directory, ASP.NET & Visual Studio.

Important note    The above tooling leverages the legacy login.windows.net based endpoints as they have been shipped before the change occurs.

The forthcoming release of Visual Studio 2015 will bring similar capabilities with new ASP.NET 4.6 projects templates and tools.

Note    For
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:

  1. Redirection to https://login.microsoftonline.com/corpfabrikam.onmicrosoft.com/wsfed,
  2. And then redirection to https://localhost:44301/.

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:

http://schemas.microsoft.com/identity/claims/tenantid:
90995f16-6b12-4032-8b87-fd59566ed917

  • Name. For display only:

http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name:
philber@corpfabrikam.onmicrosoft.com

  • First Name. For display only:

http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname:
Philippe

  • Last Name. For display only:

http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname:
Beraud

  • Object ID. Immutable security identifier:

http://schemas.microsoft.com/identity/claims/objectidentifier:
85143067-d315-4c23-b1b6-a2a33a4f0d9b

Note     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 ASP.NET 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.

Note    For 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 ASP.NET 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.0

A 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:

https://login.microsoftonline.com/<tenant domain name>/FederationMetadata/2007-06/FederationMetadata.xml

For example, our directory corpfabrikam.onmicrosoft.com (90995f16-6b12-4032-8b87-fd59566ed917) corresponds to:

https://login.microsoftonline.com/90995f16-6b12-4032-8b87-fd59566ed917/federationmetadata/2007-06/federationmetadata.xml

This is the same endpoint as the one discussed above with WS-Federation. Likewise, for backward compatibility, the login.windows.net 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="https://sts.windows.net/90995f16-6b12-4032-8b87-fd59566ed917/" xmlns="urn:oasis:names:tc:SAML:2.0:metadata">
...
</EntityDescriptor>

This value is "https://sts.windows.net/90995f16-6b12-4032-8b87-fd59566ed917/" 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="https://sts.windows.net/90995f16-6b12-4032-8b87-fd59566ed917/" xmlns="urn:oasis:names:tc:SAML:2.0:metadata">
...
<IDPSSODescriptor protocolSupportEnumeration="urn:oasis:names:tc:SAML:2.0:protocol">
<KeyDescriptor use="signing">
<KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
<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="http://www.w3.org/2000/09/xmldsig#">
<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="https://login.microsoftonline.com/90995f16-6b12-4032-8b87-fd59566ed917/saml2"
Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect"/>
<SingleSignOnService Location="https://login.microsoftonline.com/90995f16-6b12-4032-8b87-fd59566ed917/saml2"
Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect"/>
<SingleSignOnService Location="https://login.microsoftonline.com/90995f16-6b12-4032-8b87-fd59566ed917/saml2"
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:

https://login.microsoftonline.com/90995f16-6b12-4032-8b87-fd59566ed917/saml2

The 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 § 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 Connect

A 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:

https://login.microsoftonline.com/<tenant domain name>/.well-known/openid-configuration

For example, our directory corpfabrikam.onmicrosoft.com (90995f16-6b12-4032-8b87-fd59566ed917) corresponds to:

https://login.microsoftonline.com/90995f16-6b12-4032-8b87-fd59566ed917/.well-known/openid-configuration

All 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:

https://login.microsoftonline.com/<tenant domain name>/oauth2/authorize

For example, our directory corpfabrikam.onmicrosoft.com (90995f16-6b12-4032-8b87-fd59566ed917) corresponds to:

https://login.microsoftonline.com/90995f16-6b12-4032-8b87-fd59566ed917/oauth2/authorize

Following is an example of an OpenID Connect Authorize request:

https://login.microsoftonline.com/90995f16-6b12-4032-8b87-fd59566ed917/oauth2/authorize?response_type=id_token&client_id=
273a01b1-c73d-49fa-a1f7-7c75d817fd72 scope=openid&nonce=393b61fa-8cc3-4c52-a167-472ae18fe934&response_mode=form_post&redirect_uri=https%3a%2f%2fwebapp1%2f

Where:

  • "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 § 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.

Note    For 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 ASP.NET 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 refresh

The 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:

https://login.microsoftonline.com/common/.well-known/openid-configuration

Note    For 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 note    There 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 ASP.NET, 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 § Leveraging the Active Directory Authentication Library (ADAL) and Leveraging other libraries) and related samples (see section § Leveraging the various available code samples on GitHub) provided by Microsoft do the above automatically.

Handling single sign out

The 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 ASP.NET MVC template used as illustration with the ASP.NET 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 API

While 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 framework

First 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:

  1. Select in Azure management portal the application created above in the single sign-on part.

  1. Expand the ACCESS WEB APIS IN OTHER APPLICATIONS under CONFIGURE.

  1. Click Configure it now under SELECT PERMISSIONS. The application properties page will appear.
  2. 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 § Defining the web API permissions later in this document).

By default, you can choose permissions from Azure AD Graph API (Windows Azure Active Directory).

Note    If 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.

  1. 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.

Note    Once 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 name

Description

Permission type

Enable sign-on and read users' profiles

Allow 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 directory

Allow 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 data

Allow the application to read data in your organization's directory, such as users, groups and applications

Delegation and application permission. Must be consented by an administrator.

Read and write directory data

Allow the application to read and write data in your organization's directory, such as users and groups

Delegation and application permission. Must be consented by an administrator.

Note    Setting 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:

  1. In the Quick Start page for the web application, expand ACCESS WEB APIS IN OTHERS APPLICATIONS.

  1. Copy the supplied Client ID (UPDATE YOUR CODE WITH YOUR CLIENT ID) for your application in the directory.
  2. Under CREATE A KEY, click Configure key. The application properties page appears.
  3. Scroll down to keys.

  1. 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.

  1. Click SAVE at the tray of the bottom.

  1. 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 ASP.NET 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="https://login.microsoftonline.com/corpfabrikam.onmicrosoft.com/FederationMetadata/2007-06/FederationMetadata.xml" />
<add key="ida:Realm" value="https://corpfabrikam.onmicrosoft.com/WebApplication1" />
<add key="ida:AudienceUri" value="https://corpfabrikam.onmicrosoft.com/WebApplication1" />

<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:

  1. "aud" that identifies the audience that the token is intended for in form of an URI, for example https://corpfabrikam.onmicrosoft.com/WebApplication1 in our illustration.
  2. "iss" that identifies the issuer of the token.

{
"aud": "https://corpfabrikam.onmicrosoft.com/WebApplication1",
"iss": http://sts.windows.net/90995f16-6b12-4032-8b87-fd59566ed917/",

}

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=minimalmetadata
Authorization: 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:

  1. Create an organization's tenant-specific Azure AD Graph API endpoint, for example in our configuration:

https://graph.windows.net/90995f16-6b12-4032-8b87-fd59566ed917

  1. Use the endpoint to instantiate the proxy to call the Azure AD Graph API.
  2. 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.

Note    PHP 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.

Note    For more information, see the MSDN documentation of the Azure AD Graph API.

Using Azure AD for authorization

In 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.

Note    For 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.

Note    To 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.

Protocol

Groups claim issued?

WS-Federation

Yes in the SAML token in the attribute name 'http://schemas.microsoft.com/ws/2008/06/identity/claims/groups'. This is a multi-valued attribute.

SAML 2.0. Response over POST binding

Yes in the SAML token in the attribute name 'http://schemas.microsoft.com/ws/2008/06/identity/claims/groups'. This is a multi-valued attribute.

OpenID Connect 1.0 (id token). Response over POST binding

Yes in the id token in the "groups" node.

OpenID Connect 1.0 (id token) Response over query string or fragment

No

Note    For 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.

Protocol

Groups claim issued

WS-Federation

Yes in the SAML token in the attribute name 'http://schemas.microsoft.com/ws/2008/06/identity/claims/roles'. This is a multi-valued attribute.

SAML 2.0

Yes in the SAML token in the attribute name 'http://schemas.microsoft.com/ws/2008/06/identity/claims/roles'. This is a multi-valued attribute.

OpenID Connect 1.0 (id token)

Yes in the id token in the "groups" node.

Note    For 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 claim

From 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:

  1. From the Azure management portal, click ACTIVE DIRECTOY on the left pane, and then click on the desired directory.
  2. Click APPLICATIONS, and then click the application you want to configure. The Quick Start page appears with single sign-on and other configuration information.
  1. Click MANAGE MANIFEST at the bottom of the, and select Download Manifest.

A Download Manifest dialog pops up.

  1. Select Download manifest.

  1. Click Save to locally save the application manifest file.
    1. 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": "https://localhost:44301/",
"identifierUris": [
https://corpfabrikam.onmicrosoft.com/WebApplication1
],
"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": [
https://localhost:44301/
],
"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": []
}

  1. 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:

  1. "SecurityGroup". The groups claim will contain the identifiers of all security groups of which the user is a member.

– or –

  1. "All". The groups claim will contain the identifiers of all security groups and all distribution lists of which the user is a member.
  1. Once set, save the modified application manifest file.
  2. Click MANAGE MANIFEST at the bottom of the, and select Upload Manifest. An Upload Manifest dialog pops up.

  1. Click BROWSE FOR FILE and point to the modified application manifest file.


  1. 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 § Configuring the desired permissions with the consent framework earlier in this document.)

Defining application roles

From 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:

  1. From the Quick Start page of the application in the Azure management portal, download the application manifest file if not already done.
  1. 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": "https://localhost:44301/",
"identifierUris": [
https://corpfabrikam.onmicrosoft.com/WebApplication1
],
"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": [
https://localhost:44301/
],
"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": []
}

  1. 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 name

Description

allowedMemberTypes

Specifies 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)

description

Help description for the application role in the admin app assignment and consent experiences

displayName

Friendly name for the application role shown in the admin consent and app assignment experiences.

id

GUID exposed by the web application for the application role. It must be unique amongst all application roles for the web application.

isEnabled

Always 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.

origin

Reserved for future use. Always set to "application".

value

Value 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.

Note    For more information, see the Microsoft MSDN article AppRole.

  1. 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 roles

Once 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 note    If 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 note    If 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 roles

To 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 note    This 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 application

Even 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 available

This 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.

Note    When 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 https://.

Once 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 application

The 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 framework

With 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.onmicrosoft.com:

https://login.microsoftonline.com/corpfabrikam.onmicrosoft.com/oauth2/authorize?response_type=id_token&client_id=8ed7dd71-1d25-4030-a037-012d3329fd10&redirect_uri=https://locahost:44301/HandleAuthorizeResponse&nonce=8ed7dd71-1d25-4c36-1654-012d3329fd10&response_mode=form_post&prompt=admin_consent.

As 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.

Note    For more information, see the Microsoft TechNet article Adding, Updating, and Removing an Application.

Granting access with the consent experience prior to March 12, 2014

The "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:

  1. Prepare the application's project to handle multiple tenants
  2. Add sign-up capabilities to the application

The article Developing Multi-Tenant Web Applications with Azure AD
outlines how to build a multi-tenant web ASP.NET MVC 4 application that can be used by organizations that have Azure AD.

Important note    This 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 configuration

As previously mentioned, in lieu of the tenant-specific endpoints https://login.windows.net/<tenant domain name>/<protocol>, the tenant-independent endpoints https://login.windows.net/common/<protocol> 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 note    Azure 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 ASP.NET MVC template in Visual Studio 2013 handles all of this for you as illustrated above. To come back to our previous illustration with the ASP.NET 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 data

Calls 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 ASP.NET 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 application

This 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:

https://account.activedirectory.windowsazure.com/Consent.aspx

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:
  1. None. This setting enables single sign-on but disables access to directory data.
  2. 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.
  3. 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:

https://account.activedirectory.windowsazure.com/Consent.aspx?ClientId=24f8f1fe-e8b1-4201-b891-684048adf3a5&RequestedPermissions=DirectoryReaders&ConsentReturnURL=https%3a%2f%2flocalhost%3a44306%2fTenant%2fSignUpCallback%3fsignupToken%3dda9d74b3-4655-44b4-9419-f4f80220a416

Where:

  • ClientID is C24f8f1fe-e8b1-4201-b891-684048adf3a5,
  • RequestedPermissions equals DirectoryReaders,
  • And the ConsentReturnURL is https://localhost:44306/Tenant/SignUpCallback?signupToken=da9d74b3-4655-44b4-9419-f4f80220a416.
Handling the consent response

After 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:

  1. 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.
  2. 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:

https://localhost:44306/Tenant/SignUpCallback?signupToken=da9d74b3-4655-44b4-9419-f4f80220a416&Consent=Granted&TenantId=90995f16-6b12-4032-8b87-fd59566ed917

Where:

  • Consent equals Granted
  • And TenantId is 90995f16-6b12-4032-8b87-fd59566ed917 (corpfabrikam.onmicrosoft.com)

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 application

In terms of application listing, the Azure marketplace can increase the discoverability of your multi-tenant application and consequently the lead generation.

Note    For 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:

  • Registering the web API in the directory tenant.
  • Configuring the web API project for Azure AD.
  • Defining the web API application roles and permissions.
  • Enabling the client application to access the web API.

Registering the web API in the directory tenant

As 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:

  1. Sign into the Azure management portal as the administrator of the directory to configure.
  2. 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.
  3. 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.

  1. Click Add an application my organization is developing.

  1. 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.

  1. 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.

Note    With 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.

  1. 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 ASP.NET 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:

  1. Click Change Authentication. An eponym Change Authentication dialog brings up.
  2. Select Organizational Accounts on the left side.

  1. Select Cloud – Single Organization to enable authentication for user accounts that are defined in your directory tenant, for example, the corpfabrikam.onmicrosoft.com tenant in our illustration.
  2. 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.onmicrosoft.com in our illustration. If you have defined in your directory a custom federated Internet domain such fabrikam.com in lieu of corpfabrikam.onmicrosoft.com, you can specify that domain.
  3. 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.
  4. 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.onmicrosoft.com, the application ID URI becomes https://corpfabrikam.onmicrosoft.com/WebAPI.

As previously illustrated, if you want to manually specify the application ID URI, expand More Options.

  1. Click OK. An ADAL Sign in dialog brings up.

  1. 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.

  1. Click OK to finalize the configuration of the web API project.

The ASP.NET and Web Tools for Visual Studio 2013 actually performs two tasks:

  1. It reaches out to the selected directory and add an entry describing the web API being created.
  2. 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.

Note    For 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 permissions

To 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 roles

To define the applications roles for the web API, proceed with the following steps:

  1. From the Quick Start page of the application in the Azure management portal, download the application manifest file if not already done.
  2. 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": "https://localhost:44302/",
"identifierUris": [
https://corpfabrikam.onmicrosoft.com/WebApi1
],
"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": [
https://localhost:44302/
],
"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": []
}

  1. 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.

  1. 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 permissions

To define the set of permissions for the web API, proceed with the following steps:

  1. From the Azure management portal, click ACTIVE DIRECTOY on the left pane, and then click on the desired directory.
  2. Click APPLICATIONS, and then click the application you want to configure. The Quick Start page appears with single sign-on and other configuration information.
  3. Click EXPOSE WEB APIS TO OTHERS APPLICATIONS under CONFIGURE.


  1. Click MANAGE MANIFEST at the bottom of the tray, and select Download Manifest to download the application manifest file if not already done.
    1. 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": "https://localhost:44302/",
"identifierUris": [
https://corpfabrikam.onmicrosoft.com/WebApi1
],
"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": [
https://localhost:44302/
],
"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": []
}

  1. 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 name

Description

adminConsentDescription

Help description in the administrator's consent dialog and in the consented application's properties page

adminConsentDisplayName

Friendly 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.

id

GUID exposed by the web API for the permission scope. It must be unique amongst all permissions for the web API.

isEnabled

Always 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.

origin

Reserved for future use. Always set to "application".

type

Can be one of the following values:

"User": may be consented to by end users

"Admin": must be consented to by a company administrator

userConsentDescription

Help description in the user's consent dialog.

userConsentDisplayName

Friendly name for the permission shown to end-users during consent.

value

Value 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.

  1. 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 API

Using 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:

  1. The client application uses its own identity, i.e. the "app identity".

-or-

  1. 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:

  1. 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.
  2. 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:

  1. From the Azure management portal, click ACTIVE DIRECTOY on the left pane, and then click on the desired directory.
  2. 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.
  3. Click ACCESS WEB APIS IN OTHER APPLICATIONS under CONFIGURE.


  1. Click
    Configure it now under Select permissions. The application properties page shows up.
  2. Scroll down to Permissions to other applications.


  1. 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.

  1. Select All Apps in SHOW, and then click the checkmark on the right.

  1. Select the web API to call, for example WebAPI1 in our illustration, and then click the checkmark at the bottom on the right.


  1. 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.


  1. 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 identity

In 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:

  1. The configuration of a client credential that the confidential client employs to authenticate itself,
  2. 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 identity

Unlike 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 flow

With 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 code

Now 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.

Note    As 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 (https://locahost:44301/HandleAuthorizeResponse), and the App ID URI for the web API (https://localhost:44300/). 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.onmicrosoft.com:

https://login.microsoftonline.com/corpfabrikam.onmicrosoft.com/oauth2/authorize?resource=https://localhost:44300/&client_id=8ed7dd71-1d25-4030-a037-012d3329fd10&redirect_uri=https://locahost:44301/HandleAuthorizeResponse

The 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.

https://localhost:44301/HandleAuthorizeResponse?code=AAAAAAAA...............P5qd1L7x2BAP6bxxyD9KMgAA

At the end of this leg of the flow, the authorization code can be extracted in step 3.

Getting an access token with the authorization code

The 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.onmicrosoft.com:

https://login.microsoftonline.com/corpfabrikam.onmicrosoft.com/oauth2/token

The 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.onmicrosoft.com:

https://login.microsoftonline.com/corpfabrikam.onmicrosoft.com/oauth2/token?grant_type=authorization_code&client_id=8ed7dd71-1d25-4030-a037-012d3329fd10&redirect_uri=https://locahost:44301/HandleAuthorizeResponse&client_secret=
DhjYU…kqqyHiqNm/PY=&Code=AAAAAAAA...............P5qd1L7x2BAP6bxxyD9KMgAA

As 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 eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik5HVEZ2CzkwXeiVQ

Getting an access token with the refresh token

The 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.onmicrosoft.com:

https://login.microsoftonline.com/corpfabrikam.onmicrosoft.com/oauth2/token

The 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.onmicrosoft.com:

https://login.microsoftonline.com/corpfabrikam.onmicrosoft.com/oauth2/token?grant_type=refresh_token&client_id=8ed7dd71-1d25-4030-a037-012d3329fd10&client_secret=DhjYU…kqqyHiqNm/PY=&refresh_token=
AAAAAAAADENAfM5UpyznQ8EHSHp0GI8GTGXonaBFZHZADR1Kf...-Q9SAA

As 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 protocol

The 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 code

A 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 code

Using 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 identity

The 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 tenant

The directory tenant administrator creates the service principal at behest of developer.

To register a native application, proceed with the following steps:

  1. Sign into the Azure management portal as the administrator of the directory to configure.
  2. 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.
  3. 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.

  1. Click Add an application my organization is developing.

  1. 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.

  1. 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.

  1. 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 code

To update your code with the application's coordinates, proceed with the following steps:

  1. From the Quick Start page of the newly added application, click UPDATE YOUR CODE under GET STARTED.

  1. Copy the string next to REDIRECT URI and the value next to CLIENT ID.
  2. 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 user

Likewise, 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 directory

Both 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 § 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:

  1. From the Quick Start page of the newly added application, click CONFIGURE ACCESS TO WEB APIS IN OTHER APPLICATIONS under GET STARTED.

  1. Click Configure it now. The application properties page shows up.
  2. Scroll down to permissions to other applications.


  1. 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.

  1. Select All Apps in SHOW, and then click the checkmark on the right.

  1. Select the web API to call, for example WebAPI1 in our illustration, and then click the checkmark at the bottom on the right.
  2. Once added, select the delegation permissions that the web API exposes, for example "Access WebApp1" in our illustration.


  1. 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 API

The 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 identity

As 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.onmicrosoft.com:

httpslogin.microsoftonline.com/corpfabrikam.onmicrosoft.com/oauth2/authorize?response_type=code&resource=https://localhost:44300/&client_id=91498461-d9b9-4766-84ef-0b149f18f934 &redirect_uri=http://NativeApp1

This URL comprises the windows.net login URL, our domain (corpfabrikam.onmicrosoft.com), the response type we're looking for (code), the resource we want to access (https://localhost:44300/), our client ID (the alphanumeric string 91498461-d9b9-4766-84ef-0b149f18f934), and our redirect URI (http://NativeApp1) 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.

Note    As 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:

http://NativeApp1?code=AAAAAAAA...............P5qd1L7x2BAP6bxxyD9KMgAA&session_state=00a3cb02-67d2-42d5-bf03-18182d81f578

The important part here is the (authorization) code that comes back and that you need to pull out.

Getting an access token with the authorization code

To 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.onmicrosoft.com:

https://login.microsoftonline.com/corpfabrikam.onmicrosoft.com/oauth2/token

The 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:

  1. "access_token" is the JWT needed to call the web API RESTful service.
  2. "token_type" specifies what the type of token received by the application is, in this case Bearer as per RFC 6750.
  3. "expires_in" specifies how long until the JWT access tokens expires.
  4. "expires_on" specifies when does the JWT access token expires.
  5. "refresh_token" is the token can be used to request (behind the scenes without any user interaction) a new access token when that expires.
  6. "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 eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik5HVEZ2CzkwXeiVQ

Getting an access token with the refresh token

As 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 application

In 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.

Note    The 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.

Note    For 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.

Note    For 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.0

A 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.

Note    For 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 process

Registration 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: https://apps.dev.microsoft.com 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:

  1. Open a browsing session and navigate to the new portal at https://apps.dev.microsoft.com.

  1. Sign-in with either a personal account or a work or school account. This is the beauty of the app model.

  1. Click Add an app. A New Application Registration pops up.

  1. Provide a name for the application, for example "Corpfabrikam" to continue with our fictitious organization used throughout this document.
  2. Click Create application. The basic registration is complete, and your application has an Application ID.

  1. 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.

  1. Click Web.

  1. Under Redirect URIs, enter your web application's redirect URI, i.e. the location where authentication responses will be posted.
  2. For mobile application, click Add Platform, and then click Mobile application this time.

  1. 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.
  2. Click Save at the bottom of the page. Et voila!

That's all it takes to get registered!

Note    For 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 Authenticating against the directory), the app model v2.0 encompasses the same primary scenarios with some differences that are outlined hereafter:

Note    For 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.0.

Compared 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:

https://login.microsoftonline.com/common/oauth2/v2.0/authorize

https://login.microsoftonline.com/common/oauth2/v2.0/token

The "v2.0" in the above paths denotes the app model v2.0.

Important note    Applications 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 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.

Note    For 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:

  1. The ADAL for .NET 3.0 Preview version that uses the current app model.
  2. 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 note    if needed, and beyond and above information, you can get help on Stack Overflow using the
azure-active-directory
or adal
tags.

Note    You 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.