Download How to Integrate with Azure Active Directory | Microsoft Docs

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Table of Contents
Overview
Auth basics
Types of apps
Get Started
Mobile & Desktop apps
Overview
iOS
Android
.NET
Windows
Xamarin
Cordova
OAuth 2.0
Web apps
Overview
ASP.NET
Java
NodeJS
OpenID Connect
Single Page Apps
Overview
Angular JS
Javascript
Web APIs
Overview
ASP.NET
NodeJS
Service to Service
Overview
.NET
OAuth 2.0 Client Credentials
Guides
Application Registration
Multi-tenant apps
OAuth & OpenID Connect
OpenID Connect protocol
OAuth 2.0 auth code grant
OAuth 2.0 implicit grant
SAML 2.0
Customize Claims
Debug SAML-based SSO
Single Sign-On SAML protocol
Single Sign-Out SAML protocol
Create a tenant
Branding guidelines
Mobile & Desktop SSO
Enable SSO on Android
Enable SSO on iOS
Azure AD B2B
User Provisioning with SCIM
Azure AD Graph API
Get Started with AAD Graph
AppSource Certification
Azure AD App Gallery
Office 365 Seller Dashboard
Working with Visual Studio
Get started with Visual Studio connected services
Error during authentication detection
Get started with WebApi
What happened to my Web API project
Windows Server ADFS
Reference
Auth libraries (ADAL)
Code Samples
Glossary
Authentication Protocols
OpenID Connect
Oauth
Service to Service Calls
On-Behalf-Of flow
Supported Token and Claim Types
Signing key rollover
Federation Metadata
Application objects
Apps and Azure AD
Application manifest
Token lifetimes
Service Limits
v2.0 endpoint
Overview
Differences
Types of apps
Limitations
Quickstarts
Mobile Apps
Web apps and APIs
Guides
Register an app
Reference
App registration reference
Authentication libraries
v2.0 Authentication Protocols
Scopes
Azure Active Directory for developers
4/27/2017 • 1 min to read • Edit Online
Azure Active Directory is a cloud identity service that allows developers to securely sign-in any user with a
work or school account backed by Microsoft. The documentation here shows you how to add Azure AD
support to your application using industry standard authentication protocols, OAuth & OpenID Connect.
Auth basics
An introduction to authenication with Azure AD
Types of applications
An overview of the authentication scenarios supported by
Azure AD
Get started
These guided setups walk you through using our authentication libraries to sign in Azure Active Directory
users.
Mobile & Desktop Apps
Web Apps
Overview
.NET
Cordova
iOS
Windows
OAuth 2.0
Android
Xamarin
Overview
NodeJS
ASP.NET
OpenID Connect 1.0
Java
Overview
AngularJS
Single Page Apps
JavaScript
Overview
ASP.NET
Web APIs
NodeJS
Overview
.NET
Service-to-Service
Guides
OAuth 2.0 Client
Credentials
These articles inform you how to perform common tasks with Azure Active Directory.
App registration
How to register an app in Azure AD
Multi-tenant apps
How to sign in any Microsoft work account
OAuth & OpenID Connect
How to sign-in users and call web APIs using our modern
auth protocols
More guides...
Reference
These articles provide detailed information on APIs, protocol messages, and terms used in Azure Active
Directory.
Authentication Libraries (ADAL)
An overview of the libraries & SDKs provided by Azure AD
Code Samples
A list of all Azure AD code samples
Glossary
Terminology and definitions of words used throughout
this documentation
More reference material...
Help & Support
These are the best places to get help with developing on Azure Active Directory.
Stack Overflow's
azure-active-directory
and
adal
tags
Feedback on Azure Active Directory
NOTE
If you need to sign-in Microsoft personal accounts, you may want to consider using the Azure AD v2.0 endpoint. The
Azure AD v2.0 endpoint is the unification of Microsoft personal accounts & Microsoft work accounts (from Azure AD)
into a single authentication system.
Authentication Scenarios for Azure AD
4/27/2017 • 31 min to read • Edit Online
Azure Active Directory (Azure AD) simplifies authentication for developers by providing identity as a service, with
support for industry-standard protocols such as OAuth 2.0 and OpenID Connect, as well as open source libraries for
different platforms to help you start coding quickly. This document will help you understand the various scenarios
Azure AD supports and will show you how to get started. It’s divided into the following sections:
Basics of Authentication in Azure AD
Claims in Azure AD Security Tokens
Basics of Registering an Application in Azure AD
Application Types and Scenarios
Web Browser to Web Application
Single Page Application (SPA)
Native Application to Web API
Web Application to Web API
Daemon or Server Application to Web API
Basics of Authentication in Azure AD
If you are unfamiliar with basic concepts of authentication in Azure AD, read this section. Otherwise, you may want
to skip down to Application Types and Scenarios.
Let’s consider the most basic scenario where identity is required: a user in a web browser needs to authenticate to a
web application. This scenario is described in greater detail in the Web Browser to Web Application section, but it’s
a useful starting point to illustrate the capabilities of Azure AD and conceptualize how the scenario works. Consider
the following diagram for this scenario:
With the diagram above in mind, here’s what you need to know about its various components:
Azure AD is the identity provider, responsible for verifying the identity of users and applications that exist in an
organization’s directory, and ultimately issuing security tokens upon successful authentication of those users
and applications.
An application that wants to outsource authentication to Azure AD must be registered in Azure AD, which
registers and uniquely identifies the app in the directory.
Developers can use the open source Azure AD authentication libraries to make authentication easy by handling
the protocol details for you. See Azure Active Directory Authentication Libraries for more information.
• Once a user has been authenticated, the application must validate the user’s security token to ensure that
authentication was successful for the intended parties. Developers can use the provided authentication libraries to
handle validation of any token from Azure AD, including JSON Web Tokens (JWT) or SAML 2.0. If you want to
perform validation manually, see the JWT Token Handler documentation.
IMPORTANT
Azure AD uses public key cryptography to sign tokens and verify that they are valid. See Important Information About
Signing Key Rollover in Azure AD for more information on the necessary logic you must have in your application to ensure it’s
always updated with the latest keys.
• The flow of requests and responses for the authentication process is determined by the authentication protocol
that was used, such as OAuth 2.0, OpenID Connect, WS-Federation, or SAML 2.0. These protocols are discussed in
more detail in the Azure Active Directory Authentication Protocols topic and in the sections below.
NOTE
Azure AD supports the OAuth 2.0 and OpenID Connect standards that make extensive use of bearer tokens, including bearer
tokens represented as JWTs. A bearer token is a lightweight security token that grants the “bearer” access to a protected
resource. In this sense, the “bearer” is any party that can present the token. Though a party must first authenticate with Azure
AD to receive the bearer token, if the required steps are not taken to secure the token in transmission and storage, it can be
intercepted and used by an unintended party. While some security tokens have a built-in mechanism for preventing
unauthorized parties from using them, bearer tokens do not have this mechanism and must be transported in a secure
channel such as transport layer security (HTTPS). If a bearer token is transmitted in the clear, a man-in the middle attack can
be used by a malicious party to acquire the token and use it for an unauthorized access to a protected resource. The same
security principles apply when storing or caching bearer tokens for later use. Always ensure that your application transmits
and stores bearer tokens in a secure manner. For more security considerations on bearer tokens, see RFC 6750 Section 5.
Now that you have an overview of the basics, read the sections below to understand how provisioning works in
Azure AD and the common scenarios Azure AD supports.
Claims in Azure AD Security Tokens
Security tokens issued by Azure AD contain claims, or assertions of information about the subject that has been
authenticated. These claims can be used by the application for various tasks. For example, they can be used to
validate the token, identify the subject's directory tenant, display user information, determine the subject's
authorization, and so on. The claims present in any given security token are dependent upon the type of token, the
type of credential used to authenticate the user, and the application configuration. A brief description of each type
of claim emitted by Azure AD is provided in the table below. For more information, refer to Supported Token and
Claim Types.
CLAIM
DESCRIPTION
Application ID
Identifies the application that is using the token.
Audience
Identifies the recipient resource the token is intended for.
Application Authentication Context Class Reference
Indicates how the client was authenticated (public client vs.
confidential client).
Authentication Instant
Records the date and time when the authentication occurred.
CLAIM
DESCRIPTION
Authentication Method
Indicates how the subject of the token was authenticated
(password, certificate, etc.).
First Name
Provides the given name of the user as set in Azure AD.
Groups
Contains object Ids of Azure AD groups the user is a member
of.
Identity Provider
Records the identity provider that authenticated the subject of
the token.
Issued At
Records the time at which the token was issued, often used for
token freshness.
Issuer
Identifies the STS that emitted the token as well as the Azure
AD tenant.
Last Name
Provides the surname of the user as set in Azure AD.
Name
Provides a human readable value that identifies the subject of
the token.
Object Id
Contains an immutable, unique identifier of the subject in
Azure AD.
Roles
Contains friendly names of Azure AD Application Roles that
the user has been granted.
Scope
Indicates the permissions granted to the client application.
Subject
Indicates the principal about which the token asserts
information.
Tenant Id
Contains an immutable, unique identifier of the directory
tenant that issued the token.
Token Lifetime
Defines the time interval within which a token is valid.
User Principal Name
Contains the user principal name of the subject.
Version
Contains the version number of the token.
Basics of Registering an Application in Azure AD
Any application that outsources authentication to Azure AD must be registered in a directory. This step involves
telling Azure AD about your application, including the URL where it’s located, the URL to send replies after
authentication, the URI to identify your application, and more. This information is required for a few key reasons:
Azure AD needs coordinates to communicate with the application when handling sign-on or exchanging
tokens. These include the following:
Application ID URI: The identifier for an application. This value is sent to Azure AD during authentication
to indicate which application the caller wants a token for. Additionally, this value is included in the token
so that the application knows it was the intended target.
Reply URL and Redirect URI: In the case of a web API or web application, the Reply URL is the location to
which Azure AD will send the authentication response, including a token if authentication was successful.
In the case of a native application, the Redirect URI is a unique identifier to which Azure AD will redirect
the user-agent in an OAuth 2.0 request.
Application ID: The ID for an application, which is generated by Azure AD when the application is
registered. When requesting an authorization code or token, the Application ID and key are sent to Azure
AD during authentication.
Key: The key that is sent along with a Application ID when authenticating to Azure AD to call a web API.
Azure AD needs to ensure the application has the required permissions to access your directory data, other
applications in your organization, and so on
Provisioning becomes clearer when you understand that there are two categories of applications that can be
developed and integrated with Azure AD:
Single tenant application: A single tenant application is intended for use in one organization. These are typically
line-of-business (LoB) applications written by an enterprise developer. A single tenant application only needs to
be accessed by users in one directory, and as a result, it only needs to be provisioned in one directory. These
applications are typically registered by a developer in the organization.
Multi-tenant application: A multi-tenant application is intended for use in many organizations, not just one
organization. These are typically software-as-a-service (SaaS) applications written by an independent software
vendor (ISV). Multi-tenant applications need to be provisioned in each directory where they will be used, which
requires user or administrator consent to register them. This consent process starts when an application has
been registered in the directory and is given access to the Graph API or perhaps another web API. When a user
or administrator from a different organization signs up to use the application, they are presented with a dialog
that displays the permissions the application requires. The user or administrator can then consent to the
application, which gives the application access to the stated data, and finally registers the application in their
directory. For more information, see Overview of the Consent Framework.
Some additional considerations arise when developing a multi-tenant application instead of a single tenant
application. For example, if you are making your application available to users in multiple directories, you need a
mechanism to determine which tenant they’re in. A single tenant application only needs to look in its own directory
for a user, while a multi-tenant application needs to identify a specific user from all the directories in Azure AD. To
accomplish this task, Azure AD provides a common authentication endpoint where any multi-tenant application can
direct sign-in requests, instead of a tenant-specific endpoint. This endpoint is
https://login.microsoftonline.com/common for all directories in Azure AD, whereas a tenant-specific endpoint might
be https://login.microsoftonline.com/contoso.onmicrosoft.com. The common endpoint is especially important to
consider when developing your application because you’ll need the necessary logic to handle multiple tenants
during sign-in, sign-out, and token validation.
If you are currently developing a single tenant application but want to make it available to many organizations, you
can easily make changes to the application and its configuration in Azure AD to make it multi-tenant capable. In
addition, Azure AD uses the same signing key for all tokens in all directories, whether you are providing
authentication in a single tenant or multi-tenant application.
Each scenario listed in this document includes a sub-section that describes its provisioning requirements. For more
in-depth information about provisioning an application in Azure AD and the differences between single and multitenant applications, see Integrating Applications with Azure Active Directory for more information. Continue
reading to understand the common application scenarios in Azure AD.
Application Types and Scenarios
Each of the scenarios described in this document can be developed using various languages and platforms. They
are all backed by complete code samples which are available in our Code Samples guide, or directly from the
corresponding GitHub sample repositories. In addition, if your application needs a specific piece or segment of an
end-to-end scenario, in most cases that functionality can be added independently. For example, if you have a native
application that calls a web API, you can easily add a web application that also calls the web API. The following
diagram illustrates these scenarios and application types, and how different components can be added:
These are the five primary application scenarios 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 user needs to sign in to a single page application that is secured by Azure AD.
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.
Web Browser to Web Application
This section describes an application that authenticates a user in a web browser to a web application. In this
scenario, the web application directs the user’s browser to sign them in to Azure AD. Azure AD returns a sign-in
response through the user’s browser, which contains claims about the user in a security token. This scenario
supports sign-on using the WS-Federation, SAML 2.0, and OpenID Connect protocols.
Diagram
Description of Protocol Flow
1. When a user visits the application and needs to sign in, they are redirected via a sign-in request to the
authentication endpoint in Azure AD.
2. The user signs in on the sign-in page.
3. If authentication is successful, Azure AD creates an authentication token and returns a sign-in response to the
application’s Reply URL that was configured in the Azure Portal. For a production application, this Reply URL
should be HTTPS. The returned token includes claims about the user and Azure AD that are required by the
application to validate the token.
4. The application validates the token by using a public signing key and issuer information available at the
federation metadata document for Azure AD. After the application validates the token, Azure AD starts a new
session with the user. This session allows the user to access the application until it expires.
Code Samples
See the code samples for Web Browser to Web Application scenarios. And, check back frequently -- we add new
samples all the time. Web Browser to Web Application.
Registering
Single Tenant: If you are building an application just for your organization, it must be registered in your
company’s directory by using the Azure Portal.
Multi-Tenant: If you are building an application that can be used by users outside your organization, it must 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 your application available in their directory, you can include a sign-up process for
your customers that enables them to consent to your application. When they sign up for your application, they
will be presented with a dialog that shows the permissions the application requires, and then the option to
consent. Depending on the required permissions, an administrator in the other organization may be required to
give consent. When the user or administrator consents, the application is registered in their directory. For more
information, see Integrating Applications with Azure Active Directory.
Token Expiration
The user’s session expires when the lifetime of the token issued by Azure AD expires. Your application can shorten
this time period if desired, such as signing out users based on a period of inactivity. When the session expires, the
user will be prompted to sign in again.
Single Page Application (SPA )
This section describes authentication for a Single Page Application, that uses Azure AD and the OAuth 2.0 implicit
authorization grant to secure its web API back end. 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. To learn more about the implicit authorization grant, and help you
decide whether it's right for your application scenario, see Understanding the OAuth2 implicit grant flow in Azure
Active Directory.
In this scenario, when the user signs in, the JavaScript front end uses Active Directory Authentication Library for
JavaScript (ADAL.JS) and the implicit authorization grant to obtain an ID token (id_token) from Azure AD. The token
is cached and the client attaches it to the request as the bearer token when making calls to its Web API back end,
which is secured using the OWIN middleware.
Diagram
Description of Protocol Flow
1. The user navigates to the web application.
2. The application returns the JavaScript front end (presentation layer) to the browser.
3. The user initiates sign in, for example by clicking a sign in link. The browser sends a GET to the Azure AD
authorization endpoint to request an ID token. This request includes the application ID and reply URL in the
query parameters.
4. Azure AD validates the Reply URL against the registered Reply URL that was configured in the Azure Portal.
5. The user signs in on the sign-in page.
6. If authentication is successful, Azure AD creates an ID token and returns it as a URL fragment (#) to the
application’s Reply URL. For a production application, this Reply URL should be HTTPS. The returned token
includes claims about the user and Azure AD that are required by the application to validate the token.
7. The JavaScript client code running in the browser extracts the token from the response to use in securing calls to
the application’s web API back end.
8. The browser calls the application’s web API back end with the access token in the authorization header.
Code Samples
See the code samples for Single Page Application (SPA) scenarios. Be sure to check back frequently -- we add new
samples all the time. Single Page Application (SPA).
Registering
Single Tenant: If you are building an application just for your organization, it must be registered in your
company’s directory by using the Azure Portal.
Multi-Tenant: If you are building an application that can be used by users outside your organization, it must 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 your application available in their directory, you can include a sign-up process for
your customers that enables them to consent to your application. When they sign up for your application, they
will be presented with a dialog that shows the permissions the application requires, and then the option to
consent. Depending on the required permissions, an administrator in the other organization may be required to
give consent. When the user or administrator consents, the application is registered in their directory. For more
information, see Integrating Applications with Azure Active Directory.
After registering the application, it must be configured to use OAuth 2.0 Implicit Grant protocol. By default, this
protocol is disabled for applications. To enable the OAuth2 Implicit Grant protocol for your application, edit its
application manifest from the Azure Portal and set the “oauth2AllowImplicitFlow” value to true. For detailed
instructions, see Enabling OAuth 2.0 Implicit Grant for Single Page Applications.
Token Expiration
When you use ADAL.js to manage authentication with Azure AD, you benefit from several features that facilitate
refreshing an expired token as well as getting tokens for additional web API resources that may be called by the
application. When the user successfully authenticates with Azure AD, a session secured by a cookie is established
for the user between the browser and Azure AD. It’s important to note that the session exists between the user and
Azure AD and not between the user and the web application running on the server. When a token expires, ADAL.js
uses this session to silently obtain another token. It does this by using a hidden iFrame to send and receive the
request using the OAuth Implicit Grant protocol. ADAL.js can also use this same mechanism to silently obtain access
tokens from Azure AD for other web API resources that the application calls as long as these resources support
cross-origin resource sharing (CORS), are registered in the user’s directory, and any required consent was given by
the user during sign-in.
Native Application to Web API
This section describes a native application that calls a web API on behalf of a user. This scenario is built on the
OAuth 2.0 authorization code grant type with a public client, as described in section 4.1 of the OAuth 2.0
specification. The native application obtains an access token for the user by using the OAuth 2.0 protocol. This
access token is then sent in the request to the web API, which authorizes the user and returns the desired resource.
Diagram
Authentication flow for native application to API
Description of Protocol Flow
If you are using the AD Authentication Libraries, most of the protocol details described below are handled for you,
such as the browser pop-up, token caching, and handling of refresh tokens.
1. Using a browser pop-up, the native application makes a request to the authorization endpoint in Azure AD. This
request includes the Application ID and the redirect URI of the native application as shown in the Azure Portal,
and the application ID URI for the web API. If the user hasn’t already signed in, they are prompted to sign in
again
2. Azure AD authenticates the user. If it is a multi-tenant application and consent is required to use the application,
3.
4.
5.
6.
the user will be required to consent if they haven’t already done so. After granting consent and upon successful
authentication, Azure AD issues an authorization code response back to the client application’s redirect URI.
When Azure AD issues an authorization code response back to the redirect URI, the client application stops
browser interaction and extracts the authorization code from the response. Using this authorization code, the
client application sends a request to Azure AD’s token endpoint that includes the authorization code, details
about the client application (Application ID and redirect URI), and the desired resource (application ID URI for the
web API).
The authorization code and information about the client application and web API are validated by Azure AD.
Upon successful validation, Azure AD returns two tokens: a JWT access token and a JWT refresh token. In
addition, Azure AD returns basic information about the user, such as their display name and tenant ID.
Over HTTPS, the client 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 token,
and if validation is successful, returns the desired resource.
When the access token expires, the client application will receive an error that indicates the user needs to
authenticate again. If the application has a valid refresh token, it can be used to acquire a new access token
without prompting the user to sign in again. If the refresh token expires, the application will need to interactively
authenticate the user once again.
NOTE
The refresh token issued by Azure AD can be used to access multiple resources. For example, if you have a client application
that has permission to call two web APIs, the refresh token can be used to get an access token to the other web API as well.
Code Samples
See the code samples for Native Application to Web API scenarios. And, check back frequently -- we add new
samples all the time. Native Application to Web API.
Registering
Single Tenant: Both the native application and the web API must be registered in the same directory in Azure AD.
The web API can be configured to expose a set of permissions, which are used to limit the native application’s
access to its resources. The client application then selects the desired permissions from the “Permissions to
Other Applications” drop-down menu in the Azure Portal.
Multi-Tenant: First, the native application only ever registered in the developer or publisher’s directory. Second,
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,
which any user in the organization can consent to. Other applications require administrator-level permissions,
which a user in the organization cannot consent to. Only a directory administrator can give consent to
applications that require this level of permissions. When the user or administrator consents, only the web API is
registered in their directory. For more information, see Integrating Applications with Azure Active Directory.
Token Expiration
When the native application uses its authorization code to get a JWT access token, it also receives a JWT refresh
token. When the access token expires, the refresh token can be used to re-authenticate the user without requiring
them to sign in again. This refresh token is then used to authenticate the user, which results in a new access token
and refresh token.
Web Application to Web API
This section describes a web application that needs to get resources from a web API. In this scenario, there are two
identity types that the web application can use to authenticate and call the web API: an application identity, or a
delegated user identity.
Application identity: This scenario uses OAuth 2.0 client credentials grant to authenticate as the application and
access the web API. 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 via the application protocol, and 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.
Delegated user identity: This scenario can be accomplished in two ways: OpenID Connect, and OAuth 2.0
authorization code grant with a confidential client. 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.
Diagram
Description of Protocol Flow
Both the application identity and delegated user identity types are discussed in the flow below. The key difference
between them is that the delegated user identity must first acquire an authorization code before the user can signin and gain access to the web API.
A p p l i c a t i o n I d e n t i t y w i t h O A u t h 2 .0 C l i e n t C r e d e n t i a l s G r a n t
1. A user is signed in to Azure AD in the web application (see the Web Browser to Web Application above).
2. The web application needs to acquire an access token so that it can authenticate to the web API and retrieve the
desired resource. It makes a request to Azure AD’s token endpoint, providing the credential, Application ID, and
web API’s application ID URI.
3. Azure AD authenticates the application and returns a JWT access token that is used to call the web API.
4. Over HTTPS, 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 token,
and if validation is successful, returns the desired resource.
D e l e g a t e d U se r I d e n t i t y w i t h O p e n I D C o n n e c t
1. A user is signed in to a web application using Azure AD (see the Web Browser to Web Application section
above). 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 application will display the permissions it requires, and if any
of these are administrator-level permissions, a normal user in the directory will not be able to consent. This
consent process only applies to multi-tenant applications, not single tenant applications, as the application will
already have the necessary permissions. When the user signed in, the web application received an ID token with
information about the user, as well as an authorization code.
2. Using the authorization code issued by Azure AD, the web application sends a request to Azure AD’s token
endpoint that includes the authorization code, details about the client application (Application ID and redirect
URI), and the desired resource (application ID URI for the web API).
3. The authorization code and information about the web application and web API are validated by Azure AD. Upon
successful validation, Azure AD returns two tokens: a JWT access token and a JWT refresh token.
4. Over HTTPS, 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 token,
and if validation is successful, returns the desired resource.
D e l e g a t e d U se r I d e n t i t y w i t h O A u t h 2 .0 A u t h o r i z a t i o n C o d e G r a n t
1. A user is already signed in to a web application, whose authentication mechanism is independent of Azure AD.
2. The web application requires an authorization code to acquire an access token, so it issues a request through the
browser to Azure AD’s authorization endpoint, providing the Application ID and redirect URI for the web
application after successful authentication. The user signs in to Azure AD.
3. 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 application will display the permissions it requires, and if any of these
are administrator-level permissions, a normal user in the directory will not be able to consent. This consent
process only applies to multi-tenant applications, not single tenant applications, as the application will already
have the necessary permissions.
4. After the user has consented, the web application receives the authorization code that it needs to acquire an
access token.
5. Using the authorization code issued by Azure AD, the web application sends a request to Azure AD’s token
endpoint that includes the authorization code, details about the client application (Application ID and redirect
URI), and the desired resource (application ID URI for the web API).
6. The authorization code and information about the web application and web API are validated by Azure AD. Upon
successful validation, Azure AD returns two tokens: a JWT access token and a JWT refresh token.
7. Over HTTPS, 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 token,
and if validation is successful, returns the desired resource.
Code Samples
See the code samples for Web Application to Web API scenarios. And, check back frequently -- we add new samples
all the time. Web Application to Web API.
Registering
Single Tenant: For both the application identity and delegated user identity cases, the web application and the
web API must be registered in the same directory in Azure AD. The web API can be configured to expose a set of
permissions, which are used to limit the web application’s access to its resources. If a delegated user identity
type is being used, the web application needs to select the desired permissions from the “Permissions to Other
Applications” drop-down menu in the Azure Portal. This step is not required if the application identity type is
being used.
Multi-Tenant: First, the web 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 userlevel permissions, which any user in the organization can consent to. Other applications require administratorlevel permissions, which a user in the organization cannot consent to. Only a directory administrator can give
consent to applications that require this level of permissions. When the user or administrator consents, the web
application and the web API are both registered in their directory.
Token Expiration
When the web application uses its authorization code to get a JWT access token, it also receives a JWT refresh
token. When the access token expires, the refresh token can be used to re-authenticate the user without requiring
them to sign in again. This refresh token is then used to authenticate the user, which results in a new access token
and refresh token.
Daemon or Server Application to Web API
This section describes a daemon or server application that needs to get resources from a web API. There are two
sub-scenarios that apply to this section: A daemon that needs to call a web API, built on OAuth 2.0 client credentials
grant type; and a server application (such as a web API) that needs to call a web API, built on OAuth 2.0 On-BehalfOf draft specification.
For the scenario when a daemon application needs to call a web API, it’s important to understand a few things. First,
user interaction is not possible with a daemon application, which requires the application to have its own identity.
An example of a daemon application is a batch job, or an operating system service running in the background. This
type of application requests an access token by using its application identity and presenting its Application 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.
For the scenario when a server application needs to call a web API, it’s helpful to use an example. Imagine that a
user has authenticated on a native application, and this native application needs to call a web API. Azure AD issues a
JWT access token to call the web API. If the web API needs to call another downstream web API, it can use the onbehalf-of flow to delegate the user’s identity and authenticate to the second-tier web API.
Diagram
Description of Protocol Flow
A p p l i c a t i o n I d e n t i t y w i t h O A u t h 2 .0 C l i e n t C r e d e n t i a l s G r a n t
1. First, the server application needs to authenticate with Azure AD as itself, without any human interaction such as
an interactive sign-on dialog. It makes a request to Azure AD’s token endpoint, providing the credential,
Application ID, and application ID URI.
2. Azure AD authenticates the application and returns a JWT access token that is used to call the web API.
3. Over HTTPS, 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 token,
and if validation is successful, returns the desired resource.
D e l e g a t e d U se r I d e n t i t y w i t h O A u t h 2 .0 O n - B e h a l f- O f D r a ft Sp e c i fi c a t i o n
The flow discussed below assumes that a user has been authenticated on another application (such as a native
application), and their user identity has been used to acquire an access token to the first-tier web API.
1. The native application sends the access token to the first-tier web API.
2. The first-tier web API sends a request to Azure AD’s token endpoint, providing its Application ID and credentials,
as well as the user’s 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.
3. 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.
4. 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.
Code Samples
See the code samples for Daemon or Server Application to Web API scenarios. And, check back frequently -- we add
new samples all the time. Server or Daemon Application to Web API
Registering
Single Tenant: For both the application identity and delegated user identity cases, the daemon or server
application must be registered in the same directory in Azure AD. The web API can be configured to expose a set
of permissions, which are used to limit the daemon or server’s access to its resources. If a delegated user identity
type is being used, the server application needs to select the desired permissions from the “Permissions to Other
Applications” drop-down menu in the Azure Portal. This step is not required if the application identity type is
being used.
Multi-Tenant: First, the daemon or server 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, which any user in the organization can consent to. Other applications require
administrator-level permissions, which a user in the organization cannot consent to. Only a directory
administrator can give consent to applications that require this level of permissions. When the user or
administrator consents, both of the web APIs are registered in their directory.
Token Expiration
When the first application uses its authorization code to get a JWT access token, it also receives a JWT refresh token.
When the access token expires, the refresh token can be used to re-authenticate the user without prompting for
credentials. This refresh token is then used to authenticate the user, which results in a new access token and refresh
token.
See Also
Azure Active Directory Developer's Guide
Azure Active Directory Code Samples
Important Information About Signing Key Rollover in Azure AD
OAuth 2.0 in Azure AD
Authentication Scenarios for Azure AD
4/27/2017 • 31 min to read • Edit Online
Azure Active Directory (Azure AD) simplifies authentication for developers by providing identity as a service, with
support for industry-standard protocols such as OAuth 2.0 and OpenID Connect, as well as open source libraries for
different platforms to help you start coding quickly. This document will help you understand the various scenarios
Azure AD supports and will show you how to get started. It’s divided into the following sections:
Basics of Authentication in Azure AD
Claims in Azure AD Security Tokens
Basics of Registering an Application in Azure AD
Application Types and Scenarios
Web Browser to Web Application
Single Page Application (SPA)
Native Application to Web API
Web Application to Web API
Daemon or Server Application to Web API
Basics of Authentication in Azure AD
If you are unfamiliar with basic concepts of authentication in Azure AD, read this section. Otherwise, you may want
to skip down to Application Types and Scenarios.
Let’s consider the most basic scenario where identity is required: a user in a web browser needs to authenticate to a
web application. This scenario is described in greater detail in the Web Browser to Web Application section, but it’s
a useful starting point to illustrate the capabilities of Azure AD and conceptualize how the scenario works. Consider
the following diagram for this scenario:
With the diagram above in mind, here’s what you need to know about its various components:
Azure AD is the identity provider, responsible for verifying the identity of users and applications that exist in an
organization’s directory, and ultimately issuing security tokens upon successful authentication of those users
and applications.
An application that wants to outsource authentication to Azure AD must be registered in Azure AD, which
registers and uniquely identifies the app in the directory.
Developers can use the open source Azure AD authentication libraries to make authentication easy by handling
the protocol details for you. See Azure Active Directory Authentication Libraries for more information.
• Once a user has been authenticated, the application must validate the user’s security token to ensure that
authentication was successful for the intended parties. Developers can use the provided authentication libraries to
handle validation of any token from Azure AD, including JSON Web Tokens (JWT) or SAML 2.0. If you want to
perform validation manually, see the JWT Token Handler documentation.
IMPORTANT
Azure AD uses public key cryptography to sign tokens and verify that they are valid. See Important Information About
Signing Key Rollover in Azure AD for more information on the necessary logic you must have in your application to ensure it’s
always updated with the latest keys.
• The flow of requests and responses for the authentication process is determined by the authentication protocol
that was used, such as OAuth 2.0, OpenID Connect, WS-Federation, or SAML 2.0. These protocols are discussed in
more detail in the Azure Active Directory Authentication Protocols topic and in the sections below.
NOTE
Azure AD supports the OAuth 2.0 and OpenID Connect standards that make extensive use of bearer tokens, including bearer
tokens represented as JWTs. A bearer token is a lightweight security token that grants the “bearer” access to a protected
resource. In this sense, the “bearer” is any party that can present the token. Though a party must first authenticate with Azure
AD to receive the bearer token, if the required steps are not taken to secure the token in transmission and storage, it can be
intercepted and used by an unintended party. While some security tokens have a built-in mechanism for preventing
unauthorized parties from using them, bearer tokens do not have this mechanism and must be transported in a secure
channel such as transport layer security (HTTPS). If a bearer token is transmitted in the clear, a man-in the middle attack can
be used by a malicious party to acquire the token and use it for an unauthorized access to a protected resource. The same
security principles apply when storing or caching bearer tokens for later use. Always ensure that your application transmits
and stores bearer tokens in a secure manner. For more security considerations on bearer tokens, see RFC 6750 Section 5.
Now that you have an overview of the basics, read the sections below to understand how provisioning works in
Azure AD and the common scenarios Azure AD supports.
Claims in Azure AD Security Tokens
Security tokens issued by Azure AD contain claims, or assertions of information about the subject that has been
authenticated. These claims can be used by the application for various tasks. For example, they can be used to
validate the token, identify the subject's directory tenant, display user information, determine the subject's
authorization, and so on. The claims present in any given security token are dependent upon the type of token, the
type of credential used to authenticate the user, and the application configuration. A brief description of each type
of claim emitted by Azure AD is provided in the table below. For more information, refer to Supported Token and
Claim Types.
CLAIM
DESCRIPTION
Application ID
Identifies the application that is using the token.
Audience
Identifies the recipient resource the token is intended for.
Application Authentication Context Class Reference
Indicates how the client was authenticated (public client vs.
confidential client).
Authentication Instant
Records the date and time when the authentication occurred.
CLAIM
DESCRIPTION
Authentication Method
Indicates how the subject of the token was authenticated
(password, certificate, etc.).
First Name
Provides the given name of the user as set in Azure AD.
Groups
Contains object Ids of Azure AD groups the user is a member
of.
Identity Provider
Records the identity provider that authenticated the subject of
the token.
Issued At
Records the time at which the token was issued, often used for
token freshness.
Issuer
Identifies the STS that emitted the token as well as the Azure
AD tenant.
Last Name
Provides the surname of the user as set in Azure AD.
Name
Provides a human readable value that identifies the subject of
the token.
Object Id
Contains an immutable, unique identifier of the subject in
Azure AD.
Roles
Contains friendly names of Azure AD Application Roles that
the user has been granted.
Scope
Indicates the permissions granted to the client application.
Subject
Indicates the principal about which the token asserts
information.
Tenant Id
Contains an immutable, unique identifier of the directory
tenant that issued the token.
Token Lifetime
Defines the time interval within which a token is valid.
User Principal Name
Contains the user principal name of the subject.
Version
Contains the version number of the token.
Basics of Registering an Application in Azure AD
Any application that outsources authentication to Azure AD must be registered in a directory. This step involves
telling Azure AD about your application, including the URL where it’s located, the URL to send replies after
authentication, the URI to identify your application, and more. This information is required for a few key reasons:
Azure AD needs coordinates to communicate with the application when handling sign-on or exchanging
tokens. These include the following:
Application ID URI: The identifier for an application. This value is sent to Azure AD during authentication
to indicate which application the caller wants a token for. Additionally, this value is included in the token
so that the application knows it was the intended target.
Reply URL and Redirect URI: In the case of a web API or web application, the Reply URL is the location to
which Azure AD will send the authentication response, including a token if authentication was successful.
In the case of a native application, the Redirect URI is a unique identifier to which Azure AD will redirect
the user-agent in an OAuth 2.0 request.
Application ID: The ID for an application, which is generated by Azure AD when the application is
registered. When requesting an authorization code or token, the Application ID and key are sent to Azure
AD during authentication.
Key: The key that is sent along with a Application ID when authenticating to Azure AD to call a web API.
Azure AD needs to ensure the application has the required permissions to access your directory data, other
applications in your organization, and so on
Provisioning becomes clearer when you understand that there are two categories of applications that can be
developed and integrated with Azure AD:
Single tenant application: A single tenant application is intended for use in one organization. These are typically
line-of-business (LoB) applications written by an enterprise developer. A single tenant application only needs to
be accessed by users in one directory, and as a result, it only needs to be provisioned in one directory. These
applications are typically registered by a developer in the organization.
Multi-tenant application: A multi-tenant application is intended for use in many organizations, not just one
organization. These are typically software-as-a-service (SaaS) applications written by an independent software
vendor (ISV). Multi-tenant applications need to be provisioned in each directory where they will be used, which
requires user or administrator consent to register them. This consent process starts when an application has
been registered in the directory and is given access to the Graph API or perhaps another web API. When a user
or administrator from a different organization signs up to use the application, they are presented with a dialog
that displays the permissions the application requires. The user or administrator can then consent to the
application, which gives the application access to the stated data, and finally registers the application in their
directory. For more information, see Overview of the Consent Framework.
Some additional considerations arise when developing a multi-tenant application instead of a single tenant
application. For example, if you are making your application available to users in multiple directories, you need a
mechanism to determine which tenant they’re in. A single tenant application only needs to look in its own directory
for a user, while a multi-tenant application needs to identify a specific user from all the directories in Azure AD. To
accomplish this task, Azure AD provides a common authentication endpoint where any multi-tenant application can
direct sign-in requests, instead of a tenant-specific endpoint. This endpoint is
https://login.microsoftonline.com/common for all directories in Azure AD, whereas a tenant-specific endpoint might
be https://login.microsoftonline.com/contoso.onmicrosoft.com. The common endpoint is especially important to
consider when developing your application because you’ll need the necessary logic to handle multiple tenants
during sign-in, sign-out, and token validation.
If you are currently developing a single tenant application but want to make it available to many organizations, you
can easily make changes to the application and its configuration in Azure AD to make it multi-tenant capable. In
addition, Azure AD uses the same signing key for all tokens in all directories, whether you are providing
authentication in a single tenant or multi-tenant application.
Each scenario listed in this document includes a sub-section that describes its provisioning requirements. For more
in-depth information about provisioning an application in Azure AD and the differences between single and multitenant applications, see Integrating Applications with Azure Active Directory for more information. Continue
reading to understand the common application scenarios in Azure AD.
Application Types and Scenarios
Each of the scenarios described in this document can be developed using various languages and platforms. They
are all backed by complete code samples which are available in our Code Samples guide, or directly from the
corresponding GitHub sample repositories. In addition, if your application needs a specific piece or segment of an
end-to-end scenario, in most cases that functionality can be added independently. For example, if you have a native
application that calls a web API, you can easily add a web application that also calls the web API. The following
diagram illustrates these scenarios and application types, and how different components can be added:
These are the five primary application scenarios 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 user needs to sign in to a single page application that is secured by Azure AD.
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.
Web Browser to Web Application
This section describes an application that authenticates a user in a web browser to a web application. In this
scenario, the web application directs the user’s browser to sign them in to Azure AD. Azure AD returns a sign-in
response through the user’s browser, which contains claims about the user in a security token. This scenario
supports sign-on using the WS-Federation, SAML 2.0, and OpenID Connect protocols.
Diagram
Description of Protocol Flow
1. When a user visits the application and needs to sign in, they are redirected via a sign-in request to the
authentication endpoint in Azure AD.
2. The user signs in on the sign-in page.
3. If authentication is successful, Azure AD creates an authentication token and returns a sign-in response to the
application’s Reply URL that was configured in the Azure Portal. For a production application, this Reply URL
should be HTTPS. The returned token includes claims about the user and Azure AD that are required by the
application to validate the token.
4. The application validates the token by using a public signing key and issuer information available at the
federation metadata document for Azure AD. After the application validates the token, Azure AD starts a new
session with the user. This session allows the user to access the application until it expires.
Code Samples
See the code samples for Web Browser to Web Application scenarios. And, check back frequently -- we add new
samples all the time. Web Browser to Web Application.
Registering
Single Tenant: If you are building an application just for your organization, it must be registered in your
company’s directory by using the Azure Portal.
Multi-Tenant: If you are building an application that can be used by users outside your organization, it must 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 your application available in their directory, you can include a sign-up process for
your customers that enables them to consent to your application. When they sign up for your application, they
will be presented with a dialog that shows the permissions the application requires, and then the option to
consent. Depending on the required permissions, an administrator in the other organization may be required to
give consent. When the user or administrator consents, the application is registered in their directory. For more
information, see Integrating Applications with Azure Active Directory.
Token Expiration
The user’s session expires when the lifetime of the token issued by Azure AD expires. Your application can shorten
this time period if desired, such as signing out users based on a period of inactivity. When the session expires, the
user will be prompted to sign in again.
Single Page Application (SPA )
This section describes authentication for a Single Page Application, that uses Azure AD and the OAuth 2.0 implicit
authorization grant to secure its web API back end. 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. To learn more about the implicit authorization grant, and help you
decide whether it's right for your application scenario, see Understanding the OAuth2 implicit grant flow in Azure
Active Directory.
In this scenario, when the user signs in, the JavaScript front end uses Active Directory Authentication Library for
JavaScript (ADAL.JS) and the implicit authorization grant to obtain an ID token (id_token) from Azure AD. The token
is cached and the client attaches it to the request as the bearer token when making calls to its Web API back end,
which is secured using the OWIN middleware.
Diagram
Description of Protocol Flow
1. The user navigates to the web application.
2. The application returns the JavaScript front end (presentation layer) to the browser.
3. The user initiates sign in, for example by clicking a sign in link. The browser sends a GET to the Azure AD
authorization endpoint to request an ID token. This request includes the application ID and reply URL in the
query parameters.
4. Azure AD validates the Reply URL against the registered Reply URL that was configured in the Azure Portal.
5. The user signs in on the sign-in page.
6. If authentication is successful, Azure AD creates an ID token and returns it as a URL fragment (#) to the
application’s Reply URL. For a production application, this Reply URL should be HTTPS. The returned token
includes claims about the user and Azure AD that are required by the application to validate the token.
7. The JavaScript client code running in the browser extracts the token from the response to use in securing calls to
the application’s web API back end.
8. The browser calls the application’s web API back end with the access token in the authorization header.
Code Samples
See the code samples for Single Page Application (SPA) scenarios. Be sure to check back frequently -- we add new
samples all the time. Single Page Application (SPA).
Registering
Single Tenant: If you are building an application just for your organization, it must be registered in your
company’s directory by using the Azure Portal.
Multi-Tenant: If you are building an application that can be used by users outside your organization, it must 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 your application available in their directory, you can include a sign-up process for
your customers that enables them to consent to your application. When they sign up for your application, they
will be presented with a dialog that shows the permissions the application requires, and then the option to
consent. Depending on the required permissions, an administrator in the other organization may be required to
give consent. When the user or administrator consents, the application is registered in their directory. For more
information, see Integrating Applications with Azure Active Directory.
After registering the application, it must be configured to use OAuth 2.0 Implicit Grant protocol. By default, this
protocol is disabled for applications. To enable the OAuth2 Implicit Grant protocol for your application, edit its
application manifest from the Azure Portal and set the “oauth2AllowImplicitFlow” value to true. For detailed
instructions, see Enabling OAuth 2.0 Implicit Grant for Single Page Applications.
Token Expiration
When you use ADAL.js to manage authentication with Azure AD, you benefit from several features that facilitate
refreshing an expired token as well as getting tokens for additional web API resources that may be called by the
application. When the user successfully authenticates with Azure AD, a session secured by a cookie is established
for the user between the browser and Azure AD. It’s important to note that the session exists between the user and
Azure AD and not between the user and the web application running on the server. When a token expires, ADAL.js
uses this session to silently obtain another token. It does this by using a hidden iFrame to send and receive the
request using the OAuth Implicit Grant protocol. ADAL.js can also use this same mechanism to silently obtain access
tokens from Azure AD for other web API resources that the application calls as long as these resources support
cross-origin resource sharing (CORS), are registered in the user’s directory, and any required consent was given by
the user during sign-in.
Native Application to Web API
This section describes a native application that calls a web API on behalf of a user. This scenario is built on the
OAuth 2.0 authorization code grant type with a public client, as described in section 4.1 of the OAuth 2.0
specification. The native application obtains an access token for the user by using the OAuth 2.0 protocol. This
access token is then sent in the request to the web API, which authorizes the user and returns the desired resource.
Diagram
Authentication flow for native application to API
Description of Protocol Flow
If you are using the AD Authentication Libraries, most of the protocol details described below are handled for you,
such as the browser pop-up, token caching, and handling of refresh tokens.
1. Using a browser pop-up, the native application makes a request to the authorization endpoint in Azure AD. This
request includes the Application ID and the redirect URI of the native application as shown in the Azure Portal,
and the application ID URI for the web API. If the user hasn’t already signed in, they are prompted to sign in
again
2. Azure AD authenticates the user. If it is a multi-tenant application and consent is required to use the application,
3.
4.
5.
6.
the user will be required to consent if they haven’t already done so. After granting consent and upon successful
authentication, Azure AD issues an authorization code response back to the client application’s redirect URI.
When Azure AD issues an authorization code response back to the redirect URI, the client application stops
browser interaction and extracts the authorization code from the response. Using this authorization code, the
client application sends a request to Azure AD’s token endpoint that includes the authorization code, details
about the client application (Application ID and redirect URI), and the desired resource (application ID URI for the
web API).
The authorization code and information about the client application and web API are validated by Azure AD.
Upon successful validation, Azure AD returns two tokens: a JWT access token and a JWT refresh token. In
addition, Azure AD returns basic information about the user, such as their display name and tenant ID.
Over HTTPS, the client 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 token,
and if validation is successful, returns the desired resource.
When the access token expires, the client application will receive an error that indicates the user needs to
authenticate again. If the application has a valid refresh token, it can be used to acquire a new access token
without prompting the user to sign in again. If the refresh token expires, the application will need to interactively
authenticate the user once again.
NOTE
The refresh token issued by Azure AD can be used to access multiple resources. For example, if you have a client application
that has permission to call two web APIs, the refresh token can be used to get an access token to the other web API as well.
Code Samples
See the code samples for Native Application to Web API scenarios. And, check back frequently -- we add new
samples all the time. Native Application to Web API.
Registering
Single Tenant: Both the native application and the web API must be registered in the same directory in Azure AD.
The web API can be configured to expose a set of permissions, which are used to limit the native application’s
access to its resources. The client application then selects the desired permissions from the “Permissions to
Other Applications” drop-down menu in the Azure Portal.
Multi-Tenant: First, the native application only ever registered in the developer or publisher’s directory. Second,
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,
which any user in the organization can consent to. Other applications require administrator-level permissions,
which a user in the organization cannot consent to. Only a directory administrator can give consent to
applications that require this level of permissions. When the user or administrator consents, only the web API is
registered in their directory. For more information, see Integrating Applications with Azure Active Directory.
Token Expiration
When the native application uses its authorization code to get a JWT access token, it also receives a JWT refresh
token. When the access token expires, the refresh token can be used to re-authenticate the user without requiring
them to sign in again. This refresh token is then used to authenticate the user, which results in a new access token
and refresh token.
Web Application to Web API
This section describes a web application that needs to get resources from a web API. In this scenario, there are two
identity types that the web application can use to authenticate and call the web API: an application identity, or a
delegated user identity.
Application identity: This scenario uses OAuth 2.0 client credentials grant to authenticate as the application and
access the web API. 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 via the application protocol, and 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.
Delegated user identity: This scenario can be accomplished in two ways: OpenID Connect, and OAuth 2.0
authorization code grant with a confidential client. 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.
Diagram
Description of Protocol Flow
Both the application identity and delegated user identity types are discussed in the flow below. The key difference
between them is that the delegated user identity must first acquire an authorization code before the user can signin and gain access to the web API.
A p p l i c a t i o n I d e n t i t y w i t h O A u t h 2 .0 C l i e n t C r e d e n t i a l s G r a n t
1. A user is signed in to Azure AD in the web application (see the Web Browser to Web Application above).
2. The web application needs to acquire an access token so that it can authenticate to the web API and retrieve the
desired resource. It makes a request to Azure AD’s token endpoint, providing the credential, Application ID, and
web API’s application ID URI.
3. Azure AD authenticates the application and returns a JWT access token that is used to call the web API.
4. Over HTTPS, 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 token,
and if validation is successful, returns the desired resource.
D e l e g a t e d U se r I d e n t i t y w i t h O p e n I D C o n n e c t
1. A user is signed in to a web application using Azure AD (see the Web Browser to Web Application section
above). 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 application will display the permissions it requires, and if any
of these are administrator-level permissions, a normal user in the directory will not be able to consent. This
consent process only applies to multi-tenant applications, not single tenant applications, as the application will
already have the necessary permissions. When the user signed in, the web application received an ID token with
information about the user, as well as an authorization code.
2. Using the authorization code issued by Azure AD, the web application sends a request to Azure AD’s token
endpoint that includes the authorization code, details about the client application (Application ID and redirect
URI), and the desired resource (application ID URI for the web API).
3. The authorization code and information about the web application and web API are validated by Azure AD. Upon
successful validation, Azure AD returns two tokens: a JWT access token and a JWT refresh token.
4. Over HTTPS, 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 token,
and if validation is successful, returns the desired resource.
D e l e g a t e d U se r I d e n t i t y w i t h O A u t h 2 .0 A u t h o r i z a t i o n C o d e G r a n t
1. A user is already signed in to a web application, whose authentication mechanism is independent of Azure AD.
2. The web application requires an authorization code to acquire an access token, so it issues a request through the
browser to Azure AD’s authorization endpoint, providing the Application ID and redirect URI for the web
application after successful authentication. The user signs in to Azure AD.
3. 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 application will display the permissions it requires, and if any of these
are administrator-level permissions, a normal user in the directory will not be able to consent. This consent
process only applies to multi-tenant applications, not single tenant applications, as the application will already
have the necessary permissions.
4. After the user has consented, the web application receives the authorization code that it needs to acquire an
access token.
5. Using the authorization code issued by Azure AD, the web application sends a request to Azure AD’s token
endpoint that includes the authorization code, details about the client application (Application ID and redirect
URI), and the desired resource (application ID URI for the web API).
6. The authorization code and information about the web application and web API are validated by Azure AD. Upon
successful validation, Azure AD returns two tokens: a JWT access token and a JWT refresh token.
7. Over HTTPS, 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 token,
and if validation is successful, returns the desired resource.
Code Samples
See the code samples for Web Application to Web API scenarios. And, check back frequently -- we add new samples
all the time. Web Application to Web API.
Registering
Single Tenant: For both the application identity and delegated user identity cases, the web application and the
web API must be registered in the same directory in Azure AD. The web API can be configured to expose a set of
permissions, which are used to limit the web application’s access to its resources. If a delegated user identity
type is being used, the web application needs to select the desired permissions from the “Permissions to Other
Applications” drop-down menu in the Azure Portal. This step is not required if the application identity type is
being used.
Multi-Tenant: First, the web 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 userlevel permissions, which any user in the organization can consent to. Other applications require administratorlevel permissions, which a user in the organization cannot consent to. Only a directory administrator can give
consent to applications that require this level of permissions. When the user or administrator consents, the web
application and the web API are both registered in their directory.
Token Expiration
When the web application uses its authorization code to get a JWT access token, it also receives a JWT refresh
token. When the access token expires, the refresh token can be used to re-authenticate the user without requiring
them to sign in again. This refresh token is then used to authenticate the user, which results in a new access token
and refresh token.
Daemon or Server Application to Web API
This section describes a daemon or server application that needs to get resources from a web API. There are two
sub-scenarios that apply to this section: A daemon that needs to call a web API, built on OAuth 2.0 client credentials
grant type; and a server application (such as a web API) that needs to call a web API, built on OAuth 2.0 On-BehalfOf draft specification.
For the scenario when a daemon application needs to call a web API, it’s important to understand a few things. First,
user interaction is not possible with a daemon application, which requires the application to have its own identity.
An example of a daemon application is a batch job, or an operating system service running in the background. This
type of application requests an access token by using its application identity and presenting its Application 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.
For the scenario when a server application needs to call a web API, it’s helpful to use an example. Imagine that a
user has authenticated on a native application, and this native application needs to call a web API. Azure AD issues a
JWT access token to call the web API. If the web API needs to call another downstream web API, it can use the onbehalf-of flow to delegate the user’s identity and authenticate to the second-tier web API.
Diagram
Description of Protocol Flow
A p p l i c a t i o n I d e n t i t y w i t h O A u t h 2 .0 C l i e n t C r e d e n t i a l s G r a n t
1. First, the server application needs to authenticate with Azure AD as itself, without any human interaction such as
an interactive sign-on dialog. It makes a request to Azure AD’s token endpoint, providing the credential,
Application ID, and application ID URI.
2. Azure AD authenticates the application and returns a JWT access token that is used to call the web API.
3. Over HTTPS, 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 token,
and if validation is successful, returns the desired resource.
D e l e g a t e d U se r I d e n t i t y w i t h O A u t h 2 .0 O n - B e h a l f- O f D r a ft Sp e c i fi c a t i o n
The flow discussed below assumes that a user has been authenticated on another application (such as a native
application), and their user identity has been used to acquire an access token to the first-tier web API.
1. The native application sends the access token to the first-tier web API.
2. The first-tier web API sends a request to Azure AD’s token endpoint, providing its Application ID and credentials,
as well as the user’s 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.
3. 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.
4. 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.
Code Samples
See the code samples for Daemon or Server Application to Web API scenarios. And, check back frequently -- we add
new samples all the time. Server or Daemon Application to Web API
Registering
Single Tenant: For both the application identity and delegated user identity cases, the daemon or server
application must be registered in the same directory in Azure AD. The web API can be configured to expose a set
of permissions, which are used to limit the daemon or server’s access to its resources. If a delegated user identity
type is being used, the server application needs to select the desired permissions from the “Permissions to Other
Applications” drop-down menu in the Azure Portal. This step is not required if the application identity type is
being used.
Multi-Tenant: First, the daemon or server 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, which any user in the organization can consent to. Other applications require
administrator-level permissions, which a user in the organization cannot consent to. Only a directory
administrator can give consent to applications that require this level of permissions. When the user or
administrator consents, both of the web APIs are registered in their directory.
Token Expiration
When the first application uses its authorization code to get a JWT access token, it also receives a JWT refresh token.
When the access token expires, the refresh token can be used to re-authenticate the user without prompting for
credentials. This refresh token is then used to authenticate the user, which results in a new access token and refresh
token.
See Also
Azure Active Directory Developer's Guide
Azure Active Directory Code Samples
Important Information About Signing Key Rollover in Azure AD
OAuth 2.0 in Azure AD
Authentication Scenarios for Azure AD
4/27/2017 • 31 min to read • Edit Online
Azure Active Directory (Azure AD) simplifies authentication for developers by providing identity as a service, with
support for industry-standard protocols such as OAuth 2.0 and OpenID Connect, as well as open source libraries for
different platforms to help you start coding quickly. This document will help you understand the various scenarios
Azure AD supports and will show you how to get started. It’s divided into the following sections:
Basics of Authentication in Azure AD
Claims in Azure AD Security Tokens
Basics of Registering an Application in Azure AD
Application Types and Scenarios
Web Browser to Web Application
Single Page Application (SPA)
Native Application to Web API
Web Application to Web API
Daemon or Server Application to Web API
Basics of Authentication in Azure AD
If you are unfamiliar with basic concepts of authentication in Azure AD, read this section. Otherwise, you may want
to skip down to Application Types and Scenarios.
Let’s consider the most basic scenario where identity is required: a user in a web browser needs to authenticate to a
web application. This scenario is described in greater detail in the Web Browser to Web Application section, but it’s
a useful starting point to illustrate the capabilities of Azure AD and conceptualize how the scenario works. Consider
the following diagram for this scenario:
With the diagram above in mind, here’s what you need to know about its various components:
Azure AD is the identity provider, responsible for verifying the identity of users and applications that exist in an
organization’s directory, and ultimately issuing security tokens upon successful authentication of those users
and applications.
An application that wants to outsource authentication to Azure AD must be registered in Azure AD, which
registers and uniquely identifies the app in the directory.
Developers can use the open source Azure AD authentication libraries to make authentication easy by handling
the protocol details for you. See Azure Active Directory Authentication Libraries for more information.
• Once a user has been authenticated, the application must validate the user’s security token to ensure that
authentication was successful for the intended parties. Developers can use the provided authentication libraries to
handle validation of any token from Azure AD, including JSON Web Tokens (JWT) or SAML 2.0. If you want to
perform validation manually, see the JWT Token Handler documentation.
IMPORTANT
Azure AD uses public key cryptography to sign tokens and verify that they are valid. See Important Information About
Signing Key Rollover in Azure AD for more information on the necessary logic you must have in your application to ensure it’s
always updated with the latest keys.
• The flow of requests and responses for the authentication process is determined by the authentication protocol
that was used, such as OAuth 2.0, OpenID Connect, WS-Federation, or SAML 2.0. These protocols are discussed in
more detail in the Azure Active Directory Authentication Protocols topic and in the sections below.
NOTE
Azure AD supports the OAuth 2.0 and OpenID Connect standards that make extensive use of bearer tokens, including bearer
tokens represented as JWTs. A bearer token is a lightweight security token that grants the “bearer” access to a protected
resource. In this sense, the “bearer” is any party that can present the token. Though a party must first authenticate with Azure
AD to receive the bearer token, if the required steps are not taken to secure the token in transmission and storage, it can be
intercepted and used by an unintended party. While some security tokens have a built-in mechanism for preventing
unauthorized parties from using them, bearer tokens do not have this mechanism and must be transported in a secure
channel such as transport layer security (HTTPS). If a bearer token is transmitted in the clear, a man-in the middle attack can
be used by a malicious party to acquire the token and use it for an unauthorized access to a protected resource. The same
security principles apply when storing or caching bearer tokens for later use. Always ensure that your application transmits
and stores bearer tokens in a secure manner. For more security considerations on bearer tokens, see RFC 6750 Section 5.
Now that you have an overview of the basics, read the sections below to understand how provisioning works in
Azure AD and the common scenarios Azure AD supports.
Claims in Azure AD Security Tokens
Security tokens issued by Azure AD contain claims, or assertions of information about the subject that has been
authenticated. These claims can be used by the application for various tasks. For example, they can be used to
validate the token, identify the subject's directory tenant, display user information, determine the subject's
authorization, and so on. The claims present in any given security token are dependent upon the type of token, the
type of credential used to authenticate the user, and the application configuration. A brief description of each type
of claim emitted by Azure AD is provided in the table below. For more information, refer to Supported Token and
Claim Types.
CLAIM
DESCRIPTION
Application ID
Identifies the application that is using the token.
Audience
Identifies the recipient resource the token is intended for.
Application Authentication Context Class Reference
Indicates how the client was authenticated (public client vs.
confidential client).
Authentication Instant
Records the date and time when the authentication occurred.
CLAIM
DESCRIPTION
Authentication Method
Indicates how the subject of the token was authenticated
(password, certificate, etc.).
First Name
Provides the given name of the user as set in Azure AD.
Groups
Contains object Ids of Azure AD groups the user is a member
of.
Identity Provider
Records the identity provider that authenticated the subject of
the token.
Issued At
Records the time at which the token was issued, often used for
token freshness.
Issuer
Identifies the STS that emitted the token as well as the Azure
AD tenant.
Last Name
Provides the surname of the user as set in Azure AD.
Name
Provides a human readable value that identifies the subject of
the token.
Object Id
Contains an immutable, unique identifier of the subject in
Azure AD.
Roles
Contains friendly names of Azure AD Application Roles that
the user has been granted.
Scope
Indicates the permissions granted to the client application.
Subject
Indicates the principal about which the token asserts
information.
Tenant Id
Contains an immutable, unique identifier of the directory
tenant that issued the token.
Token Lifetime
Defines the time interval within which a token is valid.
User Principal Name
Contains the user principal name of the subject.
Version
Contains the version number of the token.
Basics of Registering an Application in Azure AD
Any application that outsources authentication to Azure AD must be registered in a directory. This step involves
telling Azure AD about your application, including the URL where it’s located, the URL to send replies after
authentication, the URI to identify your application, and more. This information is required for a few key reasons:
Azure AD needs coordinates to communicate with the application when handling sign-on or exchanging
tokens. These include the following:
Application ID URI: The identifier for an application. This value is sent to Azure AD during authentication
to indicate which application the caller wants a token for. Additionally, this value is included in the token
so that the application knows it was the intended target.
Reply URL and Redirect URI: In the case of a web API or web application, the Reply URL is the location to
which Azure AD will send the authentication response, including a token if authentication was successful.
In the case of a native application, the Redirect URI is a unique identifier to which Azure AD will redirect
the user-agent in an OAuth 2.0 request.
Application ID: The ID for an application, which is generated by Azure AD when the application is
registered. When requesting an authorization code or token, the Application ID and key are sent to Azure
AD during authentication.
Key: The key that is sent along with a Application ID when authenticating to Azure AD to call a web API.
Azure AD needs to ensure the application has the required permissions to access your directory data, other
applications in your organization, and so on
Provisioning becomes clearer when you understand that there are two categories of applications that can be
developed and integrated with Azure AD:
Single tenant application: A single tenant application is intended for use in one organization. These are typically
line-of-business (LoB) applications written by an enterprise developer. A single tenant application only needs to
be accessed by users in one directory, and as a result, it only needs to be provisioned in one directory. These
applications are typically registered by a developer in the organization.
Multi-tenant application: A multi-tenant application is intended for use in many organizations, not just one
organization. These are typically software-as-a-service (SaaS) applications written by an independent software
vendor (ISV). Multi-tenant applications need to be provisioned in each directory where they will be used, which
requires user or administrator consent to register them. This consent process starts when an application has
been registered in the directory and is given access to the Graph API or perhaps another web API. When a user
or administrator from a different organization signs up to use the application, they are presented with a dialog
that displays the permissions the application requires. The user or administrator can then consent to the
application, which gives the application access to the stated data, and finally registers the application in their
directory. For more information, see Overview of the Consent Framework.
Some additional considerations arise when developing a multi-tenant application instead of a single tenant
application. For example, if you are making your application available to users in multiple directories, you need a
mechanism to determine which tenant they’re in. A single tenant application only needs to look in its own directory
for a user, while a multi-tenant application needs to identify a specific user from all the directories in Azure AD. To
accomplish this task, Azure AD provides a common authentication endpoint where any multi-tenant application can
direct sign-in requests, instead of a tenant-specific endpoint. This endpoint is
https://login.microsoftonline.com/common for all directories in Azure AD, whereas a tenant-specific endpoint might
be https://login.microsoftonline.com/contoso.onmicrosoft.com. The common endpoint is especially important to
consider when developing your application because you’ll need the necessary logic to handle multiple tenants
during sign-in, sign-out, and token validation.
If you are currently developing a single tenant application but want to make it available to many organizations, you
can easily make changes to the application and its configuration in Azure AD to make it multi-tenant capable. In
addition, Azure AD uses the same signing key for all tokens in all directories, whether you are providing
authentication in a single tenant or multi-tenant application.
Each scenario listed in this document includes a sub-section that describes its provisioning requirements. For more
in-depth information about provisioning an application in Azure AD and the differences between single and multitenant applications, see Integrating Applications with Azure Active Directory for more information. Continue
reading to understand the common application scenarios in Azure AD.
Application Types and Scenarios
Each of the scenarios described in this document can be developed using various languages and platforms. They
are all backed by complete code samples which are available in our Code Samples guide, or directly from the
corresponding GitHub sample repositories. In addition, if your application needs a specific piece or segment of an
end-to-end scenario, in most cases that functionality can be added independently. For example, if you have a native
application that calls a web API, you can easily add a web application that also calls the web API. The following
diagram illustrates these scenarios and application types, and how different components can be added:
These are the five primary application scenarios 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 user needs to sign in to a single page application that is secured by Azure AD.
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.
Web Browser to Web Application
This section describes an application that authenticates a user in a web browser to a web application. In this
scenario, the web application directs the user’s browser to sign them in to Azure AD. Azure AD returns a sign-in
response through the user’s browser, which contains claims about the user in a security token. This scenario
supports sign-on using the WS-Federation, SAML 2.0, and OpenID Connect protocols.
Diagram
Description of Protocol Flow
1. When a user visits the application and needs to sign in, they are redirected via a sign-in request to the
authentication endpoint in Azure AD.
2. The user signs in on the sign-in page.
3. If authentication is successful, Azure AD creates an authentication token and returns a sign-in response to the
application’s Reply URL that was configured in the Azure Portal. For a production application, this Reply URL
should be HTTPS. The returned token includes claims about the user and Azure AD that are required by the
application to validate the token.
4. The application validates the token by using a public signing key and issuer information available at the
federation metadata document for Azure AD. After the application validates the token, Azure AD starts a new
session with the user. This session allows the user to access the application until it expires.
Code Samples
See the code samples for Web Browser to Web Application scenarios. And, check back frequently -- we add new
samples all the time. Web Browser to Web Application.
Registering
Single Tenant: If you are building an application just for your organization, it must be registered in your
company’s directory by using the Azure Portal.
Multi-Tenant: If you are building an application that can be used by users outside your organization, it must 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 your application available in their directory, you can include a sign-up process for
your customers that enables them to consent to your application. When they sign up for your application, they
will be presented with a dialog that shows the permissions the application requires, and then the option to
consent. Depending on the required permissions, an administrator in the other organization may be required to
give consent. When the user or administrator consents, the application is registered in their directory. For more
information, see Integrating Applications with Azure Active Directory.
Token Expiration
The user’s session expires when the lifetime of the token issued by Azure AD expires. Your application can shorten
this time period if desired, such as signing out users based on a period of inactivity. When the session expires, the
user will be prompted to sign in again.
Single Page Application (SPA )
This section describes authentication for a Single Page Application, that uses Azure AD and the OAuth 2.0 implicit
authorization grant to secure its web API back end. 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. To learn more about the implicit authorization grant, and help you
decide whether it's right for your application scenario, see Understanding the OAuth2 implicit grant flow in Azure
Active Directory.
In this scenario, when the user signs in, the JavaScript front end uses Active Directory Authentication Library for
JavaScript (ADAL.JS) and the implicit authorization grant to obtain an ID token (id_token) from Azure AD. The token
is cached and the client attaches it to the request as the bearer token when making calls to its Web API back end,
which is secured using the OWIN middleware.
Diagram
Description of Protocol Flow
1. The user navigates to the web application.
2. The application returns the JavaScript front end (presentation layer) to the browser.
3. The user initiates sign in, for example by clicking a sign in link. The browser sends a GET to the Azure AD
authorization endpoint to request an ID token. This request includes the application ID and reply URL in the
query parameters.
4. Azure AD validates the Reply URL against the registered Reply URL that was configured in the Azure Portal.
5. The user signs in on the sign-in page.
6. If authentication is successful, Azure AD creates an ID token and returns it as a URL fragment (#) to the
application’s Reply URL. For a production application, this Reply URL should be HTTPS. The returned token
includes claims about the user and Azure AD that are required by the application to validate the token.
7. The JavaScript client code running in the browser extracts the token from the response to use in securing calls to
the application’s web API back end.
8. The browser calls the application’s web API back end with the access token in the authorization header.
Code Samples
See the code samples for Single Page Application (SPA) scenarios. Be sure to check back frequently -- we add new
samples all the time. Single Page Application (SPA).
Registering
Single Tenant: If you are building an application just for your organization, it must be registered in your
company’s directory by using the Azure Portal.
Multi-Tenant: If you are building an application that can be used by users outside your organization, it must 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 your application available in their directory, you can include a sign-up process for
your customers that enables them to consent to your application. When they sign up for your application, they
will be presented with a dialog that shows the permissions the application requires, and then the option to
consent. Depending on the required permissions, an administrator in the other organization may be required to
give consent. When the user or administrator consents, the application is registered in their directory. For more
information, see Integrating Applications with Azure Active Directory.
After registering the application, it must be configured to use OAuth 2.0 Implicit Grant protocol. By default, this
protocol is disabled for applications. To enable the OAuth2 Implicit Grant protocol for your application, edit its
application manifest from the Azure Portal and set the “oauth2AllowImplicitFlow” value to true. For detailed
instructions, see Enabling OAuth 2.0 Implicit Grant for Single Page Applications.
Token Expiration
When you use ADAL.js to manage authentication with Azure AD, you benefit from several features that facilitate
refreshing an expired token as well as getting tokens for additional web API resources that may be called by the
application. When the user successfully authenticates with Azure AD, a session secured by a cookie is established
for the user between the browser and Azure AD. It’s important to note that the session exists between the user and
Azure AD and not between the user and the web application running on the server. When a token expires, ADAL.js
uses this session to silently obtain another token. It does this by using a hidden iFrame to send and receive the
request using the OAuth Implicit Grant protocol. ADAL.js can also use this same mechanism to silently obtain access
tokens from Azure AD for other web API resources that the application calls as long as these resources support
cross-origin resource sharing (CORS), are registered in the user’s directory, and any required consent was given by
the user during sign-in.
Native Application to Web API
This section describes a native application that calls a web API on behalf of a user. This scenario is built on the
OAuth 2.0 authorization code grant type with a public client, as described in section 4.1 of the OAuth 2.0
specification. The native application obtains an access token for the user by using the OAuth 2.0 protocol. This
access token is then sent in the request to the web API, which authorizes the user and returns the desired resource.
Diagram
Authentication flow for native application to API
Description of Protocol Flow
If you are using the AD Authentication Libraries, most of the protocol details described below are handled for you,
such as the browser pop-up, token caching, and handling of refresh tokens.
1. Using a browser pop-up, the native application makes a request to the authorization endpoint in Azure AD. This
request includes the Application ID and the redirect URI of the native application as shown in the Azure Portal,
and the application ID URI for the web API. If the user hasn’t already signed in, they are prompted to sign in
again
2. Azure AD authenticates the user. If it is a multi-tenant application and consent is required to use the application,
3.
4.
5.
6.
the user will be required to consent if they haven’t already done so. After granting consent and upon successful
authentication, Azure AD issues an authorization code response back to the client application’s redirect URI.
When Azure AD issues an authorization code response back to the redirect URI, the client application stops
browser interaction and extracts the authorization code from the response. Using this authorization code, the
client application sends a request to Azure AD’s token endpoint that includes the authorization code, details
about the client application (Application ID and redirect URI), and the desired resource (application ID URI for the
web API).
The authorization code and information about the client application and web API are validated by Azure AD.
Upon successful validation, Azure AD returns two tokens: a JWT access token and a JWT refresh token. In
addition, Azure AD returns basic information about the user, such as their display name and tenant ID.
Over HTTPS, the client 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 token,
and if validation is successful, returns the desired resource.
When the access token expires, the client application will receive an error that indicates the user needs to
authenticate again. If the application has a valid refresh token, it can be used to acquire a new access token
without prompting the user to sign in again. If the refresh token expires, the application will need to interactively
authenticate the user once again.
NOTE
The refresh token issued by Azure AD can be used to access multiple resources. For example, if you have a client application
that has permission to call two web APIs, the refresh token can be used to get an access token to the other web API as well.
Code Samples
See the code samples for Native Application to Web API scenarios. And, check back frequently -- we add new
samples all the time. Native Application to Web API.
Registering
Single Tenant: Both the native application and the web API must be registered in the same directory in Azure AD.
The web API can be configured to expose a set of permissions, which are used to limit the native application’s
access to its resources. The client application then selects the desired permissions from the “Permissions to
Other Applications” drop-down menu in the Azure Portal.
Multi-Tenant: First, the native application only ever registered in the developer or publisher’s directory. Second,
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,
which any user in the organization can consent to. Other applications require administrator-level permissions,
which a user in the organization cannot consent to. Only a directory administrator can give consent to
applications that require this level of permissions. When the user or administrator consents, only the web API is
registered in their directory. For more information, see Integrating Applications with Azure Active Directory.
Token Expiration
When the native application uses its authorization code to get a JWT access token, it also receives a JWT refresh
token. When the access token expires, the refresh token can be used to re-authenticate the user without requiring
them to sign in again. This refresh token is then used to authenticate the user, which results in a new access token
and refresh token.
Web Application to Web API
This section describes a web application that needs to get resources from a web API. In this scenario, there are two
identity types that the web application can use to authenticate and call the web API: an application identity, or a
delegated user identity.
Application identity: This scenario uses OAuth 2.0 client credentials grant to authenticate as the application and
access the web API. 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 via the application protocol, and 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.
Delegated user identity: This scenario can be accomplished in two ways: OpenID Connect, and OAuth 2.0
authorization code grant with a confidential client. 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.
Diagram
Description of Protocol Flow
Both the application identity and delegated user identity types are discussed in the flow below. The key difference
between them is that the delegated user identity must first acquire an authorization code before the user can signin and gain access to the web API.
A p p l i c a t i o n I d e n t i t y w i t h O A u t h 2 .0 C l i e n t C r e d e n t i a l s G r a n t
1. A user is signed in to Azure AD in the web application (see the Web Browser to Web Application above).
2. The web application needs to acquire an access token so that it can authenticate to the web API and retrieve the
desired resource. It makes a request to Azure AD’s token endpoint, providing the credential, Application ID, and
web API’s application ID URI.
3. Azure AD authenticates the application and returns a JWT access token that is used to call the web API.
4. Over HTTPS, 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 token,
and if validation is successful, returns the desired resource.
D e l e g a t e d U se r I d e n t i t y w i t h O p e n I D C o n n e c t
1. A user is signed in to a web application using Azure AD (see the Web Browser to Web Application section
above). 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 application will display the permissions it requires, and if any
of these are administrator-level permissions, a normal user in the directory will not be able to consent. This
consent process only applies to multi-tenant applications, not single tenant applications, as the application will
already have the necessary permissions. When the user signed in, the web application received an ID token with
information about the user, as well as an authorization code.
2. Using the authorization code issued by Azure AD, the web application sends a request to Azure AD’s token
endpoint that includes the authorization code, details about the client application (Application ID and redirect
URI), and the desired resource (application ID URI for the web API).
3. The authorization code and information about the web application and web API are validated by Azure AD. Upon
successful validation, Azure AD returns two tokens: a JWT access token and a JWT refresh token.
4. Over HTTPS, 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 token,
and if validation is successful, returns the desired resource.
D e l e g a t e d U se r I d e n t i t y w i t h O A u t h 2 .0 A u t h o r i z a t i o n C o d e G r a n t
1. A user is already signed in to a web application, whose authentication mechanism is independent of Azure AD.
2. The web application requires an authorization code to acquire an access token, so it issues a request through the
browser to Azure AD’s authorization endpoint, providing the Application ID and redirect URI for the web
application after successful authentication. The user signs in to Azure AD.
3. 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 application will display the permissions it requires, and if any of these
are administrator-level permissions, a normal user in the directory will not be able to consent. This consent
process only applies to multi-tenant applications, not single tenant applications, as the application will already
have the necessary permissions.
4. After the user has consented, the web application receives the authorization code that it needs to acquire an
access token.
5. Using the authorization code issued by Azure AD, the web application sends a request to Azure AD’s token
endpoint that includes the authorization code, details about the client application (Application ID and redirect
URI), and the desired resource (application ID URI for the web API).
6. The authorization code and information about the web application and web API are validated by Azure AD. Upon
successful validation, Azure AD returns two tokens: a JWT access token and a JWT refresh token.
7. Over HTTPS, 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 token,
and if validation is successful, returns the desired resource.
Code Samples
See the code samples for Web Application to Web API scenarios. And, check back frequently -- we add new samples
all the time. Web Application to Web API.
Registering
Single Tenant: For both the application identity and delegated user identity cases, the web application and the
web API must be registered in the same directory in Azure AD. The web API can be configured to expose a set of
permissions, which are used to limit the web application’s access to its resources. If a delegated user identity
type is being used, the web application needs to select the desired permissions from the “Permissions to Other
Applications” drop-down menu in the Azure Portal. This step is not required if the application identity type is
being used.
Multi-Tenant: First, the web 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 userlevel permissions, which any user in the organization can consent to. Other applications require administratorlevel permissions, which a user in the organization cannot consent to. Only a directory administrator can give
consent to applications that require this level of permissions. When the user or administrator consents, the web
application and the web API are both registered in their directory.
Token Expiration
When the web application uses its authorization code to get a JWT access token, it also receives a JWT refresh
token. When the access token expires, the refresh token can be used to re-authenticate the user without requiring
them to sign in again. This refresh token is then used to authenticate the user, which results in a new access token
and refresh token.
Daemon or Server Application to Web API
This section describes a daemon or server application that needs to get resources from a web API. There are two
sub-scenarios that apply to this section: A daemon that needs to call a web API, built on OAuth 2.0 client credentials
grant type; and a server application (such as a web API) that needs to call a web API, built on OAuth 2.0 On-BehalfOf draft specification.
For the scenario when a daemon application needs to call a web API, it’s important to understand a few things. First,
user interaction is not possible with a daemon application, which requires the application to have its own identity.
An example of a daemon application is a batch job, or an operating system service running in the background. This
type of application requests an access token by using its application identity and presenting its Application 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.
For the scenario when a server application needs to call a web API, it’s helpful to use an example. Imagine that a
user has authenticated on a native application, and this native application needs to call a web API. Azure AD issues a
JWT access token to call the web API. If the web API needs to call another downstream web API, it can use the onbehalf-of flow to delegate the user’s identity and authenticate to the second-tier web API.
Diagram
Description of Protocol Flow
A p p l i c a t i o n I d e n t i t y w i t h O A u t h 2 .0 C l i e n t C r e d e n t i a l s G r a n t
1. First, the server application needs to authenticate with Azure AD as itself, without any human interaction such as
an interactive sign-on dialog. It makes a request to Azure AD’s token endpoint, providing the credential,
Application ID, and application ID URI.
2. Azure AD authenticates the application and returns a JWT access token that is used to call the web API.
3. Over HTTPS, 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 token,
and if validation is successful, returns the desired resource.
D e l e g a t e d U se r I d e n t i t y w i t h O A u t h 2 .0 O n - B e h a l f- O f D r a ft Sp e c i fi c a t i o n
The flow discussed below assumes that a user has been authenticated on another application (such as a native
application), and their user identity has been used to acquire an access token to the first-tier web API.
1. The native application sends the access token to the first-tier web API.
2. The first-tier web API sends a request to Azure AD’s token endpoint, providing its Application ID and credentials,
as well as the user’s 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.
3. 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.
4. 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.
Code Samples
See the code samples for Daemon or Server Application to Web API scenarios. And, check back frequently -- we add
new samples all the time. Server or Daemon Application to Web API
Registering
Single Tenant: For both the application identity and delegated user identity cases, the daemon or server
application must be registered in the same directory in Azure AD. The web API can be configured to expose a set
of permissions, which are used to limit the daemon or server’s access to its resources. If a delegated user identity
type is being used, the server application needs to select the desired permissions from the “Permissions to Other
Applications” drop-down menu in the Azure Portal. This step is not required if the application identity type is
being used.
Multi-Tenant: First, the daemon or server 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, which any user in the organization can consent to. Other applications require
administrator-level permissions, which a user in the organization cannot consent to. Only a directory
administrator can give consent to applications that require this level of permissions. When the user or
administrator consents, both of the web APIs are registered in their directory.
Token Expiration
When the first application uses its authorization code to get a JWT access token, it also receives a JWT refresh token.
When the access token expires, the refresh token can be used to re-authenticate the user without prompting for
credentials. This refresh token is then used to authenticate the user, which results in a new access token and refresh
token.
See Also
Azure Active Directory Developer's Guide
Azure Active Directory Code Samples
Important Information About Signing Key Rollover in Azure AD
OAuth 2.0 in Azure AD
Integrate Azure AD into an iOS App
4/27/2017 • 7 min to read • Edit Online
TIP
Try the preview of our new developer portal that will help you get up and running with Azure Active Directory in just a few
minutes! The developer portal will walk you through the process of registering an app and integrating Azure AD into your
code. When you’re finished, you will have a simple application that can authenticate users in your tenant and a backend that
can accept tokens and perform validation.
Azure AD provides the Active Directory Authentication Library, or ADAL, for iOS clients that need to access
protected resources. ADAL’s sole purpose in life is to make it easy for your app to get access tokens. To
demonstrate just how easy it is, here we’ll build a Objective C To-Do List application that:
Gets access tokens for calling the Azure AD Graph API using the OAuth 2.0 authentication protocol.
Searches a directory for users with a given alias.
To build the complete working application, you’ll need to:
1. Register your application with Azure AD.
2. Install & Configure ADAL.
3. Use ADAL to get tokens from Azure AD.
To get started, download the app skeleton or download the completed sample. You'll also need an Azure AD
tenant in which you can create users and register an application. If you don't already have a tenant, learn how to
get one.
1. Determine what your Redirect URI will be for iOS
In order to securely launch your applications in certain SSO scenarios we require that you create a Redirect URI in
a particular format. A Redirect URI is used to ensure that the tokens return to the correct application that asked for
them.
The iOS format for a Redirect URI is:
<app-scheme>://<bundle-id>
aap-scheme - This is registered in your XCode project. It is how other applications can call you. You can find
this under Info.plist -> URL types -> URL Identifier. You should create one if you don't already have one or
more configured.
bundle-id - This is the Bundle Identifier found under "identity" un your project settings in XCode.
An example for this QuickStart code would be:
msquickstart://com.microsoft.azureactivedirectory.samples.graph.QuickStart
2. Register the DirectorySearcher Application
To enable your app to get tokens, you'll first need to register it in your Azure AD tenant and grant it permission to
access the Azure AD Graph API:
1. Sign in to the Azure portal.
2. On the top bar, click on your account and under the Directory list, choose the Active Directory tenant where
you wish to register your application.
3. Click on More Services in the left hand nav, and choose Azure Active Directory.
4. Click on App registrations and choose Add.
5. Follow the prompts and create a new Native Client Application.
The Name of the application will describe your application to end-users
The Redirect Uri is a scheme and string combination that Azure AD will use to return token responses.
Enter a value specific to your application based on the information above.
6. Once you've completed registration, AAD will assign your app a unique Application ID. You'll need this value in
the next sections, so copy it from the application tab.
7. From the Settings page, choose Required Permissions and choose Add. Select the Microsoft Graph as the
API and add the Read Directory Data permission under Delegated Permissions. This will enable your
application to query the Graph API for users.
3. Install & Configure ADAL
Now that you have an application in Azure AD, you can install ADAL and write your identity-related code. In order
for ADAL to be able to communicate with Azure AD, you need to provide it with some information about your app
registration.
Begin by adding ADAL to the DirectorySearcher project using Cocapods.
$ vi Podfile
Add the following to this podfile:
source 'https://github.com/CocoaPods/Specs.git'
link_with ['QuickStart']
xcodeproj 'QuickStart'
pod 'ADALiOS'
Now load the podfile using cocoapods. This will create a new XCode Workspace you will load.
$ pod install
...
$ open QuickStart.xcworkspace
In the QuickStart project, open the plist file settings.plist . Replace the values of the elements in the section to
reflect the values you input into the Azure Portal. Your code will reference these values whenever it uses ADAL.
The tenant is the domain of your Azure AD tenant, e.g. contoso.onmicrosoft.com
The clientId is the clientId of your application you copied from the portal.
The redirectUri is the redirect url you registered in the portal.
4. Use ADAL to Get Tokens from AAD
The basic principle behind ADAL is that whenever your app needs an access token, it simply calls a
completionBlock +(void) getToken : , and ADAL does the rest.
In the
QuickStart
project, open
GraphAPICaller.m
and locate the
// TODO: getToken for generic Web API flows. Returns a token with no additional parameters provided.
comment near the top. This is where you pass ADAL the coordinates through a CompletionBlock to
communicate with Azure AD and tell it how to cache tokens.
+(void) getToken : (BOOL) clearCache
parent:(UIViewController*) parent
completionHandler:(void (^) (NSString*, NSError*))completionBlock;
{
AppData* data = [AppData getInstance];
if(data.userItem){
completionBlock(data.userItem.accessToken, nil);
return;
}
ADAuthenticationError *error;
authContext = [ADAuthenticationContext authenticationContextWithAuthority:data.authority error:&error];
authContext.parentController = parent;
NSURL *redirectUri = [[NSURL alloc]initWithString:data.redirectUriString];
[ADAuthenticationSettings sharedInstance].enableFullScreen = YES;
[authContext acquireTokenWithResource:data.resourceId
clientId:data.clientId
redirectUri:redirectUri
promptBehavior:AD_PROMPT_AUTO
userId:data.userItem.userInformation.userId
extraQueryParameters: @"nux=1" // if this strikes you as strange it was legacy to display
the correct mobile UX. You most likely won't need it in your code.
completionBlock:^(ADAuthenticationResult *result) {
if (result.status != AD_SUCCEEDED)
{
completionBlock(nil, result.error);
}
else
{
data.userItem = result.tokenCacheStoreItem;
completionBlock(result.tokenCacheStoreItem.accessToken, nil);
}
}];
}
Now we need to use this token to search for users in the graph. Find the // TODO: implement SearchUsersList
commentThis method makes a GET request to the Azure AD Graph API to query for users whose UPN begins
with the given search term. But in order to query the Graph API, you need to include an access_token in the
Authorization header of the request - this is where ADAL comes in.
+(void) searchUserList:(NSString*)searchString
parent:(UIViewController*) parent
completionBlock:(void (^) (NSMutableArray* Users, NSError* error)) completionBlock
{
if (!loadedApplicationSettings)
{
[self readApplicationSettings];
}
AppData* data = [AppData getInstance];
NSString *graphURL = [NSString stringWithFormat:@"%@%@/users?apiversion=%@&$filter=startswith(userPrincipalName, '%@')", data.taskWebApiUrlString, data.tenant,
data.apiversion, searchString];
[self craftRequest:[self.class trimString:graphURL]
parent:parent
completionHandler:^(NSMutableURLRequest *request, NSError *error) {
if (error != nil)
{
completionBlock(nil, error);
}
else
{
NSOperationQueue *queue = [[NSOperationQueue alloc]init];
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse
*response, NSData *data, NSError *error) {
if (error == nil && data != nil){
NSDictionary *dataReturned = [NSJSONSerialization JSONObjectWithData:data options:0
error:nil];
// We can grab the top most JSON node to get our graph data.
NSArray *graphDataArray = [dataReturned objectForKey:@"value"];
// Don't be thrown off by the key name being "value". It really is the name of the
// first node. :-)
//each object is a key value pair
NSDictionary *keyValuePairs;
NSMutableArray* Users = [[NSMutableArray alloc]init];
for(int i =0; i < graphDataArray.count; i++)
{
keyValuePairs = [graphDataArray objectAtIndex:i];
User *s = [[User alloc]init];
s.upn = [keyValuePairs valueForKey:@"userPrincipalName"];
s.name =[keyValuePairs valueForKey:@"givenName"];
[Users addObject:s];
}
completionBlock(Users, nil);
}
else
{
completionBlock(nil, error);
}
}];
}
}];
}
When your app requests a token by calling getToken(...) , ADAL will attempt to return a token without asking
the user for credentials. If ADAL determines that the user needs to sign in to get a token, it will display a login
dialog, collect the user's credentials, and return a token upon successful authentication. If ADAL is unable to
return a token for any reason, it will throw an AdalException .
Notice that the AuthenticationResult object contains a tokenCacheStoreItem object that can be used to collect
information your app may need. In the QuickStart, tokenCacheStoreItem is used to determine if authenitcation
has already occurred.
5: Build and Run the application
Congratulations! You now have a working iOS application that has the ability to authenticate users, securely call
Web APIs using OAuth 2.0, and get basic information about the user. If you haven't already, now is the time to
populate your tenant with some users. Run your QuickStart app, and sign in with one of those users. Search for
other users based on their UPN. Close the app, and re-run it. Notice how the user's session remains intact.
ADAL makes it easy to incorporate all of these common identity features into your application. It takes care of all
the dirty work for you - cache management, OAuth protocol support, presenting the user with a login UI,
refreshing expired tokens, and more. All you really need to know is a single API call, getToken .
For reference, the completed sample (without your configuration values) is provided here.
Additional scenarios
You can now move on to additional scenarios. You may want to try:
Secure a Node.JS Web API with Azure AD
Learn How to enable cross-app SSO on iOS using ADAL
Additional resources
The Azure AD developer's guide
Azure AD samples on GitHub
CloudIdentity.com
Get security updates for our products
We encourage you to get notifications of when security incidents occur by visiting the TechCenter page for
Microsoft technical security notifications and subscribing to security advisory alerts.
Integrate Azure AD into an Android app
4/27/2017 • 14 min to read • Edit Online
TIP
Try the preview of our new developer portal, which will help you get up and running with Azure AD in just a few minutes.
The developer portal will walk you through the process of registering an app and integrating Azure AD into your code.
When you’re finished, you'll have a simple application that can authenticate users in your tenant and a back end that can
accept tokens and perform validation.
If you're developing a desktop application, Azure Active Directory (Azure AD) makes it simple and straightforward
for you to authenticate your users by using their on-premises Active Directory accounts. It also enables your
application to securely consume any web API protected by Azure AD, such as the Office 365 APIs or the Azure API.
For Android clients that need to access protected resources, Azure AD provides the Active Directory Authentication
Library (ADAL). The sole purpose of ADAL is to make it easy for your app to get access tokens. To demonstrate
how easy it is, we’ll build an Android To-Do List application that:
Gets access tokens for calling a To-Do List API by using the OAuth 2.0 authentication protocol.
Gets a user's to-do list.
Signs out users.
To get started, you need an Azure AD tenant in which you can create users and register an application. If you don't
already have a tenant, learn how to get one.
Step 1: Download and run the Node.js REST API TODO sample server
The Node.js REST API TODO sample is written specifically to work against our existing sample for building a
single-tenant To-Do REST API for Azure AD. This is a prerequisite for the Quick Start.
For information on how to set this up, see our existing samples in Microsoft Azure Active Directory Sample REST
API Service for Node.js.
Step 2: Register your web API with your Azure AD tenant
Active Directory supports adding two types of applications:
Web APIs that offer services to users
Applications (running either on the web or on a device) that access those web APIs
In this step, you're registering the web API that you're running locally for testing this sample. Normally, this web
API is a REST service that's offering functionality that you want an app to access. Azure AD can help protect any
endpoint.
We're assuming that you're registering the TODO REST API referenced earlier. But this works for any web API that
you want Azure Active Directory to help protect.
1. Sign in to the Azure portal.
2. On the top bar, click your account. In the Directory list, choose the Azure AD tenant where you want to register
your application.
3. Click More Services in the left pane, and then select Azure Active Directory.
4. Click App registrations, and then select Add.
5. Enter a friendly name for the application (for example, TodoListService), select Web Application and/or
Web API, and click Next.
6. For the sign-on URL, enter the base URL for the sample. By default, this is https://localhost:8080 .
7. Click OK to complete the registration.
8. While still in the Azure portal, go to your application page, find the application ID value, and copy it. You'll need
this later when configuring your application.
9. From the Settings -> Properties page, update the app ID URI - enter
https://<your_tenant_name>/TodoListService . Replace <your_tenant_name> with the name of your Azure AD
tenant.
Step 3: Register the sample Android Native Client application
You must register your web application in this sample. This allows your application to communicate with the justregistered web API. Azure AD will refuse to even allow your application to ask for sign-in unless it's registered.
That's part of the security of the model.
We're assuming that you're registering the sample application referenced earlier. But this procedure works for any
app that you're developing.
NOTE
You might wonder why you're putting both an application and a web API in one tenant. As you might have guessed, you
can build an app that accesses an external API that is registered in Azure AD from another tenant. If you do that, your
customers will be prompted to consent to the use of the API in the application. Active Directory Authentication Library for
iOS takes care of this consent for you. As we explore more advanced features, you'll see that this is an important part of the
work needed to access the suite of Microsoft APIs from Azure and Office, as well as any other service provider. For now,
because you registered both your web API and your application under the same tenant, you won't see any prompts for
consent. This is usually the case if you're developing an application just for your own company to use.
1. Sign in to the Azure portal.
2. On the top bar, click your account. In the Directory list, choose the Azure AD tenant where you want to register
your application.
3. Click More Services in the left pane, and then select Azure Active Directory.
4. Click App registrations, and then select Add.
5. Enter a friendly name for the application (for example, TodoListClient-Android), select Native Client
Application, and click Next.
6. For the redirect URI, enter http://TodoListClient . Click Finish.
7. From the application page, find the application ID value and copy it. You'll need this later when configuring
your application.
8. From the Settings page, select Required Permissions and select Add. Locate and select TodoListService, add
the Access TodoListService permission under Delegated Permissions, and click Done.
To build with Maven, you can use pom.xml at the top level:
1. Clone this repo into a directory of your choice:
$ git clone [email protected]:AzureADSamples/NativeClient-Android.git
2. Follow the steps in the prerequisites to set up your Maven environment for Android.
3. Set up the emulator with SDK 19.
4. Go to the root folder where you cloned the repo.
5. Run this command: mvn clean install
6. Change the directory to the Quick Start sample: cd samples\hello
7. Run this command: mvn android:deploy android:run
You should see the app starting.
8. Enter test user credentials to try.
JAR packages will be submitted beside the AAR package.
Step 4: Download the Android ADAL and add it to your Eclipse
workspace
We've made it easy for you to have multiple options to use ADAL in your Android project:
You can use the source code to import this library into Eclipse and link to your application.
If you're using Android Studio, you can use the AAR package format and reference the binaries.
Option 1: Source Zip
To download a copy of the source code, click Download ZIP on the right side of the page. Or you can download
from GitHub.
Option 2: Source via Git
To get the source code of the SDK via Git, type:
git clone [email protected]:AzureAD/azure-activedirectory-library-for-android.git
cd ./azure-activedirectory-library-for-android/src
Option 3: Binaries via Gradle
You can get the binaries from the Maven central repo. The AAR package can be included as follows in your project
in Android Studio:
repositories {
mavenCentral()
flatDir {
dirs 'libs'
}
maven {
url "YourLocalMavenRepoPath\\.m2\\repository"
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile('com.microsoft.aad:adal:1.1.1') {
exclude group: 'com.android.support'
} // Recent version is 1.1.1
}
Option 4: AAR via Maven
If you're using the M2Eclipse plug-in, you can specify the dependency in your pom.xml file:
<dependency>
<groupId>com.microsoft.aad</groupId>
<artifactId>adal</artifactId>
<version>1.1.1</version>
<type>aar</type>
</dependency>
Option 5: JAR package inside the libs folder
You can get the JAR file from the Maven repo and drop it into the libs folder in your project. You need to copy the
required resources to your project as well, because the JAR packages don't include them.
Step 5: Add references to Android ADAL to your project
1. Add a reference to your project and specify it as an Android library. If you're uncertain how to do this, you can
get more information on the Android Studio site.
2. Add the project dependency for debugging into your project settings.
3. Update your project's AndroidManifest.xml file to include:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:debuggable="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.microsoft.aad.adal.AuthenticationActivity"
android:label="@string/title_login_hello_app" >
</activity>
....
<application/>
4. Create an instance of AuthenticationContext at your main activity. The details of this call are beyond the
scope of this topic, but you can get a good start by looking at the Android Native Client sample. In the
following example, SharedPreferences is the default cache, and Authority is in the form of
https://login.windows.net/yourtenant.onmicrosoft.com :
mContext = new AuthenticationContext(MainActivity.this, authority, true); // mContext is a field in your
activity
5. Copy this code block to handle the end of AuthenticationActivity after the user enters credentials and
receives an authorization code:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (mContext != null) {
mContext.onActivityResult(requestCode, resultCode, data);
}
}
6. To ask for a token, define a callback:
private AuthenticationCallback<AuthenticationResult> callback = new
AuthenticationCallback<AuthenticationResult>() {
@Override
public void onError(Exception exc) {
if (exc instanceof AuthenticationException) {
textViewStatus.setText("Cancelled");
Log.d(TAG, "Cancelled");
} else {
textViewStatus.setText("Authentication error:" + exc.getMessage());
Log.d(TAG, "Authentication error:" + exc.getMessage());
}
}
@Override
public void onSuccess(AuthenticationResult result) {
mResult = result;
if (result == null || result.getAccessToken() == null
|| result.getAccessToken().isEmpty()) {
textViewStatus.setText("Token is empty");
Log.d(TAG, "Token is empty");
} else {
// request is successful
Log.d(TAG, "Status:" + result.getStatus() + " Expired:"
+ result.getExpiresOn().toString());
textViewStatus.setText(PASSED);
}
}
};
7. Finally, ask for a token by using that callback:
mContext.acquireToken(MainActivity.this, resource, clientId, redirect, user_loginhint,
PromptBehavior.Auto, "", callback);
Here's an explanation of the parameters:
resource is required and is the resource you're trying to access.
clientid is required and comes from Azure AD.
RedirectUri is not required to be provided for the acquireToken call. You can set it up as your package name.
PromptBehavior helps to ask for credentials to skip the cache and cookie.
callback is called after the authorization code is exchanged for a token. It has an object of AuthenticationResult,
which has access token, date expired, and ID token information.
acquireTokenSilent is optional. You can call it to handle caching and token refresh. It also provides the sync
version. It accepts userId as a parameter.
mContext.acquireTokenSilent(resource, clientid, userId, callback );
By using this walkthrough, you should have what you need to successfully integrate with Azure Active Directory.
For more examples of this working, visit the AzureADSamples/ repository on GitHub.
Important information
Customization
Your application resources can overwrite library project resources. This happens when your app is being built. For
this reason, you can customize authentication activity layout the way you want. Be sure to keep the ID of the
controls that ADAL uses (WebView).
Broker
The Microsoft Intune Company Portal app provides the broker component. The account is created in
AccountManager. The account type is "com.microsoft.workaccount." AccountManager allows only a single SSO
account. It creates an SSO cookie for the user after completing the device challenge for one of the apps.
ADAL uses the broker account if one user account is created at this authenticator and you choose not to skip it.
You can skip the broker user with:
AuthenticationSettings.Instance.setSkipBroker(true);
You need to register a special RedirectUri for broker usage. RedirectUri is in the format of
msauth://packagename/Base64UrlencodedSignature . You can get your RedirectUri for your app by using the script
brokerRedirectPrint.ps1 or the API call mContext.getBrokerRedirectUri. The signature is related to your signing
certificates.
The current broker model is for one user. AuthenticationContext provides the API method to get the broker user.
String brokerAccount = mContext.getBrokerUser(); //Broker user is returned if account is valid.
Your app manifest should have the following permissions to use AccountManager accounts. For details, see the
AccountManager information on the Android site.
GET_ACCOUNTS
USE_CREDENTIALS
MANAGE_ACCOUNTS
Authority URL and AD FS
Active Directory Federation Services (AD FS) is not recognized as production STS, so you need to turn of instance
discovery and pass false at the AuthenticationContext constructor.
The authority URL needs an STS instance and a tenant name.
Querying cache items
ADAL provides a default cache in SharedPreferences with some simple cache query functions. You can get the
current cache from AuthenticationContext by using:
ITokenCacheStore cache = mContext.getCache();
You can also provide your cache implementation, if you want to customize it.
mContext = new AuthenticationContext(MainActivity.this, authority, true, yourCache);
Prompt behavior
ADAL provides an option to specify prompt behavior. PromptBehavior.Auto will show the UI if the refresh token is
invalid and user credentials are required. PromptBehavior.Always will skip the cache usage and always show the
UI.
Silent token request from cache and refresh
A silent token request does not use the UI pop-up and does not require an activity. It returns a token from the
cache if available. If the token is expired, this method tries to refresh it. If the refresh token is expired or failed, it
returns AuthenticationException.
Future<AuthenticationResult> result = mContext.acquireTokenSilent(resource, clientid, userId, callback );
You can also make a sync call by using this method. You can set null to callback or use acquireTokenSilentSync.
Diagnostics
These are the primary sources of information for diagnosing issues:
Exceptions
Logs
Network traces
Note that correlation IDs are central to the diagnostics in the library. You can set your correlation IDs on a perrequest basis if you want to correlate an ADAL request with other operations in your code. If you don't set a
correlation ID, ADAL will generate a random one. All log messages and network calls will then be stamped with
the correlation ID. The self-generated ID changes on each request.
Exceptions
Exceptions are the first diagnostic. We try to provide helpful error messages. If you find one that is not helpful,
please file an issue and let us know. Include device information such as model and SDK number.
Logs
You can configure the library to generate log messages that you can use to help diagnose issues. You configure
logging by making the following call to configure a callback that ADAL will use to hand off each log message as
it's generated.
Logger.getInstance().setExternalLogger(new ILogger() {
@Override
public void Log(String tag, String message, String additionalMessage, LogLevel level, ADALError errorCode)
{
...
// You can write this to log file depending on level or error code.
writeToLogFile(getApplicationContext(), tag +":" + message + "-" + additionalMessage);
}
}
Messages can be written to a custom log file, as shown in the following code. Unfortunately, there is no standard
way of getting logs from a device. There are some services that can help you with this. You can also invent your
own, such as sending the file to a server.
private syncronized void writeToLogFile(Context ctx, String msg) {
File directory = ctx.getDir(ctx.getPackageName(), Context.MODE_PRIVATE);
File logFile = new File(directory, "logfile");
FileOutputStream outputStream = new FileOutputStream(logFile, true);
OutputStreamWriter osw = new OutputStreamWriter(outputStream);
osw.write(msg);
osw.flush();
osw.close();
}
These are the logging levels:
Error (exceptions)
Warn (warning)
Info (information purposes)
Verbose (more details)
You set the log level like this:
Logger.getInstance().setLogLevel(Logger.LogLevel.Verbose);
All log messages are sent to logcat, in addition to any custom log callbacks. You can get a log to a file from logcat
as follows:
adb logcat > "C:\logmsg\logfile.txt"
For details about adb commands, see the logcat information on the Android site.
Network traces
You can use various tools to capture the HTTP traffic that ADAL generates. This is most useful if you're familiar
with the OAuth protocol or if you need to provide diagnostic information to Microsoft or other support channels.
Fiddler is the easiest HTTP tracing tool. Use the following links to set it up to correctly record ADAL network traffic.
For a tracing tool like Fiddler or Charles to be useful, you must configure it to record unencrypted SSL traffic.
NOTE
Traces generated in this way might contain highly privileged information such as access tokens, usernames, and passwords.
If you're using production accounts, do not share these traces with third parties. If you need to supply a trace to someone
in order to get support, reproduce the issue by using a temporary account with usernames and passwords that you don't
mind sharing.
From the Telerik website: Setting Up Fiddler For Android
From GitHub: Configure Fiddler Rules For ADAL
Dialog mode
The acquireToken method without activity supports a dialog prompt.
Encryption
ADAL encrypts the tokens and store in SharedPreferences by default. You can look at the StorageHelper class to
see the details. Android introduced Android Keystore for 4.3 (API 18) secure storage of private keys. ADAL uses
that for API 18 and higher. If you want to use ADAL for lower SDK versions, you need to provide a secret key at
AuthenticationSettings.INSTANCE.setSecretKey.
OAuth2 bearer challenge
The AuthenticationParameters class provides functionality to get authorization_uri from the OAuth2 bearer
challenge.
Session cookies in WebView
Android WebView does not clear session cookies after the app is closed. You can handle that by using this sample
code:
CookieSyncManager.createInstance(getApplicationContext());
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.removeSessionCookie();
CookieSyncManager.getInstance().sync();
For details about cookies, see the CookieSyncManager information on the Android site.
Resource overrides
The ADAL library includes English strings for ProgressDialog messages. Your application should overwrite them if
you want localized strings.
<string
<string
<string
<string
<string
<string
<string
name="app_loading">Loading...</string>
name="broker_processing">Broker is processing</string>
name="http_auth_dialog_username">Username</string>
name="http_auth_dialog_password">Password</string>
name="http_auth_dialog_title">Sign In</string>
name="http_auth_dialog_login">Login</string>
name="http_auth_dialog_cancel">Cancel</string>
NTLM dialog box
ADAL version 1.1.0 supports an NTLM dialog box that is processed through the onReceivedHttpAuthRequest
event from WebViewClient. You can customize the layout and strings for the dialog box.
Cross-app SSO
Learn how to enable cross-app SSO on Android by using ADAL.
Additional resources
The Azure AD developer's guide
Azure AD samples on GitHub
CloudIdentity.com
Get security updates for our products
We encourage you to get notifications of when security incidents occur by visiting the TechCenter page for
Microsoft technical security notifications and subscribing to security advisory alerts.
Integrate Azure AD into a Windows Desktop WPF
App
2/3/2017 • 6 min to read • Edit Online
NOTE
This article is part of the Azure Active Directory developer's guide.
If you're developing a desktop application, Azure AD makes it simple and straightforward for you to authenticate
your users with their Active Directory accounts. It also enables your application to securely consume any web API
protected by Azure AD, such as the Office 365 APIs or the Azure API.
For .NET native clients that need to access protected resources, Azure AD provides the Active Directory
Authentication Library, or ADAL. ADAL's sole purpose in life is to make it easy for your app to get access tokens.
To demonstrate just how easy it is, here we'll build a .NET WPF To-Do List application that:
Gets access tokens for calling the Azure AD Graph API using the OAuth 2.0 authentication protocol.
Searches a directory for users with a given alias.
Signs users out.
To build the complete working application, you'll need to:
1. Register your application with Azure AD.
2. Install & Configure ADAL.
3. Use ADAL to get tokens from Azure AD.
To get started, download the app skeleton or download the completed sample. You'll also need an Azure AD
tenant in which you can create users and register an application. If you don't already have a tenant, learn how to
get one.
1. Register the DirectorySearcher Application
To enable your app to get tokens, you'll first need to register it in your Azure AD tenant and grant it permission to
access the Azure AD Graph API:
1. Sign in to the Azure portal.
2. On the top bar, click on your account and under the Directory list, choose the Active Directory tenant where
you wish to register your application.
3. Click on More Services in the left hand nav, and choose Azure Active Directory.
4. Click on App registrations and choose Add.
5. Follow the prompts and create a new Native Client Application.
The Name of the application will describe your application to end-users
The Redirect Uri is a scheme and string combination that Azure AD will use to return token responses.
Enter a value specific to your application, e.g. http://DirectorySearcher .
6. Once you've completed registration, AAD will assign your app a unique Application ID. You'll need this value in
the next sections, so copy it from the application page.
7. From the Settings page, choose Required Permissions and choose Add. Select the Microsoft Graph as the
API and add the Read Directory Data permission under Delegated Permissions. This will enable your
application to query the Graph API for users.
2. Install & Configure ADAL
Now that you have an application in Azure AD, you can install ADAL and write your identity-related code. In order
for ADAL to be able to communicate with Azure AD, you need to provide it with some information about your app
registration.
Begin by adding ADAL to the DirectorySearcher project using the Package Manager Console.
PM> Install-Package Microsoft.IdentityModel.Clients.ActiveDirectory
In the DirectorySearcher project, open app.config . Replace the values of the elements in the <appSettings>
section to reflect the values you input into the Azure Portal. Your code will reference these values whenever it
uses ADAL.
The ida:Tenant is the domain of your Azure AD tenant, e.g. contoso.onmicrosoft.com
The ida:ClientId is the clientId of your application you copied from the portal.
The ida:RedirectUri is the redirect url you registered in the portal.
3. Use ADAL to Get Tokens from AAD
The basic principle behind ADAL is that whenever your app needs an access token, it simply calls
authContext.AcquireTokenAsync(...) , and ADAL does the rest.
In the DirectorySearcher project, open MainWindow.xaml.cs and locate the MainWindow() method. The first step
is to initialize your app's AuthenticationContext - ADAL's primary class. This is where you pass ADAL the
coordinates it needs to communicate with Azure AD and tell it how to cache tokens.
public MainWindow()
{
InitializeComponent();
authContext = new AuthenticationContext(authority, new FileCache());
CheckForCachedToken();
}
Now locate the Search(...) method, which will be invoked when the user cliks the "Search" button in the
app's UI. This method makes a GET request to the Azure AD Graph API to query for users whose UPN begins
with the given search term. But in order to query the Graph API, you need to include an access_token in the
Authorization header of the request - this is where ADAL comes in.
private async void Search(object sender, RoutedEventArgs e)
{
// Validate the Input String
if (string.IsNullOrEmpty(SearchText.Text))
{
MessageBox.Show("Please enter a value for the To Do item name");
return;
}
// Get an Access Token for the Graph API
AuthenticationResult result = null;
try
{
result = await authContext.AcquireTokenAsync(graphResourceId, clientId, redirectUri, new
PlatformParameters(PromptBehavior.Auto));
UserNameLabel.Content = result.UserInfo.DisplayableId;
SignOutButton.Visibility = Visibility.Visible;
}
catch (AdalException ex)
{
// An unexpected error occurred, or user canceled the sign in.
if (ex.ErrorCode != "access_denied")
MessageBox.Show(ex.Message);
return;
}
...
}
When your app requests a token by calling AcquireTokenAsync(...) , ADAL will attempt to return a token
without asking the user for credentials. If ADAL determines that the user needs to sign in to get a token, it will
display a login dialog, collect the user's credentials, and return a token upon successful authentication. If ADAL
is unable to return a token for any reason, it will throw an AdalException .
Notice that the AuthenticationResult object contains a UserInfo object that can be used to collect information
your app may need. In the DirectorySearcher, UserInfo is used to customize the app's UI with the user's id.
When the user clicks the "Sign Out" button, we want to ensure that the next call to AcquireTokenAsync(...) will
ask the user to sign in. With ADAL, this is as easy as clearing the token cache:
private void SignOut(object sender = null, RoutedEventArgs args = null)
{
// Clear the token cache
authContext.TokenCache.Clear();
...
}
However, if the user does not click the "Sign Out" button, you will want to maintain the user's session for the
next time they run the DirectorySearcher. When the app launches, you can check ADAL's token cache for an
existing token and update the UI accordingly. In the CheckForCachedToken() method, make another call to
AcquireTokenAsync(...) , this time passing in the PromptBehavior.Never parameter. PromptBehavior.Never will
tell ADAL that the user should not be prompted for sign in, and ADAL should instead throw an exception if it is
unable to return a token.
public async void CheckForCachedToken()
{
// As the application starts, try to get an access token without prompting the user. If one exists, show
the user as signed in.
AuthenticationResult result = null;
try
{
result = await authContext.AcquireTokenAsync(graphResourceId, clientId, redirectUri, new
PlatformParameters(PromptBehavior.Never));
}
catch (AdalException ex)
{
if (ex.ErrorCode != "user_interaction_required")
{
// An unexpected error occurred.
MessageBox.Show(ex.Message);
}
// If user interaction is required, proceed to main page without singing the user in.
return;
}
// A valid token is in the cache
SignOutButton.Visibility = Visibility.Visible;
UserNameLabel.Content = result.UserInfo.DisplayableId;
}
Congratulations! You now have a working .NET WPF application that has the ability to authenticate users, securely
call Web APIs using OAuth 2.0, and get basic information about the user. If you haven't already, now is the time to
populate your tenant with some users. Run your DirectorySearcher app, and sign in with one of those users.
Search for other users based on their UPN. Close the app, and re-run it. Notice how the user's session remains
intact. Sign out, and sign back in as another user.
ADAL makes it easy to incorporate all of these common identity features into your application. It takes care of all
the dirty work for you - cache management, OAuth protocol support, presenting the user with a login UI,
refreshing expired tokens, and more. All you really need to know is a single API call,
authContext.AcquireTokenAsync(...) .
For reference, the completed sample (without your configuration values) is provided here. You can now move on
to additional scenarios. You may want to try:
Secure a .NET Web API with Azure AD >>
Additional resources
The Azure AD developer's guide
Azure AD samples on GitHub
CloudIdentity.com
Get security updates for our products
We encourage you to get notifications of when security incidents occur by visiting the TechCenter page for
Microsoft technical security notifications and subscribing to security advisory alerts.
Integrate Azure AD with Windows Store apps
2/17/2017 • 6 min to read • Edit Online
NOTE
This article is part of the Azure Active Directory developer's guide.
If you're developing apps for the Windows Store, Azure Active Directory (Azure AD) makes it simple and
straightforward to authenticate your users with their Active Directory accounts. By integrating with Azure AD, an
app can securely consume any web API that's protected by Azure AD, such as the Office 365 APIs or the Azure API.
For Windows Store desktop apps that need to access protected resources, Azure AD provides the Active Directory
Authentication Library (ADAL). The sole purpose of ADAL is to make it easy for the app to get access tokens. To
demonstrate how easy it is, this article shows how to build a DirectorySearcher Windows Store app that:
Gets access tokens for calling the Azure AD Graph API by using the OAuth 2.0 authentication protocol.
Searches a directory for users with a given user principal name (UPN).
Signs users out.
Before you get started
Download the skeleton project, or download the completed sample. Each download is a Visual Studio 2015
solution.
You also need an Azure AD tenant in which to create users and register the app. If you don't already have a
tenant, learn how to get one.
When you are ready, follow the procedures in the next three sections.
Step 1: Register the DirectorySearcher app
To enable the app to get tokens, you first need to register it in your Azure AD tenant and grant it permission to
access the Azure AD Graph API. Here's how:
1. Sign in to the Azure portal.
2. On the top bar, click your account. Then, under the Directory list, select the Active Directory tenant where you
want to register the app.
3. Click More Services in the left pane, and then select Azure Active Directory.
4. Click App registrations, and then select Add.
5. Follow the prompts to create a Native Client Application.
Name describes the app to users.
Redirect URI is a scheme and string combination that Azure AD uses to return token responses. Enter a
placeholder value for now (for example, http://DirectorySearcher). You'll replace the value later.
6. After you’ve completed the registration, Azure AD assigns the app a unique application ID. Copy the value on
the Application tab, because you'll need it later.
7. On the Settings page, select Required Permissions, and then select Add.
8. For the Azure Active Directory app, select Microsoft Graph as the API.
9. Under Delegated Permissions, add the Access the directory as the signed-in user permission. Doing so
enables the app to query the Graph API for users.
Step 2: Install and configure ADAL
Now that you have an app in Azure AD, you can install ADAL and write your identity-related code. To enable ADAL
to communicate with Azure AD, give it some information about the app registration.
1. Add ADAL to the DirectorySearcher project by using the Package Manager Console.
PM> Install-Package Microsoft.IdentityModel.Clients.ActiveDirectory
2. In the DirectorySearcher project, open MainPage.xaml.cs.
3. Replace the values in the Config Values region with the values that you entered in the Azure portal. Your code
refers to these values whenever it uses ADAL.
The tenant is the domain of your Azure AD tenant (for example, contoso.onmicrosoft.com).
The clientId is the client ID of the app, which you copied from the portal.
4. You now need to discover the callback URI for your Windows Store app. Set a breakpoint on this line in the
MainPage method:
redirectURI =
Windows.Security.Authentication.Web.WebAuthenticationBroker.GetCurrentApplicationCallbackUri();
5. Build the solution, making sure that all package references are restored. If any packages are missing, open the
NuGet Package Manager and restore them.
6. Run the app, and copy the value of redirectUri when the breakpoint is hit. The value should look
something like the following:
ms-app://s-1-15-2-1352796503-54529114-405753024-3540103335-3203256200-511895534-1429095407/
7. Back on the Settings tab of the app in the Azure portal, add a RedirectUri with the preceding value.
Step 3: Use ADAL to get tokens from Azure AD
The basic principle behind ADAL is that whenever the app needs an access token, it simply calls
authContext.AcquireToken(…) , and ADAL does the rest.
1. Initialize the app’s AuthenticationContext , which is the primary class of ADAL. This action passes ADAL the
coordinates it needs to communicate with Azure AD and tell it how to cache tokens.
public MainPage()
{
...
authContext = new AuthenticationContext(authority);
}
2. Locate the Search(...) method, which is invoked when users click the Search button on the app's UI. This
method makes a get request to the Azure AD Graph API to query for users whose UPN begins with the
given search term. To query the Graph API, include an access token in the request's Authorization header.
This is where ADAL comes in.
private async void Search(object sender, RoutedEventArgs e)
{
...
AuthenticationResult result = null;
try
{
result = await authContext.AcquireTokenAsync(graphResourceId, clientId, redirectURI, new
PlatformParameters(PromptBehavior.Auto, false));
}
catch (AdalException ex)
{
if (ex.ErrorCode != "authentication_canceled")
{
ShowAuthError(string.Format("If the error continues, please contact your
administrator.\n\nError: {0}\n\nError Description:\n\n{1}", ex.ErrorCode, ex.Message));
}
return;
}
...
}
When the app requests a token by calling AcquireTokenAsync(...) , ADAL attempts to return a token
without asking the user for credentials. If ADAL determines that the user needs to sign in to get a token, it
displays a sign-in dialog box, collects the user's credentials, and returns a token after authentication
succeeds. If ADAL is unable to return a token for any reason, the AuthenticationResult status is an error.
3. Now it's time to use the access token you just acquired. Also in the
to the Graph API get request in the Authorization header:
Search(...)
method, attach the token
// Add the access token to the Authorization header of the call to the Graph API, and call the Graph
API.
httpClient.DefaultRequestHeaders.Authorization = new HttpCredentialsHeaderValue("Bearer",
result.AccessToken);
4. You can use the
user's ID:
AuthenticationResult
object to display information about the user in the app, such as the
// Update the page UI to represent the signed-in user
ActiveUser.Text = result.UserInfo.DisplayableId;
5. You can also use ADAL to sign users out of the app. When the user clicks the Sign Out button, ensure that
the next call to AcquireTokenAsync(...) shows a sign-in view. With ADAL, this action is as easy as clearing
the token cache:
private void SignOut()
{
// Clear session state from the token cache.
authContext.TokenCache.Clear();
...
}
What's next
You now have a working Windows Store app that can authenticate users, securely call web APIs using OAuth 2.0,
and get basic information about the user.
If you haven’t already populated your tenant with users, now is the time to do so.
1.
2.
3.
4.
Run your DirectorySearcher app, and then sign in with one of the users.
Search for other users based on their UPN.
Close the app, and rerun it. Notice how the user’s session remains intact.
Sign out by right-clicking to display the bottom bar, and then sign back in as another user.
ADAL makes it easy to incorporate all these common identity features into the app. It takes care of all the dirty
work for you, such as cache management, OAuth protocol support, presenting the user with a login UI, and
refreshing expired tokens. You need to know only a single API call, authContext.AcquireToken*(…) .
For reference, download the completed sample (without your configuration values).
You can now move on to additional identity scenarios. For example, try Secure a .NET Web API with Azure AD.
Additional resources
The Azure AD developer's guide
Azure AD samples on GitHub
CloudIdentity.com
Get security updates for our products
We encourage you to get notifications of when security incidents occur by visiting the TechCenter page for
Microsoft technical security notifications and subscribing to security advisory alerts.
Integrate Azure AD with Xamarin apps
2/17/2017 • 6 min to read • Edit Online
NOTE
This article is part of the Azure Active Directory developer's guide.
With Xamarin, you can write mobile apps in C# that can run on iOS, Android, and Windows (mobile devices and
PCs). If you're building an app using Xamarin, Azure Active Directory (Azure AD) makes it simple to authenticate
users with their Azure AD accounts. The app can also securely consume any web API that's protected by Azure AD,
such as the Office 365 APIs or the Azure API.
For Xamarin apps that need to access protected resources, Azure AD provides the Active Directory Authentication
Library (ADAL). The sole purpose of ADAL is to make it easy for apps to get access tokens. To demonstrate how
easy it is, this article shows how to build DirectorySearcher apps that:
Run on iOS, Android, Windows Desktop, Windows Phone, and Windows Store.
Use a single portable class library (PCL) to authenticate users and get tokens for the Azure AD Graph API.
Search a directory for users with a given UPN.
Before you get started
Download the skeleton project, or download the completed sample. Each download is a Visual Studio 2013
solution.
You also need an Azure AD tenant in which to create users and register the app. If you don't already have a
tenant, learn how to get one.
When you are ready, follow the procedures in the next four sections.
Step 1: Set up your Xamarin development environment
Because this tutorial includes projects for iOS, Android, and Windows, you need both Visual Studio and Xamarin.
To create the necessary environment, complete the process in Set up and install Visual Studio and Xamarin on
MSDN. The instructions include material that you can review to learn more about Xamarin while you're waiting
for the installations to be completed.
After you've completed the setup, open the solution in Visual Studio. There, you will find six projects: five
platform-specific projects and one PCL, DirectorySearcher.cs, which will be shared across all platforms.
Step 2: Register the DirectorySearcher app
To enable the app to get tokens, you first need to register it in your Azure AD tenant and grant it permission to
access the Azure AD Graph API. Here's how:
1. Sign in to the Azure portal.
2. On the top bar, click your account. Then, under the Directory list, select the Active Directory tenant where you
want to register the app.
3. Click More Services in the left pane, and then select Azure Active Directory.
4. Click App registrations, and then select Add.
5. To create a new Native Client Application, follow the prompts.
Name describes the app to users.
Redirect URI is a scheme and string combination that Azure AD uses to return token responses. Enter a
value (for example, http://DirectorySearcher).
6. After you’ve completed registration, Azure AD assigns the app a unique application ID. Copy the value from
the Application tab, because you'll need it later.
7. On the Settings page, select Required Permissions, and then select Add.
8. Select Microsoft Graph as the API. Under Delegated Permissions, add the Read Directory Data
permission.
This action enables the app to query the Graph API for users.
Step 3: Install and configure ADAL
Now that you have an app in Azure AD, you can install ADAL and write your identity-related code. To enable ADAL
to communicate with Azure AD, give it some information about the app registration.
1. Add ADAL to the DirectorySearcher project by using the Package Manager Console.
PM> Install-Package Microsoft.IdentityModel.Clients.ActiveDirectory -ProjectName DirectorySearcherLib
PM> Install-Package Microsoft.IdentityModel.Clients.ActiveDirectory -ProjectName DirSearchClientAndroid
PM> Install-Package Microsoft.IdentityModel.Clients.ActiveDirectory -ProjectName DirSearchClientDesktop
PM> Install-Package Microsoft.IdentityModel.Clients.ActiveDirectory -ProjectName DirSearchClient-iOS
PM> Install-Package Microsoft.IdentityModel.Clients.ActiveDirectory -ProjectName DirSearchClientUniversal
Note that two library references are added to each project: the PCL portion of ADAL and a platform-specific
portion.
2. In the DirectorySearcherLib project, open DirectorySearcher.cs.
3. Replace the class member values with the values that you entered in the Azure portal. Your code refers to
these values whenever it uses ADAL.
The tenant is the domain of your Azure AD tenant (for example, contoso.onmicrosoft.com).
The clientId is the client ID of the app, which you copied from the portal.
The returnUri is the redirect URI that you entered in the portal (for example, http://DirectorySearcher).
Step 4: Use ADAL to get tokens from Azure AD
Almost all of the app's authentication logic lies in DirectorySearcher.SearchByAlias(...) . All that's necessary in
the platform-specific projects is to pass a contextual parameter to the DirectorySearcher PCL.
1. Open DirectorySearcher.cs, and then add a new parameter to the SearchByAlias(...) method.
IPlatformParameters is the contextual parameter that encapsulates the platform-specific objects that ADAL
needs to perform the authentication.
public static async Task<List<User>> SearchByAlias(string alias, IPlatformParameters parent)
{
2. Initialize AuthenticationContext , which is the primary class of ADAL.
This action passes ADAL the coordinates it needs to communicate with Azure AD.
3. Call
AcquireTokenAsync(...)
, which accepts the
IPlatformParameters
object and invokes the authentication
flow that's necessary to return a token to the app.
...
AuthenticationResult authResult = null;
try
{
AuthenticationContext authContext = new AuthenticationContext(authority);
authResult = await authContext.AcquireTokenAsync(graphResourceUri, clientId, returnUri,
parent);
}
catch (Exception ee)
{
results.Add(new User { error = ee.Message });
return results;
}
...
first attempts to return a token for the requested resource (the Graph API in this
case) without prompting users to enter their credentials (via caching or refreshing old tokens). As
necessary, it shows users the Azure AD sign-in page before acquiring the requested token.
AcquireTokenAsync(...)
4. Attach the access token to the Graph API request in the Authorization header:
...
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", authResult.AccessToken);
...
That's all for the
PCL and the app's identity-related code. All that remains is to call the
method in each platform's views and, where necessary, to add code for correctly handling the
DirectorySearcher
SearchByAlias(...)
UI lifecycle.
Android
1. In MainActivity.cs, add a call to
SearchByAlias(...)
in the button click handler:
List<User> results = await DirectorySearcher.SearchByAlias(searchTermText.Text, new
PlatformParameters(this));
2. Override the OnActivityResult lifecycle method to forward any authentication redirects back to the
appropriate method. ADAL provides a helper method for this in Android:
...
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
base.OnActivityResult(requestCode, resultCode, data);
AuthenticationAgentContinuationHelper.SetAuthenticationAgentContinuationEventArgs(requestCode,
resultCode, data);
}
...
Windows Desktop
In MainWindow.xaml.cs, make a call to
PlatformParameters object:
SearchByAlias(...)
by passing a
WindowInteropHelper
in the desktop's
List<User> results = await DirectorySearcher.SearchByAlias(
SearchTermText.Text,
new PlatformParameters(PromptBehavior.Auto, this.Handle));
iOS
In DirSearchClient_iOSViewController.cs, the iOS
Controller:
PlatformParameters
object takes a reference to the View
List<User> results = await DirectorySearcher.SearchByAlias(
SearchTermText.Text,
new PlatformParameters(PromptBehavior.Auto, this.Handle));
Windows Universal
In Windows Universal, open MainPage.xaml.cs, and then implement the
helper method in a shared project to update UI as necessary.
Search
method. This method uses a
...
List<User> results = await DirectorySearcherLib.DirectorySearcher.SearchByAlias(SearchTermText.Text, new
PlatformParameters(PromptBehavior.Auto, false));
...
What's next
You now have a working Xamarin app that can authenticate users and securely call web APIs by using OAuth 2.0
across five different platforms.
If you haven’t already populated your tenant with users, now is the time to do so.
1. Run your DirectorySearcher app, and then sign in with one of the users.
2. Search for other users based on their UPN.
ADAL makes it easy to incorporate common identity features into the app. It takes care of all the dirty work for
you, such as cache management, OAuth protocol support, presenting the user with a login UI, and refreshing
expired tokens. You need to know only a single API call, authContext.AcquireToken*(…) .
For reference, download the completed sample (without your configuration values).
You can now move on to additional identity scenarios. For example, try Secure a .NET Web API with Azure AD.
Additional resources
The Azure AD developer's guide
Azure AD samples on GitHub
CloudIdentity.com
Get security updates for our products
We encourage you to get notifications of when security incidents occur by visiting the TechCenter page for
Microsoft technical security notifications and subscribing to security advisory alerts.
Integrate Azure AD with an Apache Cordova app
2/14/2017 • 11 min to read • Edit Online
NOTE
This article is part of the Azure Active Directory developer's guide.
You can use Apache Cordova to develop HTML5/JavaScript applications that can run on mobile devices as fullfledged native applications. With Azure Active Directory (Azure AD), you can add enterprise-grade authentication
capabilities to your Cordova applications.
A Cordova plug-in wraps Azure AD native SDKs on iOS, Android, Windows Store, and Windows Phone. By using
that plug-in, you can enhance your application to support sign-in with your users' Windows Server Active
Directory accounts, gain access to Office 365 and Azure APIs, and even help protect calls to your own custom web
API.
In this tutorial, we'll use the Apache Cordova plug-in for Active Directory Authentication Library (ADAL) to
improve a simple app by adding the following features:
With just a few lines of code, authenticate a user and obtain a token.
Use that token to invoke the Graph API to query that directory and display the results.
Use the ADAL token cache to minimize authentication prompts for the user.
To make those improvements, you need to:
1.
2.
3.
4.
Register an application with Azure AD.
Add code to your app to request tokens.
Add code to use the token for querying the Graph API and display results.
Create the Cordova deployment project with all the platforms you want to target, add the Cordova ADAL plugin, and test the solution in emulators.
Prerequisites
To complete this tutorial, you need:
An Azure AD tenant where you have an account with app development rights.
A development environment that's configured to use Apache Cordova.
If you have both already set up, proceed directly to step 1.
If you don't have an Azure AD tenant, use the instructions on how to get one.
If you don't have Apache Cordova set up on your machine, install the following:
Git
Node.js
Cordova CLI (can be easily installed via NPM package manager:
npm install -g cordova
The preceding installations should work both on the PC and on the Mac.
Each target platform has different prerequisites:
)
To build and run an app for Windows Tablet/PC or Windows Phone:
Install Visual Studio 2013 for Windows with Update 2 or later (Express or another version) or Visual
Studio 2015.
To build and run an app for iOS:
Install Xcode 6.x or later. Download it from the Apple Developer site or the Mac App Store.
Install ios-sim. You can use it to start iOS apps in iOS Simulator from the command line. (You can easily
install it via the terminal: npm install -g ios-sim .)
To build and run an app for Android:
Install Java Development Kit (JDK) 7 or later. Make sure JAVA_HOME (environment variable) is correctly
set according to the JDK installation path (for example, C:\Program Files\Java\jdk1.7.0_75).
Install Android SDK and add the <android-sdk-location>\tools location (for example,
C:\tools\Android\android-sdk\tools) to your PATH environment variable.
Open Android SDK Manager (for example, via the terminal: android ) and install:
Android 5.0.1 (API 21) platform SDK
Android SDK Build Tools version 19.1.0 or later
Android Support Repository (Extras)
The Android SDK doesn't provide any default emulator instance. Create one by running android avd from
the terminal and then selecting Create, if you want to run the Android app on an emulator. We
recommend an API level of 19 or higher. For more information about the Android emulator and creation
options, see AVD Manager on the Android site.
Step 1: Register an application with Azure AD
This step is optional. This tutorial provides pre-provisioned values that you can use to see the sample in action
without doing any provisioning in your own tenant. However, we recommend that you do perform this step and
become familiar with the process, because it will be required when you create your own applications.
Azure AD issues tokens to only known applications. Before you can use Azure AD from your app, you need to
create an entry for it in your tenant. To register a new application in your tenant:
1. Sign in to the Azure portal.
2. On the top bar, click your account. In the Directory list, choose the Azure AD tenant where you want to
register your application.
3. Click More Services in the left pane, and then select Azure Active Directory.
4. Click App registrations, and then select Add.
5. Follow the prompts and create a Native Client Application. (Although Cordova apps are HTML based, we're
creating a native client application here. The Native Client Application option must be selected, or the
application won't work.)
Name describes your application to users.
Redirect URI is the URI that's used to return tokens to your app. Enter
http://MyDirectorySearcherApp.
After you finish registration, Azure AD assigns a unique application ID to your app. You’ll need this value in the
next sections. You can find it on the application tab of the newly created app.
To run
DirSearchClient Sample
, grant the newly created app permission to query the Azure AD Graph API:
1. From the Settings page, select Required Permissions, and then select Add.
2. For the Azure Active Directory application, select Microsoft Graph as the API and add the Access the
directory as the signed-in user permission under Delegated Permissions. This enables your application to
query the Graph API for users.
Step 2: Clone the sample app repository
From your shell or command line, type the following command:
git clone -b skeleton https://github.com/AzureADQuickStarts/NativeClient-MultiTarget-Cordova.git
Step 3: Create the Cordova app
There are multiple ways to create Cordova applications. In this tutorial, we'll use the Cordova command-line
interface (CLI).
1. From your shell or command line, type the following command:
cordova create DirSearchClient
That command creates the folder structure and scaffolding for the Cordova project.
2. Move to the new DirSearchClient folder:
cd .\DirSearchClient
3. Copy the content of the starter project in the www subfolder by using a file manager or the following
command in your shell:
Windows: xcopy ..\NativeClient-MultiTarget-Cordova\DirSearchClient www
Mac: cp -r ../NativeClient-MultiTarget-Cordova/DirSearchClient/* www
4. Add the whitelist plug-in. This is necessary for invoking the Graph API.
/E /Y
cordova plugin add cordova-plugin-whitelist
5. Add all the platforms that you want to support. To have a working sample, you need to execute at least one
of the following commands. Note that you won't be able to emulate iOS on Windows or emulate Windows
on a Mac.
cordova platform add android
cordova platform add ios
cordova platform add windows
6. Add the ADAL for Cordova plug-in to your project:
cordova plugin add cordova-plugin-ms-adal
Step 4: Add code to authenticate users and obtain tokens from Azure
AD
The application that you're developing in this tutorial will provide a simple directory search feature. The user can
then type the alias of any user in the directory and visualize some basic attributes. The starter project contains the
definition of the basic user interface of the app (in www/index.html) and the scaffolding that wires up basic app
event cycles, user interface bindings, and results display logic (in www/js/index.js). The only task left for you is to
add the logic that implements identity tasks.
The first thing you need to do in your code is introduce the protocol values that Azure AD uses for identifying
your app and the resources that you target. Those values will be used to construct the token requests later on.
Insert the following snippet at the top of the index.js file:
var authority = "https://login.windows.net/common",
redirectUri = "http://MyDirectorySearcherApp",
resourceUri = "https://graph.windows.net",
clientId = "a5d92493-ae5a-4a9f-bcbf-9f1d354067d3",
graphApiVersion = "2013-11-08";
The redirectUri and clientId values should match the values that describe your app in Azure AD. You can find
those from the Configure tab in the Azure portal, as described in step 1 earlier in this tutorial.
NOTE
If you opted for not registering a new app in your own tenant, you can simply paste the preconfigured values as is. You can
then see the sample running, though you should always create your own entry for your apps that are meant for
production.
Next, add the token request code. Insert the following snippet between the
search
and
renderData
definitions:
// Shows the user authentication dialog box if required
authenticate: function (authCompletedCallback) {
app.context = new Microsoft.ADAL.AuthenticationContext(authority);
app.context.tokenCache.readItems().then(function (items) {
if (items.length > 0) {
authority = items[0].authority;
app.context = new Microsoft.ADAL.AuthenticationContext(authority);
}
// Attempt to authorize the user silently
app.context.acquireTokenSilentAsync(resourceUri, clientId)
.then(authCompletedCallback, function () {
// We require user credentials, so this triggers the authentication dialog box
app.context.acquireTokenAsync(resourceUri, clientId, redirectUri)
.then(authCompletedCallback, function (err) {
app.error("Failed to authenticate: " + err);
});
});
});
},
Let's examine that function by breaking it down in its two main parts. This sample is designed to work with any
tenant, as opposed to being tied to a particular one. It uses the "/common" endpoint, which allows the user to
enter any account at authentication time and directs the request to the tenant where it belongs.
This first part of the method inspects the ADAL cache to see if a token is already stored. If so, the method uses the
tenants where the token came from for reinitializing ADAL. This is necessary to avoid extra prompts, because the
use of "/common" always results in asking the user to enter a new account.
app.context = new Microsoft.ADAL.AuthenticationContext(authority);
app.context.tokenCache.readItems().then(function (items) {
if (items.length > 0) {
authority = items[0].authority;
app.context = new Microsoft.ADAL.AuthenticationContext(authority);
}
The second part of the method performs the proper token request. The acquireTokenSilentAsync method asks
ADAL to return a token for the specified resource without showing any UX. That can happen if the cache already
has a suitable access token stored, or if a refresh token can be used to get a new access token without showing
any prompt. If that attempt fails, we fall back on acquireTokenAsync --which will visibly prompt the user to
authenticate.
// Attempt to authorize the user silently
app.context.acquireTokenSilentAsync(resourceUri, clientId)
.then(authCompletedCallback, function () {
// We require user credentials, so this triggers the authentication dialog box
app.context.acquireTokenAsync(resourceUri, clientId, redirectUri)
.then(authCompletedCallback, function (err) {
app.error("Failed to authenticate: " + err);
});
});
Now that we have the token, we can finally invoke the Graph API and perform the search query that we want.
Insert the following snippet below the authenticate definition:
// Makes an API call to receive the user list
requestData: function (authResult, searchText) {
var req = new XMLHttpRequest();
var url = resourceUri + "/" + authResult.tenantId + "/users?api-version=" + graphApiVersion;
url = searchText ? url + "&$filter=mailNickname eq '" + searchText + "'" : url + "&$top=10";
req.open("GET", url, true);
req.setRequestHeader('Authorization', 'Bearer ' + authResult.accessToken);
req.onload = function(e) {
if (e.target.status >= 200 && e.target.status < 300) {
app.renderData(JSON.parse(e.target.response));
return;
}
app.error('Data request failed: ' + e.target.response);
};
req.onerror = function(e) {
app.error('Data request failed: ' + e.error);
}
req.send();
},
The starting-point files supplied a simple UX for entering a user's alias in a text box. This method uses that value
to construct a query, combine it with the access token, send it to Microsoft Graph, and parse the results. The
renderData method, already present in the starting-point file, takes care of visualizing the results.
Step 5: Run the app
Your app is finally ready to run. Operating it is simple: when the app starts, enter the alias of the user you want to
look up, and then click the button. You're prompted for authentication. Upon successful authentication and
successful search, the attributes of the searched user are displayed.
Subsequent runs will perform the search without showing any prompt, thanks to the presence of the previously
acquired token in cache.
The concrete steps for running the app vary by platform.
Windows 10
Tablet/PC: cordova
run windows --archs=x64 -- --appx=uap
Mobile (requires a Windows 10 Mobile device connected to a PC):
cordova run windows --archs=arm -- --appx=uap --phone
NOTE
During the first run, you might be asked to sign in for a developer license. For more information, see Developer license.
Windows 8.1 Tablet/PC
cordova run windows
NOTE
During the first run, you might be asked to sign in for a developer license. For more information, see Developer license.
Windows Phone 8.1
To run on a connected device:
cordova run windows --device -- --phone
To run on the default emulator:
Use
cordova emulate windows -- --phone
to see all available targets and
cordova run windows --target=<target_name> -- --phone to run the application on a specific device or emulator
(for example, cordova run windows --target="Emulator 8.1 720P 4.7 inch" -- --phone ).
cordova run windows --list -- --phone
Android
To run on a connected device:
cordova run android --device
To run on the default emulator:
cordova emulate android
Make sure you've created an emulator instance by using AVD Manager, as described earlier in the "Prerequisites"
section.
Use cordova run android --list to see all available targets and cordova run android --target=<target_name> to
run the application on a specific device or emulator (for example, cordova run android --target="Nexus4_emulator"
).
iOS
To run on a connected device:
cordova run ios --device
To run on the default emulator:
cordova emulate ios
NOTE
Make sure you have the
section.
ios-sim
package installed to run on the emulator. For more information, see the "Prerequisites"
Use `cordova run ios --list` to see all available targets and `cordova run ios --target=<target_name>` to run
the application on specific device or emulator (for example, `cordova run android --target="iPhone-6"`).
Use `cordova run --help` to see additional build and run options.
Next steps
For reference, the completed sample (without your configuration values) is available in GitHub.
You can now move on to more advanced (and more interesting) scenarios. You might want to try: Secure a
Node.js Web API with Azure AD.
Additional resources
The Azure AD developer's guide
Azure AD samples on GitHub
CloudIdentity.com
Get security updates for our products
We encourage you to get notifications of when security incidents occur by visiting the TechCenter page for
Microsoft technical security notifications and subscribing to security advisory alerts.
Authorize access to web applications using OAuth 2.0
and Azure Active Directory
2/13/2017 • 20 min to read • Edit Online
Azure Active Directory (Azure AD) uses OAuth 2.0 to enable you to authorize access to web applications and web
APIs in your Azure AD tenant. This guide is language independent, and describes how to send and receive HTTP
messages without using any of our open-source libraries.
The OAuth 2.0 authorization code flow is described in section 4.1 of the OAuth 2.0 specification. It is used to
perform authentication and authorization in most application types, including web apps and natively installed apps.
Register your application with your AD tenant
First, you will need to register your application with your Azure Active Directory (Azure AD) tenant. This will give
you an Application ID for your application, as well as enable it to receive tokens.
Sign in to the Azure Portal.
Choose your Azure AD tenant by clicking on your account in the top right corner of the page.
In the left hand navigation pane, click on Azure Active Directory.
Click on App Registrations and click on Add.
Follow the prompts and create a new application. It doesn't matter if it is a web application or a native
application for this tutorial, but if you'd like specific examples for web applications or native applications, check
out our quickstarts.
For Web Applications, provide the Sign-On URL which is the base URL of your app, where users can sign
in e.g http://localhost:12345 .
For Native Applications, provide a Redirect URI, which Azure AD will use to return token responses. Enter
a value specific to your application, .e.g http://MyFirstAADApp
Once you've completed registration, Azure AD will assign your application a unique client identifier, the
Application ID. You will need this value in the next sections, so copy it from the application page.
OAuth 2.0 authorization flow
At a high level, the entire authorization flow for an application looks a bit like this:
Request an authorization code
The authorization code flow begins with the client directing the user to the /authorize endpoint. In this request, the
client indicates the permissions it needs to acquire from the user. You can get the OAuth 2.0 endpoints from your
application's page in Azure Classic Portal, in the View Endpoints button in the bottom drawer.
// Line breaks for legibility only
https://login.microsoftonline.com/{tenant}/oauth2/authorize?
client_id=6731de76-14a6-49ae-97bc-6eba6914391e
&response_type=code
&redirect_uri=http%3A%2F%2Flocalhost%2Fmyapp%2F
&response_mode=query
&resource=https%3A%2F%2Fservice.contoso.com%2F
&state=12345
PARAMETER
DESCRIPTION
PARAMETER
DESCRIPTION
tenant
required
The {tenant} value in the path of the
request can be used to control who can
sign into the application. The allowed
values are tenant identifiers, for
example,
8eaef023-2b34-4da1-9baa-8bc8c9d6a490 or
contoso.onmicrosoft.com or common for
tenant-independent tokens
client_id
required
The Application Id assigned to your app
when you registered it with Azure AD.
You can find this in the Azure Portal.
Click Active Directory, click the
directory, choose the application, and
click Configure
response_type
required
Must include
code flow.
redirect_uri
recommended
The redirect_uri of your app, where
authentication responses can be sent
and received by your app. It must
exactly match one of the redirect_uris
you registered in the portal, except it
must be url encoded. For native &
mobile apps, you should use the default
value of urn:ietf:wg:oauth:2.0:oob .
response_mode
recommended
Specifies the method that should be
used to send the resulting token back
to your app. Can be query or
form_post .
state
recommended
A value included in the request that is
also returned in the token response. A
randomly generated unique value is
typically used for preventing cross-site
request forgery attacks. The state is also
used to encode information about the
user's state in the app before the
authentication request occurred, such as
the page or view they were on.
resource
optional
The App ID URI of the web API (secured
resource). To find the App ID URI of the
web API, in the Azure Portal, click
Active Directory, click the directory,
click the application and then click
Configure.
code
for the authorization
PARAMETER
prompt
DESCRIPTION
optional
Indicate the type of user interaction that
is required.
Valid values are:
login: The user should be prompted
to reauthenticate.
consent: User consent has been
granted, but needs to be updated.
The user should be prompted to
consent.
admin_consent: An administrator
should be prompted to consent on
behalf of all users in their
organization
login_hint
optional
Can be used to pre-fill the
username/email address field of the
sign-in page for the user, if you know
their username ahead of time. Often
apps use this parameter during
reauthentication, having already
extracted the username from a previous
sign-in using the preferred_username
claim.
domain_hint
optional
Provides a hint about the tenant or
domain that the user should use to sign
in. The value of the domain_hint is a
registered domain for the tenant. If the
tenant is federated to an on-premises
directory, AAD redirects to the specified
tenant federation server.
NOTE
If the user is part of an organization, an administrator of the organization can consent or decline on the user's behalf, or
permit the user to consent. The user is given the option to consent only when the administrator permits it.
At this point, the user is asked to enter their credentials and consent to the permissions indicated in the scope
query parameter. Once the user authenticates and grants consent, Azure AD sends a response to your app at the
redirect_uri address in your request.
Successful response
A successful response could look like this:
GET HTTP/1.1 302 Found
Location: http://localhost/myapp/?code=
AwABAAAAvPM1KaPlrEqdFSBzjqfTGBCmLdgfSTLEMPGYuNHSUYBrqqf_ZT_p5uEAEJJ_nZ3UmphWygRNy2C3jJ239gV_DBnZ2syeg95Ki374WHUP-i3yIhv5i-7KU2CEoPXwURQp6IVYMwDjAOzn7C3JCu5wpngXmbZKtJdWmiBzHpcO2aICJPu1KvJrDLDP20chJBXzVYJtkfjviLNNW7l7Y3ydcHDsBRKZc3GuMQanmcghXPyoDg41g8Xbw
PudVh7uCmUponBQpIhbuffFP_tbV8SNzsPoFz9CLpBCZagJVXeqWoYMPe2dSsPiLO9Alf_YIe5zpizY4C3aLw5g9at35eZTfNd0gBRpR5ojkMIcZZ6IgAA&session_state=7B29111D-C220-4263-99AB-6F6E135D75EF&state=D79E5777702E-4260-9A62-37F75FF22CCE
PARAMETER
DESCRIPTION
admin_consent
The value is True if an administrator consented to a consent
request prompt.
code
The authorization code that the application requested. The
application can use the authorization code to request an
access token for the target resource.
session_state
A unique value that identifies the current user session. This
value is a GUID, but should be treated as an opaque value
that is passed without examination.
state
If a state parameter is included in the request, the same value
should appear in the response. It's a good practice for the
application to verify that the state values in the request and
response are identical before using the response. This helps to
detect Cross-Site Request Forgery (CSRF) attacks against the
client.
Error response
Error responses may also be sent to the
redirect_uri
so that the application can handle them appropriately.
GET http://localhost:12345/?
error=access_denied
&error_description=the+user+canceled+the+authentication
PARAMETER
DESCRIPTION
error
An error code value defined in Section 5.2 of the OAuth 2.0
Authorization Framework. The next table describes the error
codes that Azure AD returns.
error_description
A more detailed description of the error. This message is not
intended to be end-user friendly.
state
The state value is a randomly generated non-reused value that
is sent in the request and returned in the response to prevent
cross-site request forgery (CSRF) attacks.
Error codes for authorization endpoint errors
The following table describes the various error codes that can be returned in the
response.
error
parameter of the error
ERROR CODE
DESCRIPTION
CLIENT ACTION
invalid_request
Protocol error, such as a missing
required parameter.
Fix and resubmit the request. This is a
development error, and is typically
caught during initial testing.
unauthorized_client
The client application is not permitted to
request an authorization code.
This usually occurs when the client
application is not registered in Azure AD
or is not added to the user's Azure AD
tenant. The application can prompt the
user with instruction for installing the
application and adding it to Azure AD.
ERROR CODE
DESCRIPTION
CLIENT ACTION
access_denied
Resource owner denied consent
The client application can notify the user
that it cannot proceed unless the user
consents.
unsupported_response_type
The authorization server does not
support the response type in the
request.
Fix and resubmit the request. This is a
development error, and is typically
caught during initial testing.
server_error
The server encountered an unexpected
error.
Retry the request. These errors can
result from temporary conditions. The
client application might explain to the
user that its response is delayed due to
a temporary error.
temporarily_unavailable
The server is temporarily too busy to
handle the request.
Retry the request. The client application
might explain to the user that its
response is delayed due to a temporary
condition.
invalid_resource
The target resource is invalid because it
does not exist, Azure AD cannot find it,
or it is not correctly configured.
This indicates the resource, if it exists,
has not been configured in the tenant.
The application can prompt the user
with instruction for installing the
application and adding it to Azure AD.
Use the authorization code to request an access token
Now that you've acquired an authorization code and have been granted permission by the user, you can redeem
the code for an access token to the desired resource, by sending a POST request to the /token endpoint:
// Line breaks for legibility only
POST /{tenant}/oauth2/token HTTP/1.1
Host: https://login.microsoftonline.com
Content-Type: application/x-www-form-urlencoded
grant_type=authorization_code
&client_id=2d4d11a2-f814-46a7-890a-274a72a7309e
&code=AwABAAAAvPM1KaPlrEqdFSBzjqfTGBCmLdgfSTLEMPGYuNHSUYBrqqf_ZT_p5uEAEJJ_nZ3UmphWygRNy2C3jJ239gV_DBnZ2syeg95Ki
-374WHUP-i3yIhv5i-7KU2CEoPXwURQp6IVYMwDjAOzn7C3JCu5wpngXmbZKtJdWmiBzHpcO2aICJPu1KvJrDLDP20chJBXzVYJtkfjviLNNW7l7Y3ydcHDsBRKZc3GuMQanmcghXPyoDg41g8Xbw
PudVh7uCmUponBQpIhbuffFP_tbV8SNzsPoFz9CLpBCZagJVXeqWoYMPe2dSsPiLO9Alf_YIe5zpizY4C3aLw5g9at35eZTfNd0gBRpR5ojkMIcZZ6IgAA
&redirect_uri=https%3A%2F%2Flocalhost%2Fmyapp%2F
&resource=https%3A%2F%2Fservice.contoso.com%2F
&client_secret=p@ssw0rd
//NOTE: client_secret only required for web apps
PARAMETER
DESCRIPTION
PARAMETER
DESCRIPTION
tenant
required
The {tenant} value in the path of the
request can be used to control who can
sign into the application. The allowed
values are tenant identifiers, for
example,
8eaef023-2b34-4da1-9baa-8bc8c9d6a490 or
contoso.onmicrosoft.com or common for
tenant-independent tokens
client_id
required
The Application Id assigned to your app
when you registered it with Azure AD.
You can find this in the Azure Classic
Portal. Click Active Directory, click the
directory, choose the application, and
click Configure
grant_type
required
Must be authorization_code for the
authorization code flow.
code
required
The authorization_code that you acquired
in the previous section
redirect_uri
required
The same redirect_uri value that was
used to acquire the authorization_code .
client_secret
required for web apps
The application secret that you created
in the app registration portal for your
app. It should not be used in a native
app, because client_secrets cannot be
reliably stored on devices. It is required
for web apps and web APIs, which have
the ability to store the client_secret
securely on the server side.
resource
required if specified in authorization
code request, else optional
The App ID URI of the web API (secured
resource).
To find the App ID URI, in the Azure Management Portal, click Active Directory, click the directory, click the
application, and then click Configure.
Successful response
Azure AD returns an access token upon a successful response. To minimize network calls from the client application
and their associated latency, the client application should cache access tokens for the token lifetime that is specified
in the OAuth 2.0 response. To determine the token lifetime, use either the expires_in or expires_on parameter
values.
If a web API resource returns an invalid_token error code, this might indicate that the resource has determined
that the token is expired. If the client and resource clock times are different (known as a "time skew"), the resource
might consider the token to be expired before the token is cleared from the client cache. If this occurs, clear the
token from the cache, even if it is still within its calculated lifetime.
A successful response could look like this:
{
"access_token": "
eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik5HVEZ2ZEstZnl0aEV1THdqcHdBSk9NOW4tQSJ9.eyJhdWQiOiJodHRwczovL3Nlcn
ZpY2UuY29udG9zby5jb20vIiwiaXNzIjoiaHR0cHM6Ly9zdHMud2luZG93cy5uZXQvN2ZlODE0NDctZGE1Ny00Mzg1LWJlY2ItNmRlNTdmMjE0N
zdlLyIsImlhdCI6MTM4ODQ0MDg2MywibmJmIjoxMzg4NDQwODYzLCJleHAiOjEzODg0NDQ3NjMsInZlciI6IjEuMCIsInRpZCI6IjdmZTgxNDQ3
LWRhNTctNDM4NS1iZWNiLTZkZTU3ZjIxNDc3ZSIsIm9pZCI6IjY4Mzg5YWUyLTYyZmEtNGIxOC05MWZlLTUzZGQxMDlkNzRmNSIsInVwbiI6ImZ
yYW5rbUBjb250b3NvLmNvbSIsInVuaXF1ZV9uYW1lIjoiZnJhbmttQGNvbnRvc28uY29tIiwic3ViIjoiZGVOcUlqOUlPRTlQV0pXYkhzZnRYdD
JFYWJQVmwwQ2o4UUFtZWZSTFY5OCIsImZhbWlseV9uYW1lIjoiTWlsbGVyIiwiZ2l2ZW5fbmFtZSI6IkZyYW5rIiwiYXBwaWQiOiIyZDRkMTFhM
i1mODE0LTQ2YTctODkwYS0yNzRhNzJhNzMwOWUiLCJhcHBpZGFjciI6IjAiLCJzY3AiOiJ1c2VyX2ltcGVyc29uYXRpb24iLCJhY3IiOiIxIn0.
JZw8jC0gptZxVC7l5sFkdnJgP3_tRjeQEPgUn28XctVe3QqmheLZw7QVZDPCyGycDWBaqy7FLpSekET_BftDkewRhyHk9FW_KeEz0ch2c3i08NGNDbr6XYGVayNuS
esYk5Aw_p3ICRlUV1bqEwk-Jkzs9EEkQg4hbefqJS6yS1HoV_2EsEhpd_wCQpxK89WPs3hLYZETRJtG5kvCCEOvSHXmDE6eTHGTnEgsIk-UlPe275Dvou4gEAwLofhLDQbMSjnlV5VLsjimNBVcSRFShoxmQwBJR_b2011Y5IuD6St5zPnzruBbZYkGNurQK63TJPWmRd3mbJsGM0mf3CUQ",
"token_type": "Bearer",
"expires_in": "3600",
"expires_on": "1388444763",
"resource": "https://service.contoso.com/",
"refresh_token": "AwABAAAAvPM1KaPlrEqdFSBzjqfTGAMxZGUTdM0t4B4rTfgV29ghDOHRc2BC_hHeJaJICqjZ3mY2b_YNqmf9SoAylD1PycGCB90xzZeEDg6oBzOIPfYsbDWNf621pKo2Q3GGTHYlmNfwocOlrxK69hkha2CF12azM_NYhgO668yfcUl4VBbiSHZyd1NVZG5QTIOcbObu3qnLutbpadZGAxqjIbMkQ2bQS09fTrjMBtDE3D6kSMIodpCecoANo
n9b0LATkpitimVCrl-NyfN3oyG4ZCWu18M9-vEou4Sq-1oMDzExgAf61noxzkNiaTecM-Ve5cq6wHqYQjfV9DOz4lbceuYCAA",
"scope": "https%3A%2F%2Fgraph.microsoft.com%2Fmail.read",
"id_token": "
eyJ0eXAiOiJKV1QiLCJhbGciOiJub25lIn0.eyJhdWQiOiIyZDRkMTFhMi1mODE0LTQ2YTctODkwYS0yNzRhNzJhNzMwOWUiLCJpc3MiOiJodHR
wczovL3N0cy53aW5kb3dzLm5ldC83ZmU4MTQ0Ny1kYTU3LTQzODUtYmVjYi02ZGU1N2YyMTQ3N2UvIiwiaWF0IjoxMzg4NDQwODYzLCJuYmYiOj
EzODg0NDA4NjMsImV4cCI6MTM4ODQ0NDc2MywidmVyIjoiMS4wIiwidGlkIjoiN2ZlODE0NDctZGE1Ny00Mzg1LWJlY2ItNmRlNTdmMjE0NzdlI
iwib2lkIjoiNjgzODlhZTItNjJmYS00YjE4LTkxZmUtNTNkZDEwOWQ3NGY1IiwidXBuIjoiZnJhbmttQGNvbnRvc28uY29tIiwidW5pcXVlX25h
bWUiOiJmcmFua21AY29udG9zby5jb20iLCJzdWIiOiJKV3ZZZENXUGhobHBTMVpzZjd5WVV4U2hVd3RVbTV5elBtd18talgzZkhZIiwiZmFtaWx
5X25hbWUiOiJNaWxsZXIiLCJnaXZlbl9uYW1lIjoiRnJhbmsifQ.”
}
PARAMETER
DESCRIPTION
access_token
The requested access token. The app can use this token to
authenticate to the secured resource, such as a web API.
token_type
Indicates the token type value. The only type that Azure AD
supports is Bearer. For more information about Bearer tokens,
see OAuth2.0 Authorization Framework: Bearer Token Usage
(RFC 6750)
expires_in
How long the access token is valid (in seconds).
expires_on
The time when the access token expires. The date is
represented as the number of seconds from 1970-0101T0:0:0Z UTC until the expiration time. This value is used to
determine the lifetime of cached tokens.
resource
The App ID URI of the web API (secured resource).
scope
Impersonation permissions granted to the client application.
The default permission is user_impersonation . The owner of the
secured resource can register additional values in Azure AD.
refresh_token
An OAuth 2.0 refresh token. The app can use this token to
acquire additional access tokens after the current access token
expires. Refresh tokens are long-lived, and can be used to
retain access to resources for extended periods of time.
PARAMETER
DESCRIPTION
id_token
An unsigned JSON Web Token (JWT). The app can base64Url
decode the segments of this token to request information
about the user who signed in. The app can cache the values
and display them, but it should not rely on them for any
authorization or security boundaries.
JWT Token Claims
The JWT token in the value of the
id_token
parameter can be decoded into the following claims:
{
"typ": "JWT",
"alg": "none"
}.
{
"aud": "2d4d11a2-f814-46a7-890a-274a72a7309e",
"iss": "https://sts.windows.net/7fe81447-da57-4385-becb-6de57f21477e/",
"iat": 1388440863,
"nbf": 1388440863,
"exp": 1388444763,
"ver": "1.0",
"tid": "7fe81447-da57-4385-becb-6de57f21477e",
"oid": "68389ae2-62fa-4b18-91fe-53dd109d74f5",
"upn": "[email protected]",
"unique_name": "[email protected]",
"sub": "JWvYdCWPhhlpS1Zsf7yYUxShUwtUm5yzPmw_-jX3fHY",
"family_name": "Miller",
"given_name": "Frank"
}.
For more information about JSON web tokens, see the JWT IETF draft specification. For more information about the
token types and claims, read Supported Token and Claim Types
The
id_token
parameter includes the following claim types:
CLAIM TYPE
DESCRIPTION
aud
Audience of the token. When the token is issued to a client
application, the audience is the client_id of the client.
exp
Expiration time. The time when the token expires. For the
token to be valid, the current date/time must be less than or
equal to the exp value. The time is represented as the
number of seconds from January 1, 1970 (1970-0101T0:0:0Z) UTC until the time the token was issued.
family_name
User’s last name or surname. The application can display this
value.
given_name
User’s first name. The application can display this value.
iat
Issued at time. The time when the JWT was issued. The time is
represented as the number of seconds from January 1, 1970
(1970-01-01T0:0:0Z) UTC until the time the token was issued.
iss
Identifies the token issuer
CLAIM TYPE
DESCRIPTION
nbf
Not before time. The time when the token becomes effective.
For the token to be valid, the current date/time must be
greater than or equal to the Nbf value. The time is represented
as the number of seconds from January 1, 1970 (1970-0101T0:0:0Z) UTC until the time the token was issued.
oid
Object identifier (ID) of the user object in Azure AD.
sub
Token subject identifier. This is a persistent and immutable
identifier for the user that the token describes. Use this value
in caching logic.
tid
Tenant identifier (ID) of the Azure AD tenant that issued the
token.
unique_name
A unique identifier for that can be displayed to the user. This is
usually a user principal name (UPN).
upn
User principal name of the user.
ver
Version. The version of the JWT token, typically 1.0.
Error response
The token issuance endpoint errors are HTTP error codes, because the client calls the token issuance endpoint
directly. In addition to the HTTP status code, the Azure AD token issuance endpoint also returns a JSON document
with objects that describe the error.
A sample error response could look like this:
{
"error": "invalid_grant",
"error_description": "AADSTS70002: Error validating credentials. AADSTS70008: The provided authorization code
or refresh token is expired. Send a new interactive authorization request for this user and resource.\r\nTrace
ID: 3939d04c-d7ba-42bf-9cb7-1e5854cdce9e\r\nCorrelation ID: a8125194-2dc8-4078-90ba-7b6592a7f231\r\nTimestamp:
2016-04-11 18:00:12Z",
"error_codes": [
70002,
70008
],
"timestamp": "2016-04-11 18:00:12Z",
"trace_id": "3939d04c-d7ba-42bf-9cb7-1e5854cdce9e",
"correlation_id": "a8125194-2dc8-4078-90ba-7b6592a7f231"
}
PARAMETER
DESCRIPTION
error
An error code string that can be used to classify types of
errors that occur, and can be used to react to errors.
error_description
A specific error message that can help a developer identify the
root cause of an authentication error.
error_codes
A list of STS-specific error codes that can help in diagnostics.
PARAMETER
DESCRIPTION
timestamp
The time at which the error occurred.
trace_id
A unique identifier for the request that can help in diagnostics.
correlation_id
A unique identifier for the request that can help in diagnostics
across components.
HTTP status codes
The following table lists the HTTP status codes that the token issuance endpoint returns. In some cases, the error
code is sufficient to describe the response, but if there are errors, you need to parse the accompanying JSON
document and examine its error code.
HTTP CODE
DESCRIPTION
400
Default HTTP code. Used in most cases and is typically due to
a malformed request. Fix and resubmit the request.
401
Authentication failed. For example, the request is missing the
client_secret parameter.
403
Authorization failed. For example, the user does not have
permission to access the resource.
500
An internal error has occurred at the service. Retry the request.
Error codes for token endpoint errors
ERROR CODE
DESCRIPTION
CLIENT ACTION
invalid_request
Protocol error, such as a missing
required parameter.
Fix and resubmit the request
invalid_grant
The authorization code is invalid or has
expired.
Try a new request to the
endpoint
unauthorized_client
The authenticated client is not
authorized to use this authorization
grant type.
This usually occurs when the client
application is not registered in Azure AD
or is not added to the user's Azure AD
tenant. The application can prompt the
user with instruction for installing the
application and adding it to Azure AD.
invalid_client
Client authentication failed.
The client credentials are not valid. To
fix, the application administrator
updates the credentials.
unsupported_grant_type
The authorization server does not
support the authorization grant type.
Change the grant type in the request.
This type of error should occur only
during development and be detected
during initial testing.
/authorize
ERROR CODE
DESCRIPTION
CLIENT ACTION
invalid_resource
The target resource is invalid because it
does not exist, Azure AD cannot find it,
or it is not correctly configured.
This indicates the resource, if it exists,
has not been configured in the tenant.
The application can prompt the user
with instruction for installing the
application and adding it to Azure AD.
interaction_required
The request requires user interaction.
For example, an additional
authentication step is required.
Retry the request with the same
resource.
temporarily_unavailable
The server is temporarily too busy to
handle the request.
Retry the request. The client application
might explain to the user that its
response is delayed due to a temporary
condition.
Use the access token to access the resource
Now that you've successfully acquired an access_token , you can use the token in requests to Web APIs, by
including it in the Authorization header. The RFC 6750 specification explains how to use bearer tokens in HTTP
requests to access protected resources.
Sample request
GET /data HTTP/1.1
Host: service.contoso.com
Authorization: Bearer
eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik5HVEZ2ZEstZnl0aEV1THdqcHdBSk9NOW4tQSJ9.eyJhdWQiOiJodHRwczovL3Nlcn
ZpY2UuY29udG9zby5jb20vIiwiaXNzIjoiaHR0cHM6Ly9zdHMud2luZG93cy5uZXQvN2ZlODE0NDctZGE1Ny00Mzg1LWJlY2ItNmRlNTdmMjE0N
zdlLyIsImlhdCI6MTM4ODQ0MDg2MywibmJmIjoxMzg4NDQwODYzLCJleHAiOjEzODg0NDQ3NjMsInZlciI6IjEuMCIsInRpZCI6IjdmZTgxNDQ3
LWRhNTctNDM4NS1iZWNiLTZkZTU3ZjIxNDc3ZSIsIm9pZCI6IjY4Mzg5YWUyLTYyZmEtNGIxOC05MWZlLTUzZGQxMDlkNzRmNSIsInVwbiI6ImZ
yYW5rbUBjb250b3NvLmNvbSIsInVuaXF1ZV9uYW1lIjoiZnJhbmttQGNvbnRvc28uY29tIiwic3ViIjoiZGVOcUlqOUlPRTlQV0pXYkhzZnRYdD
JFYWJQVmwwQ2o4UUFtZWZSTFY5OCIsImZhbWlseV9uYW1lIjoiTWlsbGVyIiwiZ2l2ZW5fbmFtZSI6IkZyYW5rIiwiYXBwaWQiOiIyZDRkMTFhM
i1mODE0LTQ2YTctODkwYS0yNzRhNzJhNzMwOWUiLCJhcHBpZGFjciI6IjAiLCJzY3AiOiJ1c2VyX2ltcGVyc29uYXRpb24iLCJhY3IiOiIxIn0.
JZw8jC0gptZxVC7l5sFkdnJgP3_tRjeQEPgUn28XctVe3QqmheLZw7QVZDPCyGycDWBaqy7FLpSekET_BftDkewRhyHk9FW_KeEz0ch2c3i08NGNDbr6XYGVayNuS
esYk5Aw_p3ICRlUV1bqEwk-Jkzs9EEkQg4hbefqJS6yS1HoV_2EsEhpd_wCQpxK89WPs3hLYZETRJtG5kvCCEOvSHXmDE6eTHGTnEgsIk-UlPe275Dvou4gEAwLofhLDQbMSjnlV5VLsjimNBVcSRFShoxmQwBJR_b2011Y5IuD6St5zPnzruBbZYkGNurQK63TJPWmRd3mbJsGM0mf3CUQ
Error Response
Secured resources that implement RFC 6750 issue HTTP status codes. If the request does not include authentication
credentials or is missing the token, the response includes an WWW-Authenticate header. When a request fails, the
resource server responds with the HTTP status code and an error code.
The following is an example of an unsuccessful response when the client request does not include the bearer token:
HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer authorization_uri="https://login.window.net/contoso.com/oauth2/authorize",
error="invalid_token", error_description="The access token is missing.",
Error parameters
PARAMETER
DESCRIPTION
PARAMETER
DESCRIPTION
authorization_uri
The URI (physical endpoint) of the authorization server. This
value is also used as a lookup key to get more information
about the server from a discovery endpoint.
The client must validate that the authorization server is
trusted. When the resource is protected by Azure AD, it is
sufficient to verify that the URL begins with
https://login.windows.net or another hostname that Azure
AD supports. A tenant-specific resource should always
return a tenant-specific authorization URI.
error
An error code value defined in Section 5.2 of the OAuth 2.0
Authorization Framework.
error_description
A more detailed description of the error. This message is not
intended to be end-user friendly.
resource_id
Returns the unique identifier of the resource. The client
application can use this identifier as the value of the resource
parameter when it requests a token for the resource.
It is important for the client application to verify this value,
otherwise a malicious service might be able to induce an
elevation-of-privileges attack
The recommended strategy for preventing an attack is to
verify that the resource_id matches the base of the web
API URL that being accessed. For example, if
https://service.contoso.com/data is being accessed, the
resource_id can be htttps://service.contoso.com/. The client
application must reject a resource_id that does not begin
with the base URL unless there is a reliable alternate way
to verify the id.
Bearer scheme error codes
The RFC 6750 specification defines the following errors for resources that use the WWW-Authenticate header and
Bearer scheme in the response.
HTTP STATUS CODE
ERROR CODE
DESCRIPTION
CLIENT ACTION
400
invalid_request
The request is not wellformed. For example, it
might be missing a
parameter or using the same
parameter twice.
Fix the error and retry the
request. This type of error
should occur only during
development and be
detected in initial testing.
401
invalid_token
The access token is missing,
invalid, or is revoked. The
value of the
error_description parameter
provides additional detail.
Request a new token from
the authorization server. If
the new token fails, an
unexpected error has
occurred. Send an error
message to the user and
retry after random delays.
HTTP STATUS CODE
ERROR CODE
DESCRIPTION
CLIENT ACTION
403
insufficient_scope
The access token does not
contain the impersonation
permissions required to
access the resource.
Send a new authorization
request to the authorization
endpoint. If the response
contains the scope
parameter, use the scope
value in the request to the
resource.
403
insufficient_access
The subject of the token
does not have the
permissions that are
required to access the
resource.
Prompt the user to use a
different account or to
request permissions to the
specified resource.
Refreshing the access tokens
Access Tokens are short-lived and must be refreshed after they expire to continue accessing resources. You can
refresh the access_token by submitting another POST request to the /token endpoint, but this time providing the
refresh_token instead of the code .
Refresh tokens do not have specified lifetimes. Typically, the lifetimes of refresh tokens are relatively long. However,
in some cases, refresh tokens expire, are revoked, or lack sufficient privileges for the desired action. Your application
needs to expect and handle errors returned by the token issuance endpoint correctly.
When you receive a response with a refresh token error, discard the current refresh token and request a new
authorization code or access token. In particular, when using a refresh token in the Authorization Code Grant flow, if
you receive a response with the interaction_required or invalid_grant error codes, discard the refresh token and
request a new authorization code.
A sample request to the tenant-specific endpoint (you can also use the common endpoint) to get a new access
token using a refresh token looks like this:
// Line breaks for legibility only
POST /{tenant}/oauth2/token HTTP/1.1
Host: https://login.microsoftonline.com
Content-Type: application/x-www-form-urlencoded
client_id=6731de76-14a6-49ae-97bc-6eba6914391e
&refresh_token=OAAABAAAAiL9Kn2Z27UubvWFPbm0gLWQJVzCTE9UkP3pSx1aXxUjq...
&grant_type=refresh_token
&resource=https%3A%2F%2Fservice.contoso.com%2F
&client_secret=JqQX2PNo9bpM0uEihUPzyrh
// NOTE: Only required for web apps
PARAMETER
DESCRIPTION
access_token
The new access token that was requested.
expires_in
The remaining lifetime of the token in seconds. A typical value
is 3600 (one hour).
expires_on
The date and time on which the token expires. The date is
represented as the number of seconds from 1970-0101T0:0:0Z UTC until the expiration time.
PARAMETER
DESCRIPTION
refresh_token
A new OAuth 2.0 refresh_token that can be used to request
new access tokens when the one in this response expires.
resource
Identifies the secured resource that the access token can be
used to access.
scope
Impersonation permissions granted to the native client
application. The default permission is user_impersonation.
The owner of the target resource can register alternate values
in Azure AD.
token_type
The token type. The only supported value is bearer.
Successful response
A successful token response will look like:
{
"token_type": "Bearer",
"expires_in": "3600",
"expires_on": "1460404526",
"resource": "https://service.contoso.com/",
"access_token":
"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik5HVEZ2ZEstZnl0aEV1THdqcHdBSk9NOW4tQSJ9.eyJhdWQiOiJodHRwczovL3Nlc
nZpY2UuY29udG9zby5jb20vIiwiaXNzIjoiaHR0cHM6Ly9zdHMud2luZG93cy5uZXQvN2ZlODE0NDctZGE1Ny00Mzg1LWJlY2ItNmRlNTdmMjE0
NzdlLyIsImlhdCI6MTM4ODQ0MDg2MywibmJmIjoxMzg4NDQwODYzLCJleHAiOjEzODg0NDQ3NjMsInZlciI6IjEuMCIsInRpZCI6IjdmZTgxNDQ
3LWRhNTctNDM4NS1iZWNiLTZkZTU3ZjIxNDc3ZSIsIm9pZCI6IjY4Mzg5YWUyLTYyZmEtNGIxOC05MWZlLTUzZGQxMDlkNzRmNSIsInVwbiI6Im
ZyYW5rbUBjb250b3NvLmNvbSIsInVuaXF1ZV9uYW1lIjoiZnJhbmttQGNvbnRvc28uY29tIiwic3ViIjoiZGVOcUlqOUlPRTlQV0pXYkhzZnRYd
DJFYWJQVmwwQ2o4UUFtZWZSTFY5OCIsImZhbWlseV9uYW1lIjoiTWlsbGVyIiwiZ2l2ZW5fbmFtZSI6IkZyYW5rIiwiYXBwaWQiOiIyZDRkMTFh
Mi1mODE0LTQ2YTctODkwYS0yNzRhNzJhNzMwOWUiLCJhcHBpZGFjciI6IjAiLCJzY3AiOiJ1c2VyX2ltcGVyc29uYXRpb24iLCJhY3IiOiIxIn0
.JZw8jC0gptZxVC7l5sFkdnJgP3_tRjeQEPgUn28XctVe3QqmheLZw7QVZDPCyGycDWBaqy7FLpSekET_BftDkewRhyHk9FW_KeEz0ch2c3i08NGNDbr6XYGVayNuS
esYk5Aw_p3ICRlUV1bqEwk-Jkzs9EEkQg4hbefqJS6yS1HoV_2EsEhpd_wCQpxK89WPs3hLYZETRJtG5kvCCEOvSHXmDE6eTHGTnEgsIk-UlPe275Dvou4gEAwLofhLDQbMSjnlV5VLsjimNBVcSRFShoxmQwBJR_b2011Y5IuD6St5zPnzruBbZYkGNurQK63TJPWmRd3mbJsGM0mf3CUQ",
"refresh_token": "AwABAAAAv YNqmf9SoAylD1PycGCB90xzZeEDg6oBzOIPfYsbDWNf621pKo2Q3GGTHYlmNfwocOlrxK69hkha2CF12azM_NYhgO668yfcUl4VBbiSHZyd1NVZG5QTIOcbObu3qnLutbpadZGAxqjIbMkQ2bQS09fTrjMBtDE3D6kSMIodpCecoANo
n9b0LATkpitimVCrl PM1KaPlrEqdFSBzjqfTGAMxZGUTdM0t4B4rTfgV29ghDOHRc2BC_hHeJaJICqjZ3mY2b_YNqmf9SoAylD1PycGCB90xzZeEDg6oBzOIPfYsbDWNf621pKo2Q3GGTHYlmNfwocOlrxK69hkha2CF12azM_NYhgO668yfmVCrl-NyfN3oyG4ZCWu18M9-vEou4Sq-1oMDzExgAf61noxzkNiaTecMVe5cq6wHqYQjfV9DOz4lbceuYCAA"
}
Error response
A sample error response could look like this:
{
"error": "invalid_resource",
"error_description": "AADSTS50001: The application named https://foo.microsoft.com/mail.read was not found in
the tenant named 295e01fc-0c56-4ac3-ac57-5d0ed568f872. This can happen if the application has not been
installed by the administrator of the tenant or consented to by any user in the tenant. You might have sent
your authentication request to the wrong tenant.\r\nTrace ID: ef1f89f6-a14f-49de-986861bd4072f0a9\r\nCorrelation ID: b6908274-2c58-4e91-aea9-1f6b9c99347c\r\nTimestamp: 2016-04-11 18:59:01Z",
"error_codes": [
50001
],
"timestamp": "2016-04-11 18:59:01Z",
"trace_id": "ef1f89f6-a14f-49de-9868-61bd4072f0a9",
"correlation_id": "b6908274-2c58-4e91-aea9-1f6b9c99347c"
}
PARAMETER
DESCRIPTION
error
An error code string that can be used to classify types of
errors that occur, and can be used to react to errors.
error_description
A specific error message that can help a developer identify the
root cause of an authentication error.
error_codes
A list of STS-specific error codes that can help in diagnostics.
timestamp
The time at which the error occurred.
trace_id
A unique identifier for the request that can help in diagnostics.
correlation_id
A unique identifier for the request that can help in diagnostics
across components.
For a description of the error codes and the recommended client action, see Error codes for token endpoint errors.
Authentication Scenarios for Azure AD
4/27/2017 • 31 min to read • Edit Online
Azure Active Directory (Azure AD) simplifies authentication for developers by providing identity as a service, with
support for industry-standard protocols such as OAuth 2.0 and OpenID Connect, as well as open source libraries for
different platforms to help you start coding quickly. This document will help you understand the various scenarios
Azure AD supports and will show you how to get started. It’s divided into the following sections:
Basics of Authentication in Azure AD
Claims in Azure AD Security Tokens
Basics of Registering an Application in Azure AD
Application Types and Scenarios
Web Browser to Web Application
Single Page Application (SPA)
Native Application to Web API
Web Application to Web API
Daemon or Server Application to Web API
Basics of Authentication in Azure AD
If you are unfamiliar with basic concepts of authentication in Azure AD, read this section. Otherwise, you may want
to skip down to Application Types and Scenarios.
Let’s consider the most basic scenario where identity is required: a user in a web browser needs to authenticate to a
web application. This scenario is described in greater detail in the Web Browser to Web Application section, but it’s
a useful starting point to illustrate the capabilities of Azure AD and conceptualize how the scenario works. Consider
the following diagram for this scenario:
With the diagram above in mind, here’s what you need to know about its various components:
Azure AD is the identity provider, responsible for verifying the identity of users and applications that exist in an
organization’s directory, and ultimately issuing security tokens upon successful authentication of those users
and applications.
An application that wants to outsource authentication to Azure AD must be registered in Azure AD, which
registers and uniquely identifies the app in the directory.
Developers can use the open source Azure AD authentication libraries to make authentication easy by handling
the protocol details for you. See Azure Active Directory Authentication Libraries for more information.
• Once a user has been authenticated, the application must validate the user’s security token to ensure that
authentication was successful for the intended parties. Developers can use the provided authentication libraries to
handle validation of any token from Azure AD, including JSON Web Tokens (JWT) or SAML 2.0. If you want to
perform validation manually, see the JWT Token Handler documentation.
IMPORTANT
Azure AD uses public key cryptography to sign tokens and verify that they are valid. See Important Information About
Signing Key Rollover in Azure AD for more information on the necessary logic you must have in your application to ensure it’s
always updated with the latest keys.
• The flow of requests and responses for the authentication process is determined by the authentication protocol
that was used, such as OAuth 2.0, OpenID Connect, WS-Federation, or SAML 2.0. These protocols are discussed in
more detail in the Azure Active Directory Authentication Protocols topic and in the sections below.
NOTE
Azure AD supports the OAuth 2.0 and OpenID Connect standards that make extensive use of bearer tokens, including bearer
tokens represented as JWTs. A bearer token is a lightweight security token that grants the “bearer” access to a protected
resource. In this sense, the “bearer” is any party that can present the token. Though a party must first authenticate with Azure
AD to receive the bearer token, if the required steps are not taken to secure the token in transmission and storage, it can be
intercepted and used by an unintended party. While some security tokens have a built-in mechanism for preventing
unauthorized parties from using them, bearer tokens do not have this mechanism and must be transported in a secure
channel such as transport layer security (HTTPS). If a bearer token is transmitted in the clear, a man-in the middle attack can
be used by a malicious party to acquire the token and use it for an unauthorized access to a protected resource. The same
security principles apply when storing or caching bearer tokens for later use. Always ensure that your application transmits
and stores bearer tokens in a secure manner. For more security considerations on bearer tokens, see RFC 6750 Section 5.
Now that you have an overview of the basics, read the sections below to understand how provisioning works in
Azure AD and the common scenarios Azure AD supports.
Claims in Azure AD Security Tokens
Security tokens issued by Azure AD contain claims, or assertions of information about the subject that has been
authenticated. These claims can be used by the application for various tasks. For example, they can be used to
validate the token, identify the subject's directory tenant, display user information, determine the subject's
authorization, and so on. The claims present in any given security token are dependent upon the type of token, the
type of credential used to authenticate the user, and the application configuration. A brief description of each type
of claim emitted by Azure AD is provided in the table below. For more information, refer to Supported Token and
Claim Types.
CLAIM
DESCRIPTION
Application ID
Identifies the application that is using the token.
Audience
Identifies the recipient resource the token is intended for.
Application Authentication Context Class Reference
Indicates how the client was authenticated (public client vs.
confidential client).
Authentication Instant
Records the date and time when the authentication occurred.
CLAIM
DESCRIPTION
Authentication Method
Indicates how the subject of the token was authenticated
(password, certificate, etc.).
First Name
Provides the given name of the user as set in Azure AD.
Groups
Contains object Ids of Azure AD groups the user is a member
of.
Identity Provider
Records the identity provider that authenticated the subject of
the token.
Issued At
Records the time at which the token was issued, often used for
token freshness.
Issuer
Identifies the STS that emitted the token as well as the Azure
AD tenant.
Last Name
Provides the surname of the user as set in Azure AD.
Name
Provides a human readable value that identifies the subject of
the token.
Object Id
Contains an immutable, unique identifier of the subject in
Azure AD.
Roles
Contains friendly names of Azure AD Application Roles that
the user has been granted.
Scope
Indicates the permissions granted to the client application.
Subject
Indicates the principal about which the token asserts
information.
Tenant Id
Contains an immutable, unique identifier of the directory
tenant that issued the token.
Token Lifetime
Defines the time interval within which a token is valid.
User Principal Name
Contains the user principal name of the subject.
Version
Contains the version number of the token.
Basics of Registering an Application in Azure AD
Any application that outsources authentication to Azure AD must be registered in a directory. This step involves
telling Azure AD about your application, including the URL where it’s located, the URL to send replies after
authentication, the URI to identify your application, and more. This information is required for a few key reasons:
Azure AD needs coordinates to communicate with the application when handling sign-on or exchanging
tokens. These include the following:
Application ID URI: The identifier for an application. This value is sent to Azure AD during authentication
to indicate which application the caller wants a token for. Additionally, this value is included in the token
so that the application knows it was the intended target.
Reply URL and Redirect URI: In the case of a web API or web application, the Reply URL is the location to
which Azure AD will send the authentication response, including a token if authentication was successful.
In the case of a native application, the Redirect URI is a unique identifier to which Azure AD will redirect
the user-agent in an OAuth 2.0 request.
Application ID: The ID for an application, which is generated by Azure AD when the application is
registered. When requesting an authorization code or token, the Application ID and key are sent to Azure
AD during authentication.
Key: The key that is sent along with a Application ID when authenticating to Azure AD to call a web API.
Azure AD needs to ensure the application has the required permissions to access your directory data, other
applications in your organization, and so on
Provisioning becomes clearer when you understand that there are two categories of applications that can be
developed and integrated with Azure AD:
Single tenant application: A single tenant application is intended for use in one organization. These are typically
line-of-business (LoB) applications written by an enterprise developer. A single tenant application only needs to
be accessed by users in one directory, and as a result, it only needs to be provisioned in one directory. These
applications are typically registered by a developer in the organization.
Multi-tenant application: A multi-tenant application is intended for use in many organizations, not just one
organization. These are typically software-as-a-service (SaaS) applications written by an independent software
vendor (ISV). Multi-tenant applications need to be provisioned in each directory where they will be used, which
requires user or administrator consent to register them. This consent process starts when an application has
been registered in the directory and is given access to the Graph API or perhaps another web API. When a user
or administrator from a different organization signs up to use the application, they are presented with a dialog
that displays the permissions the application requires. The user or administrator can then consent to the
application, which gives the application access to the stated data, and finally registers the application in their
directory. For more information, see Overview of the Consent Framework.
Some additional considerations arise when developing a multi-tenant application instead of a single tenant
application. For example, if you are making your application available to users in multiple directories, you need a
mechanism to determine which tenant they’re in. A single tenant application only needs to look in its own directory
for a user, while a multi-tenant application needs to identify a specific user from all the directories in Azure AD. To
accomplish this task, Azure AD provides a common authentication endpoint where any multi-tenant application can
direct sign-in requests, instead of a tenant-specific endpoint. This endpoint is
https://login.microsoftonline.com/common for all directories in Azure AD, whereas a tenant-specific endpoint might
be https://login.microsoftonline.com/contoso.onmicrosoft.com. The common endpoint is especially important to
consider when developing your application because you’ll need the necessary logic to handle multiple tenants
during sign-in, sign-out, and token validation.
If you are currently developing a single tenant application but want to make it available to many organizations, you
can easily make changes to the application and its configuration in Azure AD to make it multi-tenant capable. In
addition, Azure AD uses the same signing key for all tokens in all directories, whether you are providing
authentication in a single tenant or multi-tenant application.
Each scenario listed in this document includes a sub-section that describes its provisioning requirements. For more
in-depth information about provisioning an application in Azure AD and the differences between single and multitenant applications, see Integrating Applications with Azure Active Directory for more information. Continue
reading to understand the common application scenarios in Azure AD.
Application Types and Scenarios
Each of the scenarios described in this document can be developed using various languages and platforms. They
are all backed by complete code samples which are available in our Code Samples guide, or directly from the
corresponding GitHub sample repositories. In addition, if your application needs a specific piece or segment of an
end-to-end scenario, in most cases that functionality can be added independently. For example, if you have a native
application that calls a web API, you can easily add a web application that also calls the web API. The following
diagram illustrates these scenarios and application types, and how different components can be added:
These are the five primary application scenarios 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 user needs to sign in to a single page application that is secured by Azure AD.
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.
Web Browser to Web Application
This section describes an application that authenticates a user in a web browser to a web application. In this
scenario, the web application directs the user’s browser to sign them in to Azure AD. Azure AD returns a sign-in
response through the user’s browser, which contains claims about the user in a security token. This scenario
supports sign-on using the WS-Federation, SAML 2.0, and OpenID Connect protocols.
Diagram
Description of Protocol Flow
1. When a user visits the application and needs to sign in, they are redirected via a sign-in request to the
authentication endpoint in Azure AD.
2. The user signs in on the sign-in page.
3. If authentication is successful, Azure AD creates an authentication token and returns a sign-in response to the
application’s Reply URL that was configured in the Azure Portal. For a production application, this Reply URL
should be HTTPS. The returned token includes claims about the user and Azure AD that are required by the
application to validate the token.
4. The application validates the token by using a public signing key and issuer information available at the
federation metadata document for Azure AD. After the application validates the token, Azure AD starts a new
session with the user. This session allows the user to access the application until it expires.
Code Samples
See the code samples for Web Browser to Web Application scenarios. And, check back frequently -- we add new
samples all the time. Web Browser to Web Application.
Registering
Single Tenant: If you are building an application just for your organization, it must be registered in your
company’s directory by using the Azure Portal.
Multi-Tenant: If you are building an application that can be used by users outside your organization, it must 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 your application available in their directory, you can include a sign-up process for
your customers that enables them to consent to your application. When they sign up for your application, they
will be presented with a dialog that shows the permissions the application requires, and then the option to
consent. Depending on the required permissions, an administrator in the other organization may be required to
give consent. When the user or administrator consents, the application is registered in their directory. For more
information, see Integrating Applications with Azure Active Directory.
Token Expiration
The user’s session expires when the lifetime of the token issued by Azure AD expires. Your application can shorten
this time period if desired, such as signing out users based on a period of inactivity. When the session expires, the
user will be prompted to sign in again.
Single Page Application (SPA )
This section describes authentication for a Single Page Application, that uses Azure AD and the OAuth 2.0 implicit
authorization grant to secure its web API back end. 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. To learn more about the implicit authorization grant, and help you
decide whether it's right for your application scenario, see Understanding the OAuth2 implicit grant flow in Azure
Active Directory.
In this scenario, when the user signs in, the JavaScript front end uses Active Directory Authentication Library for
JavaScript (ADAL.JS) and the implicit authorization grant to obtain an ID token (id_token) from Azure AD. The token
is cached and the client attaches it to the request as the bearer token when making calls to its Web API back end,
which is secured using the OWIN middleware.
Diagram
Description of Protocol Flow
1. The user navigates to the web application.
2. The application returns the JavaScript front end (presentation layer) to the browser.
3. The user initiates sign in, for example by clicking a sign in link. The browser sends a GET to the Azure AD
authorization endpoint to request an ID token. This request includes the application ID and reply URL in the
query parameters.
4. Azure AD validates the Reply URL against the registered Reply URL that was configured in the Azure Portal.
5. The user signs in on the sign-in page.
6. If authentication is successful, Azure AD creates an ID token and returns it as a URL fragment (#) to the
application’s Reply URL. For a production application, this Reply URL should be HTTPS. The returned token
includes claims about the user and Azure AD that are required by the application to validate the token.
7. The JavaScript client code running in the browser extracts the token from the response to use in securing calls to
the application’s web API back end.
8. The browser calls the application’s web API back end with the access token in the authorization header.
Code Samples
See the code samples for Single Page Application (SPA) scenarios. Be sure to check back frequently -- we add new
samples all the time. Single Page Application (SPA).
Registering
Single Tenant: If you are building an application just for your organization, it must be registered in your
company’s directory by using the Azure Portal.
Multi-Tenant: If you are building an application that can be used by users outside your organization, it must 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 your application available in their directory, you can include a sign-up process for
your customers that enables them to consent to your application. When they sign up for your application, they
will be presented with a dialog that shows the permissions the application requires, and then the option to
consent. Depending on the required permissions, an administrator in the other organization may be required to
give consent. When the user or administrator consents, the application is registered in their directory. For more
information, see Integrating Applications with Azure Active Directory.
After registering the application, it must be configured to use OAuth 2.0 Implicit Grant protocol. By default, this
protocol is disabled for applications. To enable the OAuth2 Implicit Grant protocol for your application, edit its
application manifest from the Azure Portal and set the “oauth2AllowImplicitFlow” value to true. For detailed
instructions, see Enabling OAuth 2.0 Implicit Grant for Single Page Applications.
Token Expiration
When you use ADAL.js to manage authentication with Azure AD, you benefit from several features that facilitate
refreshing an expired token as well as getting tokens for additional web API resources that may be called by the
application. When the user successfully authenticates with Azure AD, a session secured by a cookie is established
for the user between the browser and Azure AD. It’s important to note that the session exists between the user and
Azure AD and not between the user and the web application running on the server. When a token expires, ADAL.js
uses this session to silently obtain another token. It does this by using a hidden iFrame to send and receive the
request using the OAuth Implicit Grant protocol. ADAL.js can also use this same mechanism to silently obtain access
tokens from Azure AD for other web API resources that the application calls as long as these resources support
cross-origin resource sharing (CORS), are registered in the user’s directory, and any required consent was given by
the user during sign-in.
Native Application to Web API
This section describes a native application that calls a web API on behalf of a user. This scenario is built on the
OAuth 2.0 authorization code grant type with a public client, as described in section 4.1 of the OAuth 2.0
specification. The native application obtains an access token for the user by using the OAuth 2.0 protocol. This
access token is then sent in the request to the web API, which authorizes the user and returns the desired resource.
Diagram
Authentication flow for native application to API
Description of Protocol Flow
If you are using the AD Authentication Libraries, most of the protocol details described below are handled for you,
such as the browser pop-up, token caching, and handling of refresh tokens.
1. Using a browser pop-up, the native application makes a request to the authorization endpoint in Azure AD. This
request includes the Application ID and the redirect URI of the native application as shown in the Azure Portal,
and the application ID URI for the web API. If the user hasn’t already signed in, they are prompted to sign in
again
2. Azure AD authenticates the user. If it is a multi-tenant application and consent is required to use the application,
3.
4.
5.
6.
the user will be required to consent if they haven’t already done so. After granting consent and upon successful
authentication, Azure AD issues an authorization code response back to the client application’s redirect URI.
When Azure AD issues an authorization code response back to the redirect URI, the client application stops
browser interaction and extracts the authorization code from the response. Using this authorization code, the
client application sends a request to Azure AD’s token endpoint that includes the authorization code, details
about the client application (Application ID and redirect URI), and the desired resource (application ID URI for the
web API).
The authorization code and information about the client application and web API are validated by Azure AD.
Upon successful validation, Azure AD returns two tokens: a JWT access token and a JWT refresh token. In
addition, Azure AD returns basic information about the user, such as their display name and tenant ID.
Over HTTPS, the client 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 token,
and if validation is successful, returns the desired resource.
When the access token expires, the client application will receive an error that indicates the user needs to
authenticate again. If the application has a valid refresh token, it can be used to acquire a new access token
without prompting the user to sign in again. If the refresh token expires, the application will need to interactively
authenticate the user once again.
NOTE
The refresh token issued by Azure AD can be used to access multiple resources. For example, if you have a client application
that has permission to call two web APIs, the refresh token can be used to get an access token to the other web API as well.
Code Samples
See the code samples for Native Application to Web API scenarios. And, check back frequently -- we add new
samples all the time. Native Application to Web API.
Registering
Single Tenant: Both the native application and the web API must be registered in the same directory in Azure AD.
The web API can be configured to expose a set of permissions, which are used to limit the native application’s
access to its resources. The client application then selects the desired permissions from the “Permissions to
Other Applications” drop-down menu in the Azure Portal.
Multi-Tenant: First, the native application only ever registered in the developer or publisher’s directory. Second,
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,
which any user in the organization can consent to. Other applications require administrator-level permissions,
which a user in the organization cannot consent to. Only a directory administrator can give consent to
applications that require this level of permissions. When the user or administrator consents, only the web API is
registered in their directory. For more information, see Integrating Applications with Azure Active Directory.
Token Expiration
When the native application uses its authorization code to get a JWT access token, it also receives a JWT refresh
token. When the access token expires, the refresh token can be used to re-authenticate the user without requiring
them to sign in again. This refresh token is then used to authenticate the user, which results in a new access token
and refresh token.
Web Application to Web API
This section describes a web application that needs to get resources from a web API. In this scenario, there are two
identity types that the web application can use to authenticate and call the web API: an application identity, or a
delegated user identity.
Application identity: This scenario uses OAuth 2.0 client credentials grant to authenticate as the application and
access the web API. 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 via the application protocol, and 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.
Delegated user identity: This scenario can be accomplished in two ways: OpenID Connect, and OAuth 2.0
authorization code grant with a confidential client. 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.
Diagram
Description of Protocol Flow
Both the application identity and delegated user identity types are discussed in the flow below. The key difference
between them is that the delegated user identity must first acquire an authorization code before the user can signin and gain access to the web API.
A p p l i c a t i o n I d e n t i t y w i t h O A u t h 2 .0 C l i e n t C r e d e n t i a l s G r a n t
1. A user is signed in to Azure AD in the web application (see the Web Browser to Web Application above).
2. The web application needs to acquire an access token so that it can authenticate to the web API and retrieve the
desired resource. It makes a request to Azure AD’s token endpoint, providing the credential, Application ID, and
web API’s application ID URI.
3. Azure AD authenticates the application and returns a JWT access token that is used to call the web API.
4. Over HTTPS, 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 token,
and if validation is successful, returns the desired resource.
D e l e g a t e d U se r I d e n t i t y w i t h O p e n I D C o n n e c t
1. A user is signed in to a web application using Azure AD (see the Web Browser to Web Application section
above). 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 application will display the permissions it requires, and if any
of these are administrator-level permissions, a normal user in the directory will not be able to consent. This
consent process only applies to multi-tenant applications, not single tenant applications, as the application will
already have the necessary permissions. When the user signed in, the web application received an ID token with
information about the user, as well as an authorization code.
2. Using the authorization code issued by Azure AD, the web application sends a request to Azure AD’s token
endpoint that includes the authorization code, details about the client application (Application ID and redirect
URI), and the desired resource (application ID URI for the web API).
3. The authorization code and information about the web application and web API are validated by Azure AD. Upon
successful validation, Azure AD returns two tokens: a JWT access token and a JWT refresh token.
4. Over HTTPS, 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 token,
and if validation is successful, returns the desired resource.
D e l e g a t e d U se r I d e n t i t y w i t h O A u t h 2 .0 A u t h o r i z a t i o n C o d e G r a n t
1. A user is already signed in to a web application, whose authentication mechanism is independent of Azure AD.
2. The web application requires an authorization code to acquire an access token, so it issues a request through the
browser to Azure AD’s authorization endpoint, providing the Application ID and redirect URI for the web
application after successful authentication. The user signs in to Azure AD.
3. 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 application will display the permissions it requires, and if any of these
are administrator-level permissions, a normal user in the directory will not be able to consent. This consent
process only applies to multi-tenant applications, not single tenant applications, as the application will already
have the necessary permissions.
4. After the user has consented, the web application receives the authorization code that it needs to acquire an
access token.
5. Using the authorization code issued by Azure AD, the web application sends a request to Azure AD’s token
endpoint that includes the authorization code, details about the client application (Application ID and redirect
URI), and the desired resource (application ID URI for the web API).
6. The authorization code and information about the web application and web API are validated by Azure AD. Upon
successful validation, Azure AD returns two tokens: a JWT access token and a JWT refresh token.
7. Over HTTPS, 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 token,
and if validation is successful, returns the desired resource.
Code Samples
See the code samples for Web Application to Web API scenarios. And, check back frequently -- we add new samples
all the time. Web Application to Web API.
Registering
Single Tenant: For both the application identity and delegated user identity cases, the web application and the
web API must be registered in the same directory in Azure AD. The web API can be configured to expose a set of
permissions, which are used to limit the web application’s access to its resources. If a delegated user identity
type is being used, the web application needs to select the desired permissions from the “Permissions to Other
Applications” drop-down menu in the Azure Portal. This step is not required if the application identity type is
being used.
Multi-Tenant: First, the web 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 userlevel permissions, which any user in the organization can consent to. Other applications require administratorlevel permissions, which a user in the organization cannot consent to. Only a directory administrator can give
consent to applications that require this level of permissions. When the user or administrator consents, the web
application and the web API are both registered in their directory.
Token Expiration
When the web application uses its authorization code to get a JWT access token, it also receives a JWT refresh
token. When the access token expires, the refresh token can be used to re-authenticate the user without requiring
them to sign in again. This refresh token is then used to authenticate the user, which results in a new access token
and refresh token.
Daemon or Server Application to Web API
This section describes a daemon or server application that needs to get resources from a web API. There are two
sub-scenarios that apply to this section: A daemon that needs to call a web API, built on OAuth 2.0 client credentials
grant type; and a server application (such as a web API) that needs to call a web API, built on OAuth 2.0 On-BehalfOf draft specification.
For the scenario when a daemon application needs to call a web API, it’s important to understand a few things. First,
user interaction is not possible with a daemon application, which requires the application to have its own identity.
An example of a daemon application is a batch job, or an operating system service running in the background. This
type of application requests an access token by using its application identity and presenting its Application 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.
For the scenario when a server application needs to call a web API, it’s helpful to use an example. Imagine that a
user has authenticated on a native application, and this native application needs to call a web API. Azure AD issues a
JWT access token to call the web API. If the web API needs to call another downstream web API, it can use the onbehalf-of flow to delegate the user’s identity and authenticate to the second-tier web API.
Diagram
Description of Protocol Flow
A p p l i c a t i o n I d e n t i t y w i t h O A u t h 2 .0 C l i e n t C r e d e n t i a l s G r a n t
1. First, the server application needs to authenticate with Azure AD as itself, without any human interaction such as
an interactive sign-on dialog. It makes a request to Azure AD’s token endpoint, providing the credential,
Application ID, and application ID URI.
2. Azure AD authenticates the application and returns a JWT access token that is used to call the web API.
3. Over HTTPS, 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 token,
and if validation is successful, returns the desired resource.
D e l e g a t e d U se r I d e n t i t y w i t h O A u t h 2 .0 O n - B e h a l f- O f D r a ft Sp e c i fi c a t i o n
The flow discussed below assumes that a user has been authenticated on another application (such as a native
application), and their user identity has been used to acquire an access token to the first-tier web API.
1. The native application sends the access token to the first-tier web API.
2. The first-tier web API sends a request to Azure AD’s token endpoint, providing its Application ID and credentials,
as well as the user’s 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.
3. 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.
4. 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.
Code Samples
See the code samples for Daemon or Server Application to Web API scenarios. And, check back frequently -- we add
new samples all the time. Server or Daemon Application to Web API
Registering
Single Tenant: For both the application identity and delegated user identity cases, the daemon or server
application must be registered in the same directory in Azure AD. The web API can be configured to expose a set
of permissions, which are used to limit the daemon or server’s access to its resources. If a delegated user identity
type is being used, the server application needs to select the desired permissions from the “Permissions to Other
Applications” drop-down menu in the Azure Portal. This step is not required if the application identity type is
being used.
Multi-Tenant: First, the daemon or server 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, which any user in the organization can consent to. Other applications require
administrator-level permissions, which a user in the organization cannot consent to. Only a directory
administrator can give consent to applications that require this level of permissions. When the user or
administrator consents, both of the web APIs are registered in their directory.
Token Expiration
When the first application uses its authorization code to get a JWT access token, it also receives a JWT refresh token.
When the access token expires, the refresh token can be used to re-authenticate the user without prompting for
credentials. This refresh token is then used to authenticate the user, which results in a new access token and refresh
token.
See Also
Azure Active Directory Developer's Guide
Azure Active Directory Code Samples
Important Information About Signing Key Rollover in Azure AD
OAuth 2.0 in Azure AD
ASP.NET web app sign-in and sign-out with Azure
AD
3/17/2017 • 5 min to read • Edit Online
NOTE
This article is part of the Azure Active Directory developer's guide.
By providing a single sign-in and sign-out with only a few lines of code, Azure Active Directory (Azure AD) makes it
simple for you to outsource web-app identity management. You can sign users in and out of ASP.NET web apps by
using the Microsoft implementation of Open Web Interface for .NET (OWIN) middleware. Community-driven
OWIN middleware is included in .NET Framework 4.5. This article shows how to use OWIN to:
Sign users in to web apps by using Azure AD as the identity provider.
Display some user information.
Sign users out of the apps.
Before you get started
Download the app skeleton or download the completed sample.
You also need an Azure AD tenant in which to register the app. If you don't already have an Azure AD tenant,
learn how to get one.
When you are ready, follow the procedures in the next four sections.
Step 1: Register the new app with Azure AD
To set up the app to authenticate users, first register it in your tenant by doing the following:
1. Sign in to the Azure portal.
2. On the top bar, click your account name. Under the Directory list, select the Active Directory tenant where you
want to register the app.
3. Click More Services in the left pane, and then select Azure Active Directory.
4. Click App registrations, and then select Add.
5. Follow the prompts to create a new Web Application and/or WebAPI.
Name describes the app to users.
Sign-On URL is the base URL of the app. The skeleton's default URL is https://localhost:44320/.
6. After you've completed the registration, Azure AD assigns the app a unique application ID. Copy the value from
the app page to use in the next sections.
7. From the Settings -> Properties page for your application, update the App ID URI. The App ID URI is a unique
identifier for the app. The naming convention is https://<tenant-domain>/<app-name> (for example,
https://contoso.onmicrosoft.com/my-first-aad-app ).
Step 2: Set up the app to use the OWIN authentication pipeline
In this step, you configure the OWIN middleware to use the OpenID Connect authentication protocol. You use
OWIN to issue sign-in and sign-out requests, manage user sessions, get user information, and so forth.
1. To begin, add the OWIN middleware NuGet packages to the project by using the Package Manager Console.
PM> Install-Package Microsoft.Owin.Security.OpenIdConnect
PM> Install-Package Microsoft.Owin.Security.Cookies
PM> Install-Package Microsoft.Owin.Host.SystemWeb
2. To add an OWIN Startup class to the project called Startup.cs , right-click the project, select Add, select
New Item, and then search for OWIN. The OWIN middleware invokes the Configuration(...) method when
the app starts.
3. Change the class declaration to public partial class Startup . We've already implemented part of this class
for you in another file. In the Configuration(...) method, make a call to ConfgureAuth(...) to set up
authentication for the app.
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
}
}
4. Open the App_Start\Startup.Auth.cs file, and then implement the ConfigureAuth(...) method. The
parameters you provide in OpenIDConnectAuthenticationOptions serve as coordinates for the app to
communicate with Azure AD. You also need to set up cookie authentication, because the OpenID Connect
middleware uses cookies in the background.
public void ConfigureAuth(IAppBuilder app)
{
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions
{
ClientId = clientId,
Authority = authority,
PostLogoutRedirectUri = postLogoutRedirectUri,
});
}
5. Open the web.config file in the root of the project, and then enter the configuration values in the
<appSettings> section.
ida:ClientId
: The GUID you copied from the Azure portal in "Step 1: Register the new app with Azure
AD."
: The name of your Azure AD tenant (for example, contoso.onmicrosoft.com).
ida:PostLogoutRedirectUri : The indicator that tells Azure AD where a user should be redirected after a
sign-out request is successfully completed.
ida:Tenant
Step 3: Use OWIN to issue sign-in and sign-out requests to Azure AD
The app is now properly configured to communicate with Azure AD by using the OpenID Connect authentication
protocol. OWIN has handled all of the details of crafting authentication messages, validating tokens from Azure AD,
and maintaining user sessions. All that remains is to give your users a way to sign in and sign out.
1. You can use authorize tags in your controllers to require users to sign in before they access certain pages. To
do so, open Controllers\HomeController.cs, and then add the [Authorize] tag to the About controller.
[Authorize]
public ActionResult About()
{
...
2. You can also use OWIN to directly issue authentication requests from within your code. To do so, open
Controllers\AccountController.cs. Then, in the SignIn() and SignOut() actions, issue OpenID Connect
challenge and sign-out requests.
public void SignIn()
{
// Send an OpenID Connect sign-in request.
if (!Request.IsAuthenticated)
{
HttpContext.GetOwinContext().Authentication.Challenge(new AuthenticationProperties { RedirectUri
= "/" }, OpenIdConnectAuthenticationDefaults.AuthenticationType);
}
}
public void SignOut()
{
// Send an OpenID Connect sign-out request.
HttpContext.GetOwinContext().Authentication.SignOut(
OpenIdConnectAuthenticationDefaults.AuthenticationType,
CookieAuthenticationDefaults.AuthenticationType);
}
3. Open Views\Shared_LoginPartial.cshtml to show the user the app sign-in and sign-out links, and to print out
the user's name in a view.
@if (Request.IsAuthenticated)
{
<text>
<ul class="nav navbar-nav navbar-right">
<li class="navbar-text">
Hello, @User.Identity.Name!
</li>
<li>
@Html.ActionLink("Sign out", "SignOut", "Account")
</li>
</ul>
</text>
}
else
{
<ul class="nav navbar-nav navbar-right">
<li>@Html.ActionLink("Sign in", "SignIn", "Account", routeValues: null, htmlAttributes: new { id =
"loginLink" })</li>
</ul>
}
Step 4: Display user information
When it authenticates users with OpenID Connect, Azure AD returns an id_token to the app that contains "claims,"
or assertions about the user. You can use these claims to personalize the app by doing the following:
1. Open the Controllers\HomeController.cs file. You can access the user's claims in your controllers via the
ClaimsPrincipal.Current security principal object.
public ActionResult About()
{
ViewBag.Name = ClaimsPrincipal.Current.FindFirst(ClaimTypes.Name).Value;
ViewBag.ObjectId =
ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value
;
ViewBag.GivenName = ClaimsPrincipal.Current.FindFirst(ClaimTypes.GivenName).Value;
ViewBag.Surname = ClaimsPrincipal.Current.FindFirst(ClaimTypes.Surname).Value;
ViewBag.UPN = ClaimsPrincipal.Current.FindFirst(ClaimTypes.Upn).Value;
return View();
}
2. Build and run the app. If you haven't already created a new user in your tenant with an onmicrosoft.com
domain, now is the time to do so. Here's how:
a. Sign in with that user, and note how the user's identity is reflected on the top bar.
b. Sign out, and then sign back in as another user in your tenant.
c. If you're feeling particularly ambitious, register and run another instance of this app (with its own clientId),
and watch single sign-in in action.
Next steps
For reference, see the completed sample (without your configuration values).
You can now move on to more advanced topics. For example, try Secure a Web API with Azure AD.
Additional resources
The Azure AD developer's guide
Azure AD samples on GitHub
CloudIdentity.com
Get security updates for our products
We encourage you to get notifications of when security incidents occur by visiting the TechCenter page for
Microsoft technical security notifications and subscribing to security advisory alerts.
Java web app sign-in and sign-out with Azure AD
4/17/2017 • 27 min to read • Edit Online
NOTE
This article is part of the Azure Active Directory developer's guide.
By providing a single sign-in and sign-out with only a few lines of code, Azure Active Directory (Azure AD) makes it
simple for you to outsource web-app identity management. You can sign users in and out of Java web apps by
using the Microsoft implementation of the community-driven Azure Active Directory Authentication Library for
Java (ADAL4J).
This article shows how to use the ADAL4J to:
Sign users in to web apps by using Azure AD as the identity provider.
Display some user information.
Sign users out of the apps.
Before you get started
Download the app skeleton, or download the completed sample.
You also need an Azure AD tenant in which to register the app. If you don't already have an Azure AD tenant,
learn how to get one.
When you are ready, follow the procedures in the next nine sections.
Step 1: Register the new app with Azure AD
To set up the app to authenticate users, first register it in your tenant by doing the following:
1. Sign in to the Azure portal.
2. On the top bar, click your account name. Under the Directory list, select the Active Directory tenant where you
want to register the app.
3. Click More Services in the left pane, and then select Azure Active Directory.
4. Click App registrations, and then select Add.
5. Follow the prompts to create a Web Application and/or WebAPI.
Name describes the app to users.
Sign-On URL is the base URL of the app. The skeleton's default URL is
http://localhost:8080/adal4jsample/.
6. After you've completed the registration, Azure AD assigns the app a unique application ID. Copy the value from
the app page to use in the next sections.
7. From the Settings -> Properties page for your application, update the App ID URI. The App ID URI is a unique
identifier for the app. The naming convention is https://<tenant-domain>/<app-name> (for example,
http://localhost:8080/adal4jsample/ ).
When you are in the portal for the app, create and copy a key for the app on the Settings page. You'll need the key
shortly.
Step 2: Set up the app to use the ADAL4J and prerequisites by using
Maven
In this step, you configure the ADAL4J to use the OpenID Connect authentication protocol. You use the ADAL4J to
issue sign-in and sign-out requests, manage user sessions, get user information, and so forth.
In the root directory of your project, open/create
replace it with the following:
pom.xml
, locate
// TODO: provide dependencies for Maven
, and
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.microsoft.azure</groupId>
<artifactId>adal4jsample</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>adal4jsample</name>
<url>http://maven.apache.org</url>
<properties>
<spring.version>3.0.5.RELEASE</spring.version>
</properties>
<dependencies>
<dependency>
<groupId>com.microsoft.azure</groupId>
<artifactId>adal4j</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>com.nimbusds</groupId>
<artifactId>oauth2-oidc-sdk</artifactId>
<version>4.5</version>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20090211</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.5</version>
</dependency>
<!-- Spring 3 dependencies -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
</dependency>
</dependencies>
<build>
<finalName>sample-for-adal4j</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.7</source>
<target>1.7</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.4</version>
<configuration>
<warName>${project.artifactId}</warName>
<source>${project.basedir}\src</source>
<target>${maven.compiler.target}</target>
<encoding>utf-8</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>install</id>
<phase>install</phase>
<goals>
<goal>sources</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>2.5</version>
<configuration>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
</plugins>
</build>
</project>
Step 3: Create the Java web app files (WEB-INF)
In this step, you configure the Java web app to use the OpenID Connect authentication protocol. Use the ADAL4J to
issue sign-in and sign-out requests, manage the user's session, get information about the user, and so forth.
1. Open the web.xml file located under \webapp\WEB-INF\, and enter the app configuration values in the XML.
The XML file should contain the following code:
<?xml version="1.0"?>
<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Archetype Created Web Application</display-name>
<context-param>
<param-name>authority</param-name>
<param-value>https://login.windows.net/</param-value>
</context-param>
<context-param>
<param-name>tenant</param-name>
<param-value>YOUR_TENANT_NAME</param-value>
</context-param>
<filter>
<filter-name>BasicFilter</filter-name>
<filter-class>com.microsoft.aad.adal4jsample.BasicFilter</filter-class>
<init-param>
<param-name>client_id</param-name>
<param-value>YOUR_CLIENT_ID</param-value>
</init-param>
<init-param>
<param-name>secret_key</param-name>
<param-value>YOUR_CLIENT_SECRET</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>BasicFilter</filter-name>
<url-pattern>/secure/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>
YOUR_CLIENT_ID is the Application Id assigned to your app in the registration portal.
YOUR_CLIENT_SECRET is the Application Secret that you created in the portal.
YOUR_TENANT_NAME is the tenant name of your app (for example, contoso.onmicrosoft.com).
As you can see in the XML file, you are writing a JavaServer Pages (JSP) or Java Servlet web app called mvcdispatcher that uses BasicFilter whenever you visit the /secure URL. In the same code, you use /secure as a
place for the protected content and to force authentication to Azure AD.
2. Create the mvc-dispatcher-servlet.xml file located under \webapp\WEB-INF\, and enter the following code:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.microsoft.aad.adal4jsample" />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
This code tells the web app to use Spring, and it indicates where to find the JSP file, which you write in the
next section.
Step 4: Create the JSP View files (for BasicFilter MVC)
You are half-way through setting up your web app in WEB-INF. Next, you create the JSP files for BasicFilter model
view controller (MVC), which the web app executes. We hinted at creating the files during the configuration.
Earlier, you told Java in the XML configuration files that you have a / resource that loads JSP files, and you have a
/secure resource that passes through a filter, which you called BasicFilter.
To create the JSP files, do the following:
1. Create the index.jsp file (located under \webapp), and then paste the following code:
<html>
<body>
<h2>Hello World!</h2>
<ul>
<li><a href="secure/aad">Secure Page</a></li>
</ul>
</body>
</html>
This code simply redirects to a secure page that is protected by the filter.
2. In the same directory, create an error.jsp file to catch any errors that might happen:
<html>
<body>
<h2>ERROR PAGE!</h2>
<p>
Exception <%=request.getAttribute("error")%></p>
<ul>
<li><a href="<%=request.getContextPath()%>/index.jsp">Go Home</a></li>
</ul>
</body>
</html>
3. To make that secure webpage, create a folder under \webapp called \secure so that the directory is now
\webapp\secure.
4. In the \webapp\secure directory, create an aad.jsp file, and then paste the following code:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>AAD Secure Page</title>
</head>
<body>
<h1>Directory - Users List</h1>
<p>${users}</p>
<ul>
<li><a href="<%=request.getContextPath()%>/secure/aad?cc=1">Get new Access Token via Client
Credentials</a></li>
</ul>
<ul>
<li><a href="<%=request.getContextPath()%>/secure/aad?refresh=1">Get new Access Token via
Refresh Token</a></li>
</ul>
<ul>
<li><a href="<%=request.getContextPath()%>/index.jsp">Go Home</a></li>
</ul>
</body>
</html>
This page redirects to specific requests, which the BasicFilter servlet reads and then executes on by using the
ADAJ4J.
You now need to set up the Java files so that the servlet can do its work.
Step 5: Create some Java helper files (for BasicFilter MVC)
Our goal in this step is to create Java files that:
Allow for sign-in and sign-out of the user.
Get some data about the user.
NOTE
To get data about the user, use the Graph API from Azure AD. The Graph API is a secure webservice that you can use
to grab data about your organization, including individual users. This approach is better than pre-filling sensitive data
in tokens, because it ensures that:
The users who ask for the data are authorized.
Anyone who might happen to grab the token (from a jailbroken phone or web-browser cache on a desktop, for
example) cannot obtain important details about the user or the organization.
To write some Java files for this work:
1. Create a folder in your root directory called adal4jsample to store all the Java files.
In this example, you are using the namespace com.microsoft.aad.adal4jsample in the Java files. Most IDEs
create a nested folder structure for this purpose (for example, /com/microsoft/aad/adal4jsample). You can
do this also, but it is not necessary.
2. Inside this folder, create a file called JSONHelper.java, which you'll use to help parse the JSON data from
your tokens. To create the file, paste the following code:
package com.microsoft.aad.adal4jsample;
import
import
import
import
java.lang.reflect.Field;
java.util.Arrays;
java.util.Enumeration;
java.util.List;
import javax.servlet.http.HttpServletRequest;
import
import
import
import
import
org.apache.commons.lang3.text.WordUtils;
org.apache.log4j.Logger;
org.json.JSONArray;
org.json.JSONException;
org.json.JSONObject;
/**
* This class provides the methods to parse JSON data from a JSON-formatted
* string.
*
* @author Azure Active Directory contributor
*
*/
public class JSONHelper {
private static Logger logger = Logger.getLogger(JSONHelper.class);
JSONHelper() {
// PropertyConfigurator.configure("log4j.properties");
}
/**
* This method parses a JSON array out of a collection of JSON objects
* within a string.
*
* @param jSonData
*
The JSON string that holds the collection
* @return A JSON array that contains all the collection objects
* @throws Exception
*/
public static JSONArray fetchDirectoryObjectJSONArray(JSONObject jsonObject) throws Exception {
JSONArray jsonArray = new JSONArray();
jsonArray = jsonObject.optJSONObject("responseMsg").optJSONArray("value");
jsonArray = jsonObject.optJSONObject("responseMsg").optJSONArray("value");
return jsonArray;
}
/**
* This method parses a JSON object out of a collection of JSON objects
* within a string.
*
* @param jsonObject
* @return A JSON object that contains the DirectoryObject
* @throws Exception
*/
public static JSONObject fetchDirectoryObjectJSONObject(JSONObject jsonObject) throws Exception {
JSONObject jObj = new JSONObject();
jObj = jsonObject.optJSONObject("responseMsg");
return jObj;
}
/**
* This method parses the skip token from a JSON-formatted string.
*
* @param jsonData
*
The JSON-formatted string
* @return The skipToken
* @throws Exception
*/
public static String fetchNextSkiptoken(JSONObject jsonObject) throws Exception {
String skipToken = "";
// Parse the skip token out of the string.
skipToken = jsonObject.optJSONObject("responseMsg").optString("odata.nextLink");
if (!skipToken.equalsIgnoreCase("")) {
// Remove the unnecessary prefix from the skip token.
int index = skipToken.indexOf("$skiptoken=") + (new String("$skiptoken=")).length();
skipToken = skipToken.substring(index);
}
return skipToken;
}
/**
* @param jsonObject
* @return
* @throws Exception
*/
public static String fetchDeltaLink(JSONObject jsonObject) throws Exception {
String deltaLink = "";
// Parse the skip token out of the string.
deltaLink = jsonObject.optJSONObject("responseMsg").optString("aad.deltaLink");
if (deltaLink == null || deltaLink.length() == 0) {
deltaLink = jsonObject.optJSONObject("responseMsg").optString("aad.nextLink");
logger.info("deltaLink empty, nextLink ->" + deltaLink);
}
if (!deltaLink.equalsIgnoreCase("")) {
// Remove the unnecessary prefix from the skip token.
int index = deltaLink.indexOf("deltaLink=") + (new String("deltaLink=")).length();
deltaLink = deltaLink.substring(index);
}
return deltaLink;
}
/**
* This method creates a string consisting of a JSON document with all
* the necessary elements set from the HttpServletRequest request.
*
* @param request
*
The HttpServletRequest
* @return The string containing the JSON document
* @throws Exception
*
If there is any error processing the request.
*
If there is any error processing the request.
*/
public static String createJSONString(HttpServletRequest request, String controller) throws
Exception {
JSONObject obj = new JSONObject();
try {
Field[] allFields = Class.forName(
"com.microsoft.windowsazure.activedirectory.sdk.graph.models." +
controller).getDeclaredFields();
String[] allFieldStr = new String[allFields.length];
for (int i = 0; i < allFields.length; i++) {
allFieldStr[i] = allFields[i].getName();
}
List<String> allFieldStringList = Arrays.asList(allFieldStr);
Enumeration<String> fields = request.getParameterNames();
while (fields.hasMoreElements()) {
String fieldName = fields.nextElement();
String param = request.getParameter(fieldName);
if (allFieldStringList.contains(fieldName)) {
if (param == null || param.length() == 0) {
if (!fieldName.equalsIgnoreCase("password")) {
obj.put(fieldName, JSONObject.NULL);
}
} else {
if (fieldName.equalsIgnoreCase("password")) {
obj.put("passwordProfile", new JSONObject("{\"password\": \"" + param +
"\"}"));
} else {
obj.put(fieldName, param);
}
}
}
}
} catch (JSONException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return obj.toString();
}
/**
*
* @param key
* @param value
* @return string format of this JSON object
* @throws Exception
*/
public static String createJSONString(String key, String value) throws Exception {
JSONObject obj = new JSONObject();
try {
obj.put(key, value);
} catch (JSONException e) {
e.printStackTrace();
}
return obj.toString();
}
/**
* This is a generic method that copies the simple attribute values from an
* argument jsonObject to an argument generic object.
*
* @param jsonObject
*
The jsonObject from where the attributes are to be copied.
*
The jsonObject from where the attributes are to be copied.
* @param destObject
*
The object where the attributes should be copied to.
* @throws Exception
*
Throws an Exception when the operation is unsuccessful.
*/
public static <T> void convertJSONObjectToDirectoryObject(JSONObject jsonObject, T destObject)
throws Exception {
// Get the list of all the field names.
Field[] fieldList = destObject.getClass().getDeclaredFields();
// For all the declared field.
for (int i = 0; i < fieldList.length; i++) {
// If the field is of type String, that is
// if it is a simple attribute.
if (fieldList[i].getType().equals(String.class)) {
// Invoke the corresponding set method of the destObject using
// the argument taken from the jsonObject.
destObject
.getClass()
.getMethod(String.format("set%s", WordUtils.capitalize(fieldList[i].getName())),
new Class[] { String.class })
.invoke(destObject, new Object[] { jsonObject.optString(fieldList[i].getName())
});
}
}
}
public static JSONArray joinJSONArrays(JSONArray a, JSONArray b) {
JSONArray comb = new JSONArray();
for (int i = 0; i < a.length(); i++) {
comb.put(a.optJSONObject(i));
}
for (int i = 0; i < b.length(); i++) {
comb.put(b.optJSONObject(i));
}
return comb;
}
}
3. Create a file called HttpClientHelper.java, which you will use to help parse the HTTP data from your Azure AD
endpoint. To create the file, paste the following code:
package com.microsoft.aad.adal4jsample;
import
import
import
import
import
import
import
java.io.BufferedReader;
java.io.ByteArrayOutputStream;
java.io.IOException;
java.io.InputStream;
java.io.InputStreamReader;
java.io.OutputStreamWriter;
java.net.HttpURLConnection;
import org.json.JSONException;
import org.json.JSONObject;
/**
* This is Helper class for all RestClient class.
*
* @author Azure Active Directory Contributor
*
*/
public class HttpClientHelper {
public HttpClientHelper() {
super();
}
public static String getResponseStringFromConn(HttpURLConnection conn, boolean isSuccess) throws
IOException {
BufferedReader reader = null;
if (isSuccess) {
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
} else {
reader = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
}
StringBuffer stringBuffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
stringBuffer.append(line);
}
return stringBuffer.toString();
}
public static String getResponseStringFromConn(HttpURLConnection conn, String payLoad) throws
IOException {
// Send the http message payload to the server.
if (payLoad != null) {
conn.setDoOutput(true);
OutputStreamWriter osw = new OutputStreamWriter(conn.getOutputStream());
osw.write(payLoad);
osw.flush();
osw.close();
}
// Get the message response from the server.
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line = "";
StringBuffer stringBuffer = new StringBuffer();
while ((line = br.readLine()) != null) {
stringBuffer.append(line);
}
br.close();
return stringBuffer.toString();
}
public static byte[] getByteaArrayFromConn(HttpURLConnection conn, boolean isSuccess) throws
IOException {
InputStream is = conn.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buff = new byte[1024];
int bytesRead = 0;
while ((bytesRead = is.read(buff, 0, buff.length)) != -1) {
baos.write(buff, 0, bytesRead);
}
byte[] bytes = baos.toByteArray();
baos.close();
return bytes;
}
/**
* for bad response, whose responseCode is not 200 level
*
* @param responseCode
* @param errorCode
* @param errorMsg
* @return
* @throws JSONException
*/
public static JSONObject processResponse(int responseCode, String errorCode, String errorMsg) throws
JSONException {
JSONObject response = new JSONObject();
response.put("responseCode", responseCode);
response.put("errorCode", errorCode);
response.put("errorMsg", errorMsg);
return response;
}
/**
* for bad response, whose responseCode is not 200 level
*
* @param responseCode
* @param errorCode
* @param errorMsg
* @return
* @throws JSONException
*/
public static JSONObject processGoodRespStr(int responseCode, String goodRespStr) throws
JSONException {
JSONObject response = new JSONObject();
response.put("responseCode", responseCode);
if (goodRespStr.equalsIgnoreCase("")) {
response.put("responseMsg", "");
} else {
response.put("responseMsg", new JSONObject(goodRespStr));
}
return response;
}
/**
* for good response
*
* @param responseCode
* @param responseMsg
* @return
* @throws JSONException
*/
public static JSONObject processBadRespStr(int responseCode, String responseMsg) throws
JSONException {
JSONObject response = new JSONObject();
response.put("responseCode", responseCode);
if (responseMsg.equalsIgnoreCase("")) { // good response is empty string
response.put("responseMsg", "");
} else { // bad response is json string
JSONObject errorObject = new JSONObject(responseMsg).optJSONObject("odata.error");
String errorCode = errorObject.optString("code");
String errorMsg = errorObject.optJSONObject("message").optString("value");
response.put("responseCode", responseCode);
response.put("errorCode", errorCode);
response.put("errorMsg", errorMsg);
}
return response;
}
}
Step 6: Create the Java Graph API Model files (for BasicFilter MVC)
As indicated previously, you use the Graph API to get data about the signed-in user. To make this process easy,
create both a file to represent a Directory object and a file to represent the user so that the OO pattern of Java can
be used.
1. Create a file called DirectoryObject.java, which you use to store basic data about any Directory object. You
can use this file later for any other Graph queries you might perform. To create the file, paste the following
code:
package com.microsoft.aad.adal4jsample;
/**
* @author Azure Active Directory Contributor
*
*/
public abstract class DirectoryObject {
public DirectoryObject() {
super();
}
/**
*
* @return
*/
public abstract String getObjectId();
/**
* @param objectId
*/
public abstract void setObjectId(String objectId);
/**
*
* @return
*/
public abstract String getObjectType();
/**
*
* @param objectType
*/
public abstract void setObjectType(String objectType);
/**
*
* @return
*/
public abstract String getDisplayName();
/**
*
* @param displayName
*/
public abstract void setDisplayName(String displayName);
}
2. Create a file called User.java, which you use to store basic data about any user from the directory. These are
basic getter and setter methods for directory data, so you can paste the following code:
package com.microsoft.aad.adal4jsample;
import java.security.acl.Group;
import java.util.ArrayList;
import javax.xml.bind.annotation.XmlRootElement;
import org.json.JSONObject;
/**
* The **User** class holds together all the members of a WAAD User entity and all the access methods
and set methods.
* @author Azure Active Directory Contributor
*/
@XmlRootElement
public class User extends DirectoryObject{
// The following are the individual private members of a User object that holds
// a particular simple attribute of a User object.
protected String objectId;
protected String objectType;
protected String accountEnabled;
protected String city;
protected String country;
protected String department;
protected String dirSyncEnabled;
protected String displayName;
protected String facsimileTelephoneNumber;
protected String givenName;
protected String jobTitle;
protected String lastDirSyncTime;
protected String mail;
protected String mailNickname;
protected String mobile;
protected String password;
protected String passwordPolicies;
protected String physicalDeliveryOfficeName;
protected String postalCode;
protected String preferredLanguage;
protected String state;
protected String streetAddress;
protected String surname;
protected String telephoneNumber;
protected String usageLocation;
protected String userPrincipalName;
protected boolean isDeleted; // this will move to dto
/**
* These four properties are for future use.
*/
// managerDisplayname of this user.
protected String managerDisplayname;
// The directReports holds a list of directReports.
private ArrayList<User> directReports;
// The groups holds a list of group entities this user belongs to.
private ArrayList<Group> groups;
// The roles holds a list of role entities this user belongs to.
private ArrayList<Group> roles;
/**
* The constructor for the **User** class. Initializes the dynamic lists and managerDisplayname
variables.
*/
public User(){
directReports = null;
groups = new ArrayList<Group>();
groups = new ArrayList<Group>();
roles = new ArrayList<Group>();
managerDisplayname = null;
}
//
//
//
//
//
//
//
//
//
//
//
//
//
public User(String displayName, String objectId){
setDisplayName(displayName);
setObjectId(objectId);
}
public User(String displayName, String objectId, String userPrincipalName, String accountEnabled){
setDisplayName(displayName);
setObjectId(objectId);
setUserPrincipalName(userPrincipalName);
setAccountEnabled(accountEnabled);
}
/**
* @return The objectId of this user.
*/
public String getObjectId() {
return objectId;
}
/**
* @param objectId The objectId to set to this User object.
*/
public void setObjectId(String objectId) {
this.objectId = objectId;
}
/**
* @return The objectType of this user.
*/
public String getObjectType() {
return objectType;
}
/**
* @param objectType The objectType to set to this User object.
*/
public void setObjectType(String objectType) {
this.objectType = objectType;
}
/**
* @return The userPrincipalName of this user.
*/
public String getUserPrincipalName() {
return userPrincipalName;
}
/**
* @param userPrincipalName The userPrincipalName to set to this User object.
*/
public void setUserPrincipalName(String userPrincipalName) {
this.userPrincipalName = userPrincipalName;
}
/**
* @return The usageLocation of this user.
*/
public String getUsageLocation() {
return usageLocation;
}
/**
* @param usageLocation The usageLocation to set to this User object.
*/
*/
public void setUsageLocation(String usageLocation) {
this.usageLocation = usageLocation;
}
/**
* @return The telephoneNumber of this user.
*/
public String getTelephoneNumber() {
return telephoneNumber;
}
/**
* @param telephoneNumber The telephoneNumber to set to this User object.
*/
public void setTelephoneNumber(String telephoneNumber) {
this.telephoneNumber = telephoneNumber;
}
/**
* @return The surname of this user.
*/
public String getSurname() {
return surname;
}
/**
* @param surname The surname to set to this User object.
*/
public void setSurname(String surname) {
this.surname = surname;
}
/**
* @return The streetAddress of this user.
*/
public String getStreetAddress() {
return streetAddress;
}
/**
* @param streetAddress The streetAddress to set to this user.
*/
public void setStreetAddress(String streetAddress) {
this.streetAddress = streetAddress;
}
/**
* @return The state of this user.
*/
public String getState() {
return state;
}
/**
* @param state The state to set to this User object.
*/
public void setState(String state) {
this.state = state;
}
/**
* @return The preferredLanguage of this user.
*/
public String getPreferredLanguage() {
return preferredLanguage;
}
/**
* @param preferredLanguage The preferredLanguage to set to this user.
* @param preferredLanguage The preferredLanguage to set to this user.
*/
public void setPreferredLanguage(String preferredLanguage) {
this.preferredLanguage = preferredLanguage;
}
/**
* @return The postalCode of this user.
*/
public String getPostalCode() {
return postalCode;
}
/**
* @param postalCode The postalCode to set to this user.
*/
public void setPostalCode(String postalCode) {
this.postalCode = postalCode;
}
/**
* @return The physicalDeliveryOfficeName of this user.
*/
public String getPhysicalDeliveryOfficeName() {
return physicalDeliveryOfficeName;
}
/**
* @param physicalDeliveryOfficeName The physicalDeliveryOfficeName to set to this User object.
*/
public void setPhysicalDeliveryOfficeName(String physicalDeliveryOfficeName) {
this.physicalDeliveryOfficeName = physicalDeliveryOfficeName;
}
/**
* @return The passwordPolicies of this user.
*/
public String getPasswordPolicies() {
return passwordPolicies;
}
/**
* @param passwordPolicies The passwordPolicies to set to this User object.
*/
public void setPasswordPolicies(String passwordPolicies) {
this.passwordPolicies = passwordPolicies;
}
/**
* @return The mobile of this user.
*/
public String getMobile() {
return mobile;
}
/**
* @param mobile The mobile to set to this User object.
*/
public void setMobile(String mobile) {
this.mobile = mobile;
}
/**
* @return The password of this user.
*/
public String getPassword() {
return password;
}
/**
/**
* @param password The mobile to set to this User object.
*/
public void setPassword(String password) {
this.password = password;
}
/**
* @return The mail of this user.
*/
public String getMail() {
return mail;
}
/**
* @param mail The mail to set to this User object.
*/
public void setMail(String mail) {
this.mail = mail;
}
/**
* @return The MailNickname of this user.
*/
public String getMailNickname() {
return mailNickname;
}
/**
* @param mail The MailNickname to set to this User object.
*/
public void setMailNickname(String mailNickname) {
this.mailNickname = mailNickname;
}
/**
* @return The jobTitle of this user.
*/
public String getJobTitle() {
return jobTitle;
}
/**
* @param jobTitle The jobTitle to set to this User object.
*/
public void setJobTitle(String jobTitle) {
this.jobTitle = jobTitle;
}
/**
* @return The givenName of this user.
*/
public String getGivenName() {
return givenName;
}
/**
* @param givenName The givenName to set to this User object.
*/
public void setGivenName(String givenName) {
this.givenName = givenName;
}
/**
* @return The facsimileTelephoneNumber of this user.
*/
public String getFacsimileTelephoneNumber() {
return facsimileTelephoneNumber;
}
/**
* @param facsimileTelephoneNumber The facsimileTelephoneNumber to set to this User object.
*/
public void setFacsimileTelephoneNumber(String facsimileTelephoneNumber) {
this.facsimileTelephoneNumber = facsimileTelephoneNumber;
}
/**
* @return The displayName of this user.
*/
public String getDisplayName() {
return displayName;
}
/**
* @param displayName The displayName to set to this User object.
*/
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
/**
* @return The dirSyncEnabled of this user.
*/
public String getDirSyncEnabled() {
return dirSyncEnabled;
}
/**
* @param dirSyncEnabled The dirSyncEnabled to set to this User object.
*/
public void setDirSyncEnabled(String dirSyncEnabled) {
this.dirSyncEnabled = dirSyncEnabled;
}
/**
* @return The department of this user.
*/
public String getDepartment() {
return department;
}
/**
* @param department The department to set to this User object.
*/
public void setDepartment(String department) {
this.department = department;
}
/**
* @return The lastDirSyncTime of this user.
*/
public String getLastDirSyncTime() {
return lastDirSyncTime;
}
/**
* @param lastDirSyncTime The lastDirSyncTime to set to this User object.
*/
public void setLastDirSyncTime(String lastDirSyncTime) {
this.lastDirSyncTime = lastDirSyncTime;
}
/**
* @return The country of this user.
*/
public String getCountry() {
return country;
}
/**
* @param country The country to set to this user.
*/
public void setCountry(String country) {
this.country = country;
}
/**
* @return The city of this user.
*/
public String getCity() {
return city;
}
/**
* @param city The city to set to this user.
*/
public void setCity(String city) {
this.city = city;
}
/**
* @return The accountEnabled attribute of this user.
*/
public String getAccountEnabled() {
return accountEnabled;
}
/**
* @param accountEnabled The accountEnabled to set to this user.
*/
public void setAccountEnabled(String accountEnabled) {
this.accountEnabled = accountEnabled;
}
public boolean isIsDeleted() {
return this.isDeleted;
}
public void setIsDeleted(boolean isDeleted) {
this.isDeleted = isDeleted;
}
@Override
public String toString() {
return new JSONObject(this).toString();
}
public String getManagerDisplayname(){
return managerDisplayname;
}
public void setManagerDisplayname(String managerDisplayname){
this.managerDisplayname = managerDisplayname;
}
}
/**
* The DirectReports class holds the essential data for a single DirectReport entry. That is,
* it holds the displayName and the objectId of the direct entry. It also provides the
* access methods to set or get the displayName and the ObjectId of this entry.
*/
//class DirectReport extends User{
//
//
private String displayName;
//
private String objectId;
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//}
/**
* Two arguments Constructor for the DirectReport class.
* @param displayName
* @param objectId
*/
public DirectReport(String displayName, String objectId){
this.displayName = displayName;
this.objectId = objectId;
}
/**
* @return The displayName of this direct report entry.
*/
public String getDisplayName() {
return displayName;
}
/**
* @return The objectId of this direct report entry.
*/
public String getObjectId() {
return objectId;
}
Step 7: Create the authentication model and controller files (for
BasicFilter)
We acknowledge that Java can be verbose, but you're almost done. Before you write the BasicFilter servlet to
handle the requests, you need to write some more helper files that the ADAL4J needs.
1. Create a file called AuthHelper.java, which will give you methods to use to determine the state of the signedin user. The methods include:
isAuthenticated(): Returns whether the user is signed in.
containsAuthenticationData(): Returns whether the token has data.
isAuthenticationSuccessful(): Returns whether the authentication was successful for the user.
To create the AuthHelper.java file, paste the following code:
package com.microsoft.aad.adal4jsample;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import
import
import
import
com.microsoft.aad.adal4j.AuthenticationResult;
com.nimbusds.openid.connect.sdk.AuthenticationResponse;
com.nimbusds.openid.connect.sdk.AuthenticationResponseParser;
com.nimbusds.openid.connect.sdk.AuthenticationSuccessResponse;
public final class AuthHelper {
public static final String PRINCIPAL_SESSION_NAME = "principal";
private AuthHelper() {
}
public static boolean isAuthenticated(HttpServletRequest request) {
return request.getSession().getAttribute(PRINCIPAL_SESSION_NAME) != null;
}
public static AuthenticationResult getAuthSessionObject(
HttpServletRequest request) {
return (AuthenticationResult) request.getSession().getAttribute(
PRINCIPAL_SESSION_NAME);
}
public static boolean containsAuthenticationData(
HttpServletRequest httpRequest) {
Map<String, String[]> map = httpRequest.getParameterMap();
return httpRequest.getMethod().equalsIgnoreCase("POST") &&
(httpRequest.getParameterMap().containsKey(
AuthParameterNames.ERROR)
|| httpRequest.getParameterMap().containsKey(
AuthParameterNames.ID_TOKEN) || httpRequest
.getParameterMap().containsKey(AuthParameterNames.CODE));
}
public static boolean isAuthenticationSuccessful(
AuthenticationResponse authResponse) {
return authResponse instanceof AuthenticationSuccessResponse;
}
}
2. Create a file called AuthParameterNames.java, which gives you some immutable variables that the ADAL4J
requires. To create the file, paste the following code:
package com.microsoft.aad.adal4jsample;
public final class AuthParameterNames {
private AuthParameterNames() {
}
public
public
public
public
public
static
static
static
static
static
String
String
String
String
String
ERROR = "error";
ERROR_DESCRIPTION = "error_description";
ERROR_URI = "error_uri";
ID_TOKEN = "id_token";
CODE = "code";
}
3. Create a file called AadController.java, which is the controller of your MVC pattern. The file gives you the JSP
controller and exposes the secure/aad URL endpoint for the app. The file also includes the graph query. To
create the file, paste the following code:
package com.microsoft.aad.adal4jsample;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import
import
import
import
import
import
org.json.JSONArray;
org.json.JSONObject;
org.springframework.stereotype.Controller;
org.springframework.ui.ModelMap;
org.springframework.web.bind.annotation.RequestMapping;
org.springframework.web.bind.annotation.RequestMethod;
import com.microsoft.aad.adal4j.AuthenticationResult;
@Controller
@RequestMapping("/secure/aad")
public class AadController {
@RequestMapping(method = { RequestMethod.GET, RequestMethod.POST })
public String getDirectoryObjects(ModelMap model, HttpServletRequest httpRequest) {
HttpSession session = httpRequest.getSession();
AuthenticationResult result = (AuthenticationResult)
session.getAttribute(AuthHelper.PRINCIPAL_SESSION_NAME);
if (result == null) {
model.addAttribute("error", new Exception("AuthenticationResult not found in session."));
return "/error";
} else {
String data;
try {
data = this.getUsernamesFromGraph(result.getAccessToken(), session.getServletContext()
.getInitParameter("tenant"));
model.addAttribute("users", data);
} catch (Exception e) {
model.addAttribute("error", e);
return "/error";
}
}
return "/secure/aad";
}
private String getUsernamesFromGraph(String accessToken, String tenant) throws Exception {
URL url = new URL(String.format("https://graph.windows.net/%s/users?api-version=2013-04-05",
tenant,
accessToken));
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// Set the appropriate header fields in the request header.
conn.setRequestProperty("api-version", "2013-04-05");
conn.setRequestProperty("Authorization", accessToken);
conn.setRequestProperty("Accept", "application/json;odata=minimalmetadata");
String goodRespStr = HttpClientHelper.getResponseStringFromConn(conn, true);
// logger.info("goodRespStr ->" + goodRespStr);
int responseCode = conn.getResponseCode();
JSONObject response = HttpClientHelper.processGoodRespStr(responseCode, goodRespStr);
JSONArray users = new JSONArray();
users = JSONHelper.fetchDirectoryObjectJSONArray(response);
StringBuilder builder = new StringBuilder();
User user = null;
for (int i = 0; i < users.length(); i++) {
JSONObject thisUserJSONObject = users.optJSONObject(i);
user = new User();
user = new User();
JSONHelper.convertJSONObjectToDirectoryObject(thisUserJSONObject, user);
builder.append(user.getUserPrincipalName() + "<br/>");
}
return builder.toString();
}
}
Step 8: Create the BasicFilter file (for BasicFilter MVC)
You can now create the BasicFilter.java file, which handles the requests from the JSP View files. To create the file,
paste the following code:
package com.microsoft.aad.adal4jsample;
import
import
import
import
import
import
import
import
import
import
import
import
java.io.IOException;
java.io.UnsupportedEncodingException;
java.net.URI;
java.net.URLEncoder;
java.util.Date;
java.util.HashMap;
java.util.Map;
java.util.UUID;
java.util.concurrent.ExecutionException;
java.util.concurrent.ExecutorService;
java.util.concurrent.Executors;
java.util.concurrent.Future;
import
import
import
import
import
import
import
import
import
javax.naming.ServiceUnavailableException;
javax.servlet.Filter;
javax.servlet.FilterChain;
javax.servlet.FilterConfig;
javax.servlet.ServletException;
javax.servlet.ServletRequest;
javax.servlet.ServletResponse;
javax.servlet.http.HttpServletRequest;
javax.servlet.http.HttpServletResponse;
import
import
import
import
import
import
import
import
com.microsoft.aad.adal4j.AuthenticationContext;
com.microsoft.aad.adal4j.AuthenticationResult;
com.microsoft.aad.adal4j.ClientCredential;
com.nimbusds.oauth2.sdk.AuthorizationCode;
com.nimbusds.openid.connect.sdk.AuthenticationErrorResponse;
com.nimbusds.openid.connect.sdk.AuthenticationResponse;
com.nimbusds.openid.connect.sdk.AuthenticationResponseParser;
com.nimbusds.openid.connect.sdk.AuthenticationSuccessResponse;
public class BasicFilter implements Filter {
private
private
private
private
String
String
String
String
clientId = "";
clientSecret = "";
tenant = "";
authority;
public void destroy() {
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
if (request instanceof HttpServletRequest) {
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
try {
try {
String currentUri = request.getScheme()
+ "://"
+ request.getServerName()
+ ("http".equals(request.getScheme())
&& request.getServerPort() == 80
|| "https".equals(request.getScheme())
&& request.getServerPort() == 443 ? "" : ":"
+ request.getServerPort())
+ httpRequest.getRequestURI();
String fullUrl = currentUri
+ (httpRequest.getQueryString() != null ? "?"
+ httpRequest.getQueryString() : "");
// check if user has a session
if (!AuthHelper.isAuthenticated(httpRequest)) {
if (AuthHelper.containsAuthenticationData(httpRequest)) {
Map<String, String> params = new HashMap<String, String>();
for (String key : request.getParameterMap().keySet()) {
params.put(key,
request.getParameterMap().get(key)[0]);
}
AuthenticationResponse authResponse = AuthenticationResponseParser
.parse(new URI(fullUrl), params);
if (AuthHelper.isAuthenticationSuccessful(authResponse)) {
AuthenticationSuccessResponse oidcResponse = (AuthenticationSuccessResponse)
authResponse;
AuthenticationResult result = getAccessToken(
oidcResponse.getAuthorizationCode(),
currentUri);
createSessionPrincipal(httpRequest, result);
} else {
AuthenticationErrorResponse oidcResponse = (AuthenticationErrorResponse)
authResponse;
throw new Exception(String.format(
"Request for auth code failed: %s - %s",
oidcResponse.getErrorObject().getCode(),
oidcResponse.getErrorObject()
.getDescription()));
}
} else {
// not authenticated
httpResponse.setStatus(302);
httpResponse
.sendRedirect(getRedirectUrl(currentUri));
return;
}
} else {
// if authenticated, how to check for valid session?
AuthenticationResult result = AuthHelper
.getAuthSessionObject(httpRequest);
if (httpRequest.getParameter("refresh") != null) {
result = getAccessTokenFromRefreshToken(
result.getRefreshToken(), currentUri);
} else {
if (httpRequest.getParameter("cc") != null) {
result = getAccessTokenFromClientCredentials();
} else {
if (result.getExpiresOnDate().before(new Date())) {
result = getAccessTokenFromRefreshToken(
result.getRefreshToken(), currentUri);
}
}
}
createSessionPrincipal(httpRequest, result);
}
} catch (Throwable exc) {
httpResponse.setStatus(500);
httpResponse.setStatus(500);
request.setAttribute("error", exc.getMessage());
httpResponse.sendRedirect(((HttpServletRequest) request)
.getContextPath() + "/error.jsp");
}
}
chain.doFilter(request, response);
}
private AuthenticationResult getAccessTokenFromClientCredentials()
throws Throwable {
AuthenticationContext context = null;
AuthenticationResult result = null;
ExecutorService service = null;
try {
service = Executors.newFixedThreadPool(1);
context = new AuthenticationContext(authority + tenant + "/", true,
service);
Future<AuthenticationResult> future = context.acquireToken(
"https://graph.windows.net", new ClientCredential(clientId,
clientSecret), null);
result = future.get();
} catch (ExecutionException e) {
throw e.getCause();
} finally {
service.shutdown();
}
if (result == null) {
throw new ServiceUnavailableException(
"authentication result was null");
}
return result;
}
private AuthenticationResult getAccessTokenFromRefreshToken(
String refreshToken, String currentUri) throws Throwable {
AuthenticationContext context = null;
AuthenticationResult result = null;
ExecutorService service = null;
try {
service = Executors.newFixedThreadPool(1);
context = new AuthenticationContext(authority + tenant + "/", true,
service);
Future<AuthenticationResult> future = context
.acquireTokenByRefreshToken(refreshToken,
new ClientCredential(clientId, clientSecret), null,
null);
result = future.get();
} catch (ExecutionException e) {
throw e.getCause();
} finally {
service.shutdown();
}
if (result == null) {
throw new ServiceUnavailableException(
"authentication result was null");
}
return result;
}
private AuthenticationResult getAccessToken(
AuthorizationCode authorizationCode, String currentUri)
throws Throwable {
String authCode = authorizationCode.getValue();
ClientCredential credential = new ClientCredential(clientId,
clientSecret);
AuthenticationContext context = null;
AuthenticationContext context = null;
AuthenticationResult result = null;
ExecutorService service = null;
try {
service = Executors.newFixedThreadPool(1);
context = new AuthenticationContext(authority + tenant + "/", true,
service);
Future<AuthenticationResult> future = context
.acquireTokenByAuthorizationCode(authCode, new URI(
currentUri), credential, null);
result = future.get();
} catch (ExecutionException e) {
throw e.getCause();
} finally {
service.shutdown();
}
if (result == null) {
throw new ServiceUnavailableException(
"authentication result was null");
}
return result;
}
private void createSessionPrincipal(HttpServletRequest httpRequest,
AuthenticationResult result) throws Exception {
httpRequest.getSession().setAttribute(
AuthHelper.PRINCIPAL_SESSION_NAME, result);
}
private String getRedirectUrl(String currentUri)
throws UnsupportedEncodingException {
String redirectUrl = authority
+ this.tenant
+ "/oauth2/authorize?
response_type=code%20id_token&scope=openid&response_mode=form_post&redirect_uri="
+ URLEncoder.encode(currentUri, "UTF-8") + "&client_id="
+ clientId + "&resource=https%3a%2f%2fgraph.windows.net"
+ "&nonce=" + UUID.randomUUID() + "&site_id=500879";
return redirectUrl;
}
public void init(FilterConfig config) throws ServletException {
clientId = config.getInitParameter("client_id");
authority = config.getServletContext().getInitParameter("authority");
tenant = config.getServletContext().getInitParameter("tenant");
clientSecret = config.getInitParameter("secret_key");
}
}
This servlet exposes all the methods that the ADAL4J will expect from the app to run. The methods include:
getAccessTokenFromClientCredentials(): Gets the access token from the secret.
getAccessTokenFromRefreshToken(): Gets the access token from a refresh token.
getAccessToken(): Gets the access token from an OpenID Connect flow (which you use).
createSessionPrincipal(): Creates a session principal to use for Graph API access.
getRedirectUrl(): Gets the redirectURL to compare it with the value you entered in the portal.
Step 9: Compile and run the sample in Tomcat
1. Change to your root directory.
2. To build the sample you just put together by using
maven
, run the following command:
$ mvn package
This command uses the pom.xml file that you wrote for dependencies.
You should now have a adal4jsample.war file in your /targets directory. You can deploy the file in your Tomcat
container and visit the http://localhost:8080/adal4jsample/ URL.
NOTE
You can easily deploy a .war file with the latest Tomcat servers. Go to http://localhost:8080/manager/, and follow the
instructions for uploading the adal4jsample.war file. It will autodeploy for you with the correct endpoint.
Next steps
You now have a working Java app that can authenticate users, securely call web APIs using OAuth 2.0, and get
basic information about the users. If you haven't already populated your tenant with users, now is a good time to
do so.
For additional reference, you can get the completed sample (without your configuration values) in either of two
ways:
Download it as a .zip file.
Clone the file from GitHub by entering the following command:
git clone --branch complete https://github.com/Azure-Samples/active-directory-java-webappopenidconnect.git
Node.js web app sign-in and sign-out with Azure AD
4/19/2017 • 10 min to read • Edit Online
Here we use Passport to:
Sign the user in to the app with Azure Active Directory (Azure AD).
Display information about the user.
Sign the user out of the app.
Passport is authentication middleware for Node.js. Flexible and modular, Passport can be unobtrusively dropped in
to any Express-based or restify web application. A comprehensive set of strategies support authentication that uses
a username and password, Facebook, Twitter, and more. We have developed a strategy for Microsoft Azure Active
Directory. We install this module and then add the Microsoft Azure Active Directory passport-azure-ad plug-in.
To do this, take the following steps:
1.
2.
3.
4.
Register an app.
Set up your app to use the passport-azure-ad strategy.
Use Passport to issue sign-in and sign-out requests to Azure AD.
Print data about the user.
The code for this tutorial is maintained on GitHub. To follow along, you can download the app's skeleton as a .zip
file or clone the skeleton:
git clone --branch skeleton https://github.com/AzureADQuickStarts/WebApp-OpenIDConnect-NodeJS.git
The completed application is provided at the end of this tutorial as well.
Step 1: Register an app
1. Sign in to the Azure portal.
2. In the menu at the top of the page, select your account. Under the Directory list, choose the Active Directory
tenant where you want to register your application.
3. Select More Services in the menu on the left side of the screen, and then select Azure Active Directory.
4. Select App registrations, and then select Add.
5. Follow the prompts to create a Web Application and/or WebAPI.
The name of the application describes your application to users.
The Sign-On URL is the base URL of your app. The skeleton's default is
`http://localhost:3000/auth/openid/return``.
6. After you register, Azure AD assigns your app a unique application ID. You need this value in the following
sections, so copy it from the application page.
7. From the Settings -> Properties page for your application, update the App ID URI. The App ID URI is a unique
identifier for your application. The convention is to use the format https://<tenant-domain>/<app-name> , for
example: https://contoso.onmicrosoft.com/my-first-aad-app .
Step 2: Add prerequisites to your directory
1. From the command line, change directories to your root folder if you're not already there, and then run the
following commands:
npm install express
npm install ejs
npm install ejs-locals
npm install restify
npm install mongoose
npm install bunyan
npm install assert-plus
npm install passport
2. In addition, you need
passport-azure-ad
:
npm install passport-azure-ad
This installs the libraries that
passport-azure-ad
depends on.
Step 3: Set up your app to use the passport-node-js strategy
Here, we configure Express to use the OpenID Connect authentication protocol. Passport is used to do various
things, including issue sign-in and sign-out requests, manage the user's session, and get information about the
user.
1. To begin, open the config.js file at the root of the project, and then enter your app's configuration values
in the exports.creds section.
The
clientID
is the Application Id that's assigned to your app in the registration portal.
The
returnURL
The
clientSecret
is the Redirect Uri that you entered in the portal.
is the secret that you generated in the portal.
2. Next, open the app.js file in the root of the project. Then add the following call to invoke the
strategy that comes with passport-azure-ad .
var OIDCStrategy = require('passport-azure-ad').OIDCStrategy;
// add a logger
var log = bunyan.createLogger({
name: 'Microsoft OIDC Example Web Application'
});
3. After that, use the strategy we just referenced to handle our sign-in requests.
OIDCStrategy
// Use the OIDCStrategy within Passport. (Section 2)
//
// Strategies in passport require a `validate` function that accepts
// credentials (in this case, an OpenID identifier), and invokes a callback
// with a user object.
passport.use(new OIDCStrategy({
callbackURL: config.creds.returnURL,
realm: config.creds.realm,
clientID: config.creds.clientID,
clientSecret: config.creds.clientSecret,
oidcIssuer: config.creds.issuer,
identityMetadata: config.creds.identityMetadata,
skipUserProfile: config.creds.skipUserProfile,
responseType: config.creds.responseType,
responseMode: config.creds.responseMode
},
function(iss, sub, profile, accessToken, refreshToken, done) {
if (!profile.email) {
return done(new Error("No email found"), null);
}
// asynchronous verification, for effect...
process.nextTick(function () {
findByEmail(profile.email, function(err, user) {
if (err) {
return done(err);
}
if (!user) {
// "Auto-registration"
users.push(profile);
return done(null, profile);
}
return done(null, user);
});
});
}
));
Passport uses a similar pattern for all its strategies (Twitter, Facebook, and so on) that all strategy writers
adhere to. Looking at the strategy, you see that we pass it a function that has a token and a done as the
parameters. The strategy comes back to us after it does its work. Then we want to store the user and stash
the token so we don't need to ask for it again.
IMPORTANT
The previous code takes any user that happens to authenticate to our server. This is known as auto-registration. We
recommend that you don't let anyone authenticate to a production server without first having them register via a
process that you decide on. This is usually the pattern you see in consumer apps, which allow you to register with
Facebook but then ask you to provide additional information. If this weren't a sample application, we could have
extracted the user's email address from the token object that is returned and then asked the user to fill out additional
information. Because this is a test server, we add them to the in-memory database.
4. Next, let's add the methods that enable us to track the signed-in users as required by Passport. These
methods include serializing and deserializing the user's information.
// Passport session setup. (Section 2)
// To support persistent sign-in sessions, Passport needs to be able to
// serialize users into the session and deserialize them out of the session. Typically,
// this is done simply by storing the user ID when serializing and finding
// the user by ID when deserializing.
passport.serializeUser(function(user, done) {
done(null, user.email);
});
passport.deserializeUser(function(id, done) {
findByEmail(id, function (err, user) {
done(err, user);
});
});
// array to hold signed-in users
var users = [];
var findByEmail = function(email, fn) {
for (var i = 0, len = users.length; i < len; i++) {
var user = users[i];
log.info('we are using user: ', user);
if (user.email === email) {
return fn(null, user);
}
}
return fn(null, null);
};
5. Next, let's add the code to load the Express engine. Here we use the default /views and /routes pattern that
Express provides.
// configure Express (section 2)
var app = express();
app.configure(function() {
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.logger());
app.use(express.methodOverride());
app.use(cookieParser());
app.use(expressSession({ secret: 'keyboard cat', resave: true, saveUninitialized: false }));
app.use(bodyParser.urlencoded({ extended : true }));
// Initialize Passport! Also use passport.session() middleware, to support
// persistent login sessions (recommended).
app.use(passport.initialize());
app.use(passport.session());
app.use(app.router);
app.use(express.static(__dirname + '/../../public'));
});
6. Finally, let's add the routes that hand off the actual sign-in requests to the
passport-azure-ad
engine:
```JavaScript
// Our Auth routes (section 3)
// GET /auth/openid
// Use passport.authenticate() as route middleware to authenticate the
// request. The first step in OpenID authentication involves redirecting
// the user to their OpenID provider. After authenticating, the OpenID
// provider redirects the user back to this application at
// /auth/openid/return.
app.get('/auth/openid',
passport.authenticate('azuread-openidconnect', { failureRedirect: '/login' }),
function(req, res) {
log.info('Authentication was called in the Sample');
res.redirect('/');
});
// GET /auth/openid/return
// Use passport.authenticate() as route middleware to authenticate the
// request. If authentication fails, the user is redirected back to the
// sign-in page. Otherwise, the primary route function is called,
// which, in this example, redirects the user to the home page.
app.get('/auth/openid/return',
passport.authenticate('azuread-openidconnect', { failureRedirect: '/login' }),
function(req, res) {
log.info('We received a return from AzureAD.');
res.redirect('/');
});
// POST /auth/openid/return
// Use passport.authenticate() as route middleware to authenticate the
// request. If authentication fails, the user is redirected back to the
// sign-in page. Otherwise, the primary route function is called,
// which, in this example, redirects the user to the home page.
app.post('/auth/openid/return',
passport.authenticate('azuread-openidconnect', { failureRedirect: '/login' }),
function(req, res) {
log.info('We received a return from AzureAD.');
res.redirect('/');
});
```
Step 4: Use Passport to issue sign-in and sign-out requests to Azure
AD
Your app is now properly configured to communicate with the endpoint by using the OpenID Connect
authentication protocol. passport-azure-ad has taken care of all the details of crafting authentication messages,
validating tokens from Azure AD, and maintaining user sessions. All that remains is giving your users a way to sign
in and sign out, and gathering additional information about the signed-in users.
1. First, let's add the default, sign-in, account, and sign-out methods to our
app.js
file:
//Routes (section 4)
app.get('/', function(req, res){
res.render('index', { user: req.user });
});
app.get('/account', ensureAuthenticated, function(req, res){
res.render('account', { user: req.user });
});
app.get('/login',
passport.authenticate('azuread-openidconnect', { failureRedirect: '/login' }),
function(req, res) {
log.info('Login was called in the Sample');
res.redirect('/');
});
app.get('/logout', function(req, res){
req.logout();
res.redirect('/');
});
2. Let's review these in detail:
The / route redirects to the index.ejs view, passing the user in the request (if it exists).
The /account route first ensures we are authenticated (we implement that in the following example),
and then passes the user in the request so that we can get additional information about the user.
The /login route calls our azuread-openidconnect authenticator from passport-azuread . If that doesn't
succeed, it redirects the user back to /login.
The /logout route simply calls the logout.ejs (and route), which clears cookies and then returns the user
back to index.ejs.
3. For the last part of app.js , let's add the EnsureAuthenticated method that is used in /account , as shown
earlier.
// Simple route middleware to ensure user is authenticated. (section 4)
// Use this route middleware on any resource that needs to be protected. If
// the request is authenticated (typically via a persistent sign-in session),
// the request proceeds. Otherwise, the user is redirected to the
// sign-in page.
function ensureAuthenticated(req, res, next) {
if (req.isAuthenticated()) { return next(); }
res.redirect('/login')
}
4. Finally, let's create the server itself in
app.js
:
app.listen(3000);
Step 5: To display our user in the website, create the views and routes
in Express
Now app.js is complete. We simply need to add the routes and views that show the information we get to the
user, as well as handle the /logout and /login routes that we created.
1. Create the
/routes/index.js
route under the root directory.
/*
* GET home page.
*/
exports.index = function(req, res){
res.render('index', { title: 'Express' });
};
2. Create the
/routes/user.js
route under the root directory.
```JavaScript
/*
* GET users listing.
*/
exports.list = function(req, res){
res.send("respond with a resource");
};
```
These pass along the request to our views, including the user if present.
3. Create the /views/index.ejs view under the root directory. This is a simple page that calls our login and
logout methods and enables us to grab account information. Notice that we can use the conditional
if (!user) as the user being passed through in the request is evidence we have a signed-in user.
<% if (!user) { %>
<h2>Welcome! Please log in.</h2>
<a href="/login">Log In</a>
<% } else { %>
<h2>Hello, <%= user.displayName %>.</h2>
<a href="/account">Account Info</a></br>
<a href="/logout">Log Out</a>
<% } %>
4. Create the
view under the root directory so that we can view additional information that
has put in the user request.
/views/account.ejs
passport-azuread
<% if (!user) { %>
<h2>Welcome! Please log in.</h2>
<a href="/login">Log In</a>
<% } else { %>
<p>displayName: <%= user.displayName %></p>
<p>givenName: <%= user.name.givenName %></p>
<p>familyName: <%= user.name.familyName %></p>
<p>UPN: <%= user._json.upn %></p>
<p>Profile ID: <%= user.id %></p>
##Next steps <p>Full Claimes</p>
<%- JSON.stringify(user) %>
<p></p>
<a href="/logout">Log Out</a>
<% } %>
5. Let's make this look good by adding a layout. Create the '/views/layout.ejs' view under the root directory.
<!DOCTYPE html>
<html>
<head>
<title>Passport-OpenID Example</title>
</head>
<body>
<% if (!user) { %>
<p>
<a href="/">Home</a> |
<a href="/login">Log In</a>
</p>
<% } else { %>
<p>
<a href="/">Home</a> |
<a href="/account">Account</a> |
<a href="/logout">Log Out</a>
</p>
<% } %>
<%- body %>
</body>
</html>
Next steps
Finally, build and run your app. Run
node app.js
, and then go to
http://localhost:3000
.
Sign in with either a personal Microsoft account or a work or school account, and notice how the user's identity is
reflected in the /account list. You now have a web app that's secured with industry standard protocols that can
authenticate users with both their personal and work/school accounts.
For reference, the completed sample (without your configuration values) is provided as a .zip file. Alternatively, you
can clone it from GitHub:
git clone --branch complete https://github.com/AzureADQuickStarts/WebApp-OpenIDConnect-NodeJS.git
You can now move onto more advanced topics. You might want to try:
Secure a Web API with Azure AD
Additional resources
The Azure AD developer's guide
Azure AD samples on GitHub
CloudIdentity.com
Get security updates for our products
We encourage you to get notifications of when security incidents occur by visiting the TechCenter page for
Microsoft technical security notifications and subscribing to security advisory alerts.
Authorize access to web applications using OpenID
Connect and Azure Active Directory
2/23/2017 • 11 min to read • Edit Online
OpenID Connect is a simple identity layer built on top of the OAuth 2.0 protocol. OAuth 2.0 defines mechanisms to
obtain and use access tokens to access protected resources, but they do not define standard methods to provide
identity information. OpenID Connect implements authentication as an extension to the OAuth 2.0 authorization
process. It provides information about the end user in the form of an id_token that verifies the identity of the user
and provides basic profile information about the user.
OpenID Connect is our recommendation if you are building a web application that is hosted on a server and
accessed via a browser.
Register your application with your AD tenant
First, you will need to register your application with your Azure Active Directory (Azure AD) tenant. This will give
you an Application ID for your application, as well as enable it to receive tokens.
Sign in to the Azure Portal.
Choose your Azure AD tenant by clicking on your account in the top right corner of the page.
In the left hand navigation pane, click on Azure Active Directory.
Click on App Registrations and click on Add.
Follow the prompts and create a new application. It doesn't matter if it is a web application or a native
application for this tutorial, but if you'd like specific examples for web applications or native applications, check
out our quickstarts.
For Web Applications, provide the Sign-On URL which is the base URL of your app, where users can sign
in e.g http://localhost:12345 .
For Native Applications, provide a Redirect URI, which Azure AD will use to return token responses. Enter
a value specific to your application, .e.g http://MyFirstAADApp
Once you've completed registration, Azure AD will assign your application a unique client identifier, the
Application ID. You will need this value in the next sections, so copy it from the application page.
Authentication flow using OpenID Connect
The most basic sign-in flow contains the following steps - each of them is described in detail below.
OpenID Connect metadata document
OpenID Connect describes a metadata document that contains most of the information required for an app to
perform sign-in. This includes information such as the URLs to use and the location of the service's public signing
keys. The OpenID Connect metadata document can be found at:
https://login.microsoftonline.com/{tenant}/.well-known/openid-configuration
The metadata is a simple JavaScript Object Notation (JSON) document. See the following snippet for an example.
The snippet's contents are fully described in the OpenID Connect specification.
{
"authorization_endpoint": "https://login.microsoftonline.com/common/oauth2/authorize",
"token_endpoint": "https://login.microsoftonline.com/common/oauth2/token",
"token_endpoint_auth_methods_supported":
[
"client_secret_post",
"private_key_jwt"
],
"jwks_uri": "https://login.microsoftonline.com/common/discovery/keys"
...
}
Send the sign-in request
When your web application needs to authenticate the user, it must direct the user to the /authorize endpoint. This
request is similar to the first leg of the OAuth 2.0 Authorization Code Flow, with a few important distinctions:
The request must include the scope openid in the scope parameter.
The response_type parameter must include id_token .
The request must include the nonce parameter.
So a sample request would look like this:
// Line breaks for legibility only
GET https://login.microsoftonline.com/{tenant}/oauth2/authorize?
client_id=6731de76-14a6-49ae-97bc-6eba6914391e
&response_type=id_token
&redirect_uri=http%3A%2F%2Flocalhost%2Fmyapp%2F
&response_mode=form_post
&scope=openid
&state=12345
&nonce=7362CAEA-9CA5-4B43-9BA3-34D7C303EBA7
PARAMETER
DESCRIPTION
tenant
required
The {tenant} value in the path of the
request can be used to control who can
sign into the application. The allowed
values are tenant identifiers, for
example,
8eaef023-2b34-4da1-9baa-8bc8c9d6a490 or
contoso.onmicrosoft.com or common for
tenant-independent tokens
client_id
required
The Application Id assigned to your app
when you registered it with Azure AD.
You can find this in the Azure Portal.
Click Azure Active Directory, click
App Registrations, choose the
application and locate the Application Id
on the application page.
response_type
required
Must include id_token for OpenID
Connect sign-in. It may also include
other response_types, such as code .
PARAMETER
DESCRIPTION
scope
required
A space-separated list of scopes. For
OpenID Connect, it must include the
scope openid , which translates to the
"Sign you in" permission in the consent
UI. You may also include other scopes in
this request for requesting consent.
nonce
required
A value included in the request,
generated by the app, that is included in
the resulting id_token as a claim. The
app can then verify this value to
mitigate token replay attacks. The value
is typically a randomized, unique string
or GUID that can be used to identify the
origin of the request.
redirect_uri
recommended
The redirect_uri of your app, where
authentication responses can be sent
and received by your app. It must
exactly match one of the redirect_uris
you registered in the portal, except it
must be url encoded.
response_mode
recommended
Specifies the method that should be
used to send the resulting
authorization_code back to your app.
Supported values are form_post for
HTTP form post or fragment for URL
fragment. For web applications, we
recommend using
response_mode=form_post to ensure the
most secure transfer of tokens to your
application.
state
recommended
A value included in the request that is
returned in the token response. It can
be a string of any content that you
wish. A randomly generated unique
value is typically used for preventing
cross-site request forgery attacks. The
state is also used to encode information
about the user's state in the app before
the authentication request occurred,
such as the page or view they were on.
PARAMETER
DESCRIPTION
prompt
optional
Indicates the type of user interaction
that is required. Currently, the only valid
values are 'login', 'none', and 'consent'.
prompt=login forces the user to enter
their credentials on that request,
negating single-sign on. prompt=none is
the opposite - it ensures that the user is
not presented with any interactive
prompt whatsoever. If the request
cannot be completed silently via singlesign on, the endpoint returns an error.
prompt=consent triggers the OAuth
consent dialog after the user signs in,
asking the user to grant permissions to
the app.
login_hint
optional
Can be used to pre-fill the
username/email address field of the
sign-in page for the user, if you know
their username ahead of time. Often
apps use this parameter during
reauthentication, having already
extracted the username from a previous
sign-in using the preferred_username
claim.
At this point, the user is asked to enter their credentials and complete the authentication.
Sample response
A sample response, after the user has authenticated, could look like this:
POST /myapp/ HTTP/1.1
Host: localhost
Content-Type: application/x-www-form-urlencoded
id_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik1uQ19WWmNB...&state=12345
PARAMETER
DESCRIPTION
id_token
The
id_token that the app requested. You can use the
id_token to verify the user's identity and begin a session with
the user.
state
Error response
Error responses may also be sent to the
A value included in the request that is also returned in the
token response. A randomly generated unique value is
typically used for preventing cross-site request forgery attacks.
The state is also used to encode information about the user's
state in the app before the authentication request occurred,
such as the page or view they were on.
redirect_uri
so the app can handle them appropriately:
POST /myapp/ HTTP/1.1
Host: localhost
Content-Type: application/x-www-form-urlencoded
error=access_denied&error_description=the+user+canceled+the+authentication
PARAMETER
DESCRIPTION
error
An error code string that can be used to classify types of
errors that occur, and can be used to react to errors.
error_description
A specific error message that can help a developer identify the
root cause of an authentication error.
Error codes for authorization endpoint errors
The following table describes the various error codes that can be returned in the
response.
error
parameter of the error
ERROR CODE
DESCRIPTION
CLIENT ACTION
invalid_request
Protocol error, such as a missing
required parameter.
Fix and resubmit the request. This is a
development error, and is typically
caught during initial testing.
unauthorized_client
The client application is not permitted to
request an authorization code.
This usually occurs when the client
application is not registered in Azure AD
or is not added to the user's Azure AD
tenant. The application can prompt the
user with instruction for installing the
application and adding it to Azure AD.
access_denied
Resource owner denied consent
The client application can notify the user
that it cannot proceed unless the user
consents.
unsupported_response_type
The authorization server does not
support the response type in the
request.
Fix and resubmit the request. This is a
development error, and is typically
caught during initial testing.
server_error
The server encountered an unexpected
error.
Retry the request. These errors can
result from temporary conditions. The
client application might explain to the
user that its response is delayed due to
a temporary error.
temporarily_unavailable
The server is temporarily too busy to
handle the request.
Retry the request. The client application
might explain to the user that its
response is delayed due to a temporary
condition.
invalid_resource
The target resource is invalid because it
does not exist, Azure AD cannot find it,
or it is not correctly configured.
This indicates the resource, if it exists,
has not been configured in the tenant.
The application can prompt the user
with instruction for installing the
application and adding it to Azure AD.
Validate the id_token
Just receiving an id_token is not sufficient to authenticate the user; you must validate the signature and verify the
claims in the id_token per your app's requirements. The Azure AD endpoint uses JSON Web Tokens (JWTs) and
public key cryptography to sign tokens and verify that they are valid.
You can choose to validate the id_token in client code, but a common practice is to send the id_token to a
backend server and perform the validation there. Once you've validated the signature of the id_token , there are a
few claims you are required to verify.
You may also wish to validate additional claims depending on your scenario. Some common validations include:
Ensuring the user/organization has signed up for the app.
Ensuring the user has proper authorization/privileges
Ensuring a certain strength of authentication has occurred, such as multi-factor authentication.
Once you have validated the id_token , you can begin a session with the user and use the claims in the id_token to
obtain information about the user in your app. This information can be used for display, records, authorizations, etc.
For more information about the token types and claims, read Supported Token and Claim Types.
Send a sign-out request
When you wish to sign the user out of the app, it is not sufficient to clear your app's cookies or otherwise end the
session with the user. You must also redirect the user to the end_session_endpoint for sign-out. If you fail to do so,
the user will be able to reauthenticate to your app without entering their credentials again, because they will have a
valid single sign-on session with the Azure AD endpoint.
You can simply redirect the user to the
end_session_endpoint
listed in the OpenID Connect metadata document:
GET https://login.microsoftonline.com/common/oauth2/logout?
post_logout_redirect_uri=http%3A%2F%2Flocalhost%2Fmyapp%2F
PARAMETER
post_logout_redirect_uri
DESCRIPTION
recommended
The URL that the user should be
redirected to after successful logout. If
not included, the user is shown a
generic message.
Single sign-out
When you redirect the user to the end_session_endpoint , Azure AD clears the user's session from the browser.
However, the user may still be signed in to other applications that use Azure AD for authentication. To enable those
applications to sign the user out simultaneously, Azure AD sends an HTTP GET request to the registered LogoutUrl
of all the applications that the user is currently signed in to. Applications must respond to this request by clearing
any session that identifies the user and returning a 200 response. If you wish to support single sign out in your
application, you must implement such a LogoutUrl in your application's code. You can set the LogoutUrl from the
Azure portal:
1. Navigate to the Azure Portal.
2. Choose your Active Directory by clicking on your account in the top right corner of the page.
3. From the left hand navigation panel, choose Azure Active Directory, then choose App registrations and select
your application.
4. Click on Properties and find the Logout URL text box.
Token Acquisition
Many web apps need to not only sign the user in, but also access a web service on behalf of that user using OAuth.
This scenario combines OpenID Connect for user authentication while simultaneously acquiring an
authorization_code that can be used to get access_tokens using the OAuth Authorization Code Flow.
Get Access Tokens
To acquire access tokens, you need to modify the sign-in request from above:
// Line breaks for legibility only
GET https://login.microsoftonline.com/{tenant}/oauth2/authorize?
client_id=6731de76-14a6-49ae-97bc-6eba6914391e
// Your registered Application Id
&response_type=id_token+code
&redirect_uri=http%3A%2F%2Flocalhost%2Fmyapp%2F
// Your registered Redirect Uri, url encoded
&response_mode=form_post
// form_post', or 'fragment'
&scope=openid
&resource=https%3A%2F%2Fservice.contoso.com%2F
&state=12345
// Any value, provided by your app
&nonce=678910
// Any value, provided by your app
By including permission scopes in the request and using response_type=code+id_token , the authorize endpoint
ensures that the user has consented to the permissions indicated in the scope query parameter, and return your
app an authorization code to exchange for an access token.
Successful Response
A successful response using
response_mode=form_post
looks like:
POST /myapp/ HTTP/1.1
Host: localhost
Content-Type: application/x-www-form-urlencoded
id_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik1uQ19WWmNB...&code=AwABAAAAvPM1KaPlrEqdFSBzjqfTGBCmLdgfS
TLEMPGYuNHSUYBrq...&state=12345
PARAMETER
DESCRIPTION
id_token
The
id_token that the app requested. You can use the
id_token to verify the user's identity and begin a session with
the user.
code
The authorization_code that the app requested. The app can
use the authorization code to request an access token for the
target resource. Authorization_codes are short lived, and
typically expire after about 10 minutes.
state
If a state parameter is included in the request, the same value
should appear in the response. The app should verify that the
state values in the request and response are identical.
Error response
Error responses may also be sent to the
redirect_uri
so the app can handle them appropriately:
POST /myapp/ HTTP/1.1
Host: localhost
Content-Type: application/x-www-form-urlencoded
error=access_denied&error_description=the+user+canceled+the+authentication
PARAMETER
DESCRIPTION
error
An error code string that can be used to classify types of
errors that occur, and can be used to react to errors.
error_description
A specific error message that can help a developer identify the
root cause of an authentication error.
For a description of the possible error codes and their recommended client action, see Error codes for authorization
endpoint errors.
Once you've gotten an authorization code and an id_token , you can sign the user in and get access tokens on
their behalf. To sign the user in, you must validate the id_token exactly as described above. To get access tokens,
you can follow the steps described in the "Use the authorization code to request an access token" section of our
OAuth protocol documentation.
Authentication Scenarios for Azure AD
4/27/2017 • 31 min to read • Edit Online
Azure Active Directory (Azure AD) simplifies authentication for developers by providing identity as a service, with
support for industry-standard protocols such as OAuth 2.0 and OpenID Connect, as well as open source libraries for
different platforms to help you start coding quickly. This document will help you understand the various scenarios
Azure AD supports and will show you how to get started. It’s divided into the following sections:
Basics of Authentication in Azure AD
Claims in Azure AD Security Tokens
Basics of Registering an Application in Azure AD
Application Types and Scenarios
Web Browser to Web Application
Single Page Application (SPA)
Native Application to Web API
Web Application to Web API
Daemon or Server Application to Web API
Basics of Authentication in Azure AD
If you are unfamiliar with basic concepts of authentication in Azure AD, read this section. Otherwise, you may want
to skip down to Application Types and Scenarios.
Let’s consider the most basic scenario where identity is required: a user in a web browser needs to authenticate to a
web application. This scenario is described in greater detail in the Web Browser to Web Application section, but it’s
a useful starting point to illustrate the capabilities of Azure AD and conceptualize how the scenario works. Consider
the following diagram for this scenario:
With the diagram above in mind, here’s what you need to know about its various components:
Azure AD is the identity provider, responsible for verifying the identity of users and applications that exist in an
organization’s directory, and ultimately issuing security tokens upon successful authentication of those users
and applications.
An application that wants to outsource authentication to Azure AD must be registered in Azure AD, which
registers and uniquely identifies the app in the directory.
Developers can use the open source Azure AD authentication libraries to make authentication easy by handling
the protocol details for you. See Azure Active Directory Authentication Libraries for more information.
• Once a user has been authenticated, the application must validate the user’s security token to ensure that
authentication was successful for the intended parties. Developers can use the provided authentication libraries to
handle validation of any token from Azure AD, including JSON Web Tokens (JWT) or SAML 2.0. If you want to
perform validation manually, see the JWT Token Handler documentation.
IMPORTANT
Azure AD uses public key cryptography to sign tokens and verify that they are valid. See Important Information About
Signing Key Rollover in Azure AD for more information on the necessary logic you must have in your application to ensure it’s
always updated with the latest keys.
• The flow of requests and responses for the authentication process is determined by the authentication protocol
that was used, such as OAuth 2.0, OpenID Connect, WS-Federation, or SAML 2.0. These protocols are discussed in
more detail in the Azure Active Directory Authentication Protocols topic and in the sections below.
NOTE
Azure AD supports the OAuth 2.0 and OpenID Connect standards that make extensive use of bearer tokens, including bearer
tokens represented as JWTs. A bearer token is a lightweight security token that grants the “bearer” access to a protected
resource. In this sense, the “bearer” is any party that can present the token. Though a party must first authenticate with Azure
AD to receive the bearer token, if the required steps are not taken to secure the token in transmission and storage, it can be
intercepted and used by an unintended party. While some security tokens have a built-in mechanism for preventing
unauthorized parties from using them, bearer tokens do not have this mechanism and must be transported in a secure
channel such as transport layer security (HTTPS). If a bearer token is transmitted in the clear, a man-in the middle attack can
be used by a malicious party to acquire the token and use it for an unauthorized access to a protected resource. The same
security principles apply when storing or caching bearer tokens for later use. Always ensure that your application transmits
and stores bearer tokens in a secure manner. For more security considerations on bearer tokens, see RFC 6750 Section 5.
Now that you have an overview of the basics, read the sections below to understand how provisioning works in
Azure AD and the common scenarios Azure AD supports.
Claims in Azure AD Security Tokens
Security tokens issued by Azure AD contain claims, or assertions of information about the subject that has been
authenticated. These claims can be used by the application for various tasks. For example, they can be used to
validate the token, identify the subject's directory tenant, display user information, determine the subject's
authorization, and so on. The claims present in any given security token are dependent upon the type of token, the
type of credential used to authenticate the user, and the application configuration. A brief description of each type
of claim emitted by Azure AD is provided in the table below. For more information, refer to Supported Token and
Claim Types.
CLAIM
DESCRIPTION
Application ID
Identifies the application that is using the token.
Audience
Identifies the recipient resource the token is intended for.
Application Authentication Context Class Reference
Indicates how the client was authenticated (public client vs.
confidential client).
Authentication Instant
Records the date and time when the authentication occurred.
CLAIM
DESCRIPTION
Authentication Method
Indicates how the subject of the token was authenticated
(password, certificate, etc.).
First Name
Provides the given name of the user as set in Azure AD.
Groups
Contains object Ids of Azure AD groups the user is a member
of.
Identity Provider
Records the identity provider that authenticated the subject of
the token.
Issued At
Records the time at which the token was issued, often used for
token freshness.
Issuer
Identifies the STS that emitted the token as well as the Azure
AD tenant.
Last Name
Provides the surname of the user as set in Azure AD.
Name
Provides a human readable value that identifies the subject of
the token.
Object Id
Contains an immutable, unique identifier of the subject in
Azure AD.
Roles
Contains friendly names of Azure AD Application Roles that
the user has been granted.
Scope
Indicates the permissions granted to the client application.
Subject
Indicates the principal about which the token asserts
information.
Tenant Id
Contains an immutable, unique identifier of the directory
tenant that issued the token.
Token Lifetime
Defines the time interval within which a token is valid.
User Principal Name
Contains the user principal name of the subject.
Version
Contains the version number of the token.
Basics of Registering an Application in Azure AD
Any application that outsources authentication to Azure AD must be registered in a directory. This step involves
telling Azure AD about your application, including the URL where it’s located, the URL to send replies after
authentication, the URI to identify your application, and more. This information is required for a few key reasons:
Azure AD needs coordinates to communicate with the application when handling sign-on or exchanging
tokens. These include the following:
Application ID URI: The identifier for an application. This value is sent to Azure AD during authentication
to indicate which application the caller wants a token for. Additionally, this value is included in the token
so that the application knows it was the intended target.
Reply URL and Redirect URI: In the case of a web API or web application, the Reply URL is the location to
which Azure AD will send the authentication response, including a token if authentication was successful.
In the case of a native application, the Redirect URI is a unique identifier to which Azure AD will redirect
the user-agent in an OAuth 2.0 request.
Application ID: The ID for an application, which is generated by Azure AD when the application is
registered. When requesting an authorization code or token, the Application ID and key are sent to Azure
AD during authentication.
Key: The key that is sent along with a Application ID when authenticating to Azure AD to call a web API.
Azure AD needs to ensure the application has the required permissions to access your directory data, other
applications in your organization, and so on
Provisioning becomes clearer when you understand that there are two categories of applications that can be
developed and integrated with Azure AD:
Single tenant application: A single tenant application is intended for use in one organization. These are typically
line-of-business (LoB) applications written by an enterprise developer. A single tenant application only needs to
be accessed by users in one directory, and as a result, it only needs to be provisioned in one directory. These
applications are typically registered by a developer in the organization.
Multi-tenant application: A multi-tenant application is intended for use in many organizations, not just one
organization. These are typically software-as-a-service (SaaS) applications written by an independent software
vendor (ISV). Multi-tenant applications need to be provisioned in each directory where they will be used, which
requires user or administrator consent to register them. This consent process starts when an application has
been registered in the directory and is given access to the Graph API or perhaps another web API. When a user
or administrator from a different organization signs up to use the application, they are presented with a dialog
that displays the permissions the application requires. The user or administrator can then consent to the
application, which gives the application access to the stated data, and finally registers the application in their
directory. For more information, see Overview of the Consent Framework.
Some additional considerations arise when developing a multi-tenant application instead of a single tenant
application. For example, if you are making your application available to users in multiple directories, you need a
mechanism to determine which tenant they’re in. A single tenant application only needs to look in its own directory
for a user, while a multi-tenant application needs to identify a specific user from all the directories in Azure AD. To
accomplish this task, Azure AD provides a common authentication endpoint where any multi-tenant application can
direct sign-in requests, instead of a tenant-specific endpoint. This endpoint is
https://login.microsoftonline.com/common for all directories in Azure AD, whereas a tenant-specific endpoint might
be https://login.microsoftonline.com/contoso.onmicrosoft.com. The common endpoint is especially important to
consider when developing your application because you’ll need the necessary logic to handle multiple tenants
during sign-in, sign-out, and token validation.
If you are currently developing a single tenant application but want to make it available to many organizations, you
can easily make changes to the application and its configuration in Azure AD to make it multi-tenant capable. In
addition, Azure AD uses the same signing key for all tokens in all directories, whether you are providing
authentication in a single tenant or multi-tenant application.
Each scenario listed in this document includes a sub-section that describes its provisioning requirements. For more
in-depth information about provisioning an application in Azure AD and the differences between single and multitenant applications, see Integrating Applications with Azure Active Directory for more information. Continue
reading to understand the common application scenarios in Azure AD.
Application Types and Scenarios
Each of the scenarios described in this document can be developed using various languages and platforms. They
are all backed by complete code samples which are available in our Code Samples guide, or directly from the
corresponding GitHub sample repositories. In addition, if your application needs a specific piece or segment of an
end-to-end scenario, in most cases that functionality can be added independently. For example, if you have a native
application that calls a web API, you can easily add a web application that also calls the web API. The following
diagram illustrates these scenarios and application types, and how different components can be added:
These are the five primary application scenarios 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 user needs to sign in to a single page application that is secured by Azure AD.
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.
Web Browser to Web Application
This section describes an application that authenticates a user in a web browser to a web application. In this
scenario, the web application directs the user’s browser to sign them in to Azure AD. Azure AD returns a sign-in
response through the user’s browser, which contains claims about the user in a security token. This scenario
supports sign-on using the WS-Federation, SAML 2.0, and OpenID Connect protocols.
Diagram
Description of Protocol Flow
1. When a user visits the application and needs to sign in, they are redirected via a sign-in request to the
authentication endpoint in Azure AD.
2. The user signs in on the sign-in page.
3. If authentication is successful, Azure AD creates an authentication token and returns a sign-in response to the
application’s Reply URL that was configured in the Azure Portal. For a production application, this Reply URL
should be HTTPS. The returned token includes claims about the user and Azure AD that are required by the
application to validate the token.
4. The application validates the token by using a public signing key and issuer information available at the
federation metadata document for Azure AD. After the application validates the token, Azure AD starts a new
session with the user. This session allows the user to access the application until it expires.
Code Samples
See the code samples for Web Browser to Web Application scenarios. And, check back frequently -- we add new
samples all the time. Web Browser to Web Application.
Registering
Single Tenant: If you are building an application just for your organization, it must be registered in your
company’s directory by using the Azure Portal.
Multi-Tenant: If you are building an application that can be used by users outside your organization, it must 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 your application available in their directory, you can include a sign-up process for
your customers that enables them to consent to your application. When they sign up for your application, they
will be presented with a dialog that shows the permissions the application requires, and then the option to
consent. Depending on the required permissions, an administrator in the other organization may be required to
give consent. When the user or administrator consents, the application is registered in their directory. For more
information, see Integrating Applications with Azure Active Directory.
Token Expiration
The user’s session expires when the lifetime of the token issued by Azure AD expires. Your application can shorten
this time period if desired, such as signing out users based on a period of inactivity. When the session expires, the
user will be prompted to sign in again.
Single Page Application (SPA )
This section describes authentication for a Single Page Application, that uses Azure AD and the OAuth 2.0 implicit
authorization grant to secure its web API back end. 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. To learn more about the implicit authorization grant, and help you
decide whether it's right for your application scenario, see Understanding the OAuth2 implicit grant flow in Azure
Active Directory.
In this scenario, when the user signs in, the JavaScript front end uses Active Directory Authentication Library for
JavaScript (ADAL.JS) and the implicit authorization grant to obtain an ID token (id_token) from Azure AD. The token
is cached and the client attaches it to the request as the bearer token when making calls to its Web API back end,
which is secured using the OWIN middleware.
Diagram
Description of Protocol Flow
1. The user navigates to the web application.
2. The application returns the JavaScript front end (presentation layer) to the browser.
3. The user initiates sign in, for example by clicking a sign in link. The browser sends a GET to the Azure AD
authorization endpoint to request an ID token. This request includes the application ID and reply URL in the
query parameters.
4. Azure AD validates the Reply URL against the registered Reply URL that was configured in the Azure Portal.
5. The user signs in on the sign-in page.
6. If authentication is successful, Azure AD creates an ID token and returns it as a URL fragment (#) to the
application’s Reply URL. For a production application, this Reply URL should be HTTPS. The returned token
includes claims about the user and Azure AD that are required by the application to validate the token.
7. The JavaScript client code running in the browser extracts the token from the response to use in securing calls to
the application’s web API back end.
8. The browser calls the application’s web API back end with the access token in the authorization header.
Code Samples
See the code samples for Single Page Application (SPA) scenarios. Be sure to check back frequently -- we add new
samples all the time. Single Page Application (SPA).
Registering
Single Tenant: If you are building an application just for your organization, it must be registered in your
company’s directory by using the Azure Portal.
Multi-Tenant: If you are building an application that can be used by users outside your organization, it must 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 your application available in their directory, you can include a sign-up process for
your customers that enables them to consent to your application. When they sign up for your application, they
will be presented with a dialog that shows the permissions the application requires, and then the option to
consent. Depending on the required permissions, an administrator in the other organization may be required to
give consent. When the user or administrator consents, the application is registered in their directory. For more
information, see Integrating Applications with Azure Active Directory.
After registering the application, it must be configured to use OAuth 2.0 Implicit Grant protocol. By default, this
protocol is disabled for applications. To enable the OAuth2 Implicit Grant protocol for your application, edit its
application manifest from the Azure Portal and set the “oauth2AllowImplicitFlow” value to true. For detailed
instructions, see Enabling OAuth 2.0 Implicit Grant for Single Page Applications.
Token Expiration
When you use ADAL.js to manage authentication with Azure AD, you benefit from several features that facilitate
refreshing an expired token as well as getting tokens for additional web API resources that may be called by the
application. When the user successfully authenticates with Azure AD, a session secured by a cookie is established
for the user between the browser and Azure AD. It’s important to note that the session exists between the user and
Azure AD and not between the user and the web application running on the server. When a token expires, ADAL.js
uses this session to silently obtain another token. It does this by using a hidden iFrame to send and receive the
request using the OAuth Implicit Grant protocol. ADAL.js can also use this same mechanism to silently obtain access
tokens from Azure AD for other web API resources that the application calls as long as these resources support
cross-origin resource sharing (CORS), are registered in the user’s directory, and any required consent was given by
the user during sign-in.
Native Application to Web API
This section describes a native application that calls a web API on behalf of a user. This scenario is built on the
OAuth 2.0 authorization code grant type with a public client, as described in section 4.1 of the OAuth 2.0
specification. The native application obtains an access token for the user by using the OAuth 2.0 protocol. This
access token is then sent in the request to the web API, which authorizes the user and returns the desired resource.
Diagram
Authentication flow for native application to API
Description of Protocol Flow
If you are using the AD Authentication Libraries, most of the protocol details described below are handled for you,
such as the browser pop-up, token caching, and handling of refresh tokens.
1. Using a browser pop-up, the native application makes a request to the authorization endpoint in Azure AD. This
request includes the Application ID and the redirect URI of the native application as shown in the Azure Portal,
and the application ID URI for the web API. If the user hasn’t already signed in, they are prompted to sign in
again
2. Azure AD authenticates the user. If it is a multi-tenant application and consent is required to use the application,
3.
4.
5.
6.
the user will be required to consent if they haven’t already done so. After granting consent and upon successful
authentication, Azure AD issues an authorization code response back to the client application’s redirect URI.
When Azure AD issues an authorization code response back to the redirect URI, the client application stops
browser interaction and extracts the authorization code from the response. Using this authorization code, the
client application sends a request to Azure AD’s token endpoint that includes the authorization code, details
about the client application (Application ID and redirect URI), and the desired resource (application ID URI for the
web API).
The authorization code and information about the client application and web API are validated by Azure AD.
Upon successful validation, Azure AD returns two tokens: a JWT access token and a JWT refresh token. In
addition, Azure AD returns basic information about the user, such as their display name and tenant ID.
Over HTTPS, the client 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 token,
and if validation is successful, returns the desired resource.
When the access token expires, the client application will receive an error that indicates the user needs to
authenticate again. If the application has a valid refresh token, it can be used to acquire a new access token
without prompting the user to sign in again. If the refresh token expires, the application will need to interactively
authenticate the user once again.
NOTE
The refresh token issued by Azure AD can be used to access multiple resources. For example, if you have a client application
that has permission to call two web APIs, the refresh token can be used to get an access token to the other web API as well.
Code Samples
See the code samples for Native Application to Web API scenarios. And, check back frequently -- we add new
samples all the time. Native Application to Web API.
Registering
Single Tenant: Both the native application and the web API must be registered in the same directory in Azure AD.
The web API can be configured to expose a set of permissions, which are used to limit the native application’s
access to its resources. The client application then selects the desired permissions from the “Permissions to
Other Applications” drop-down menu in the Azure Portal.
Multi-Tenant: First, the native application only ever registered in the developer or publisher’s directory. Second,
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,
which any user in the organization can consent to. Other applications require administrator-level permissions,
which a user in the organization cannot consent to. Only a directory administrator can give consent to
applications that require this level of permissions. When the user or administrator consents, only the web API is
registered in their directory. For more information, see Integrating Applications with Azure Active Directory.
Token Expiration
When the native application uses its authorization code to get a JWT access token, it also receives a JWT refresh
token. When the access token expires, the refresh token can be used to re-authenticate the user without requiring
them to sign in again. This refresh token is then used to authenticate the user, which results in a new access token
and refresh token.
Web Application to Web API
This section describes a web application that needs to get resources from a web API. In this scenario, there are two
identity types that the web application can use to authenticate and call the web API: an application identity, or a
delegated user identity.
Application identity: This scenario uses OAuth 2.0 client credentials grant to authenticate as the application and
access the web API. 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 via the application protocol, and 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.
Delegated user identity: This scenario can be accomplished in two ways: OpenID Connect, and OAuth 2.0
authorization code grant with a confidential client. 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.
Diagram
Description of Protocol Flow
Both the application identity and delegated user identity types are discussed in the flow below. The key difference
between them is that the delegated user identity must first acquire an authorization code before the user can signin and gain access to the web API.
A p p l i c a t i o n I d e n t i t y w i t h O A u t h 2 .0 C l i e n t C r e d e n t i a l s G r a n t
1. A user is signed in to Azure AD in the web application (see the Web Browser to Web Application above).
2. The web application needs to acquire an access token so that it can authenticate to the web API and retrieve the
desired resource. It makes a request to Azure AD’s token endpoint, providing the credential, Application ID, and
web API’s application ID URI.
3. Azure AD authenticates the application and returns a JWT access token that is used to call the web API.
4. Over HTTPS, 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 token,
and if validation is successful, returns the desired resource.
D e l e g a t e d U se r I d e n t i t y w i t h O p e n I D C o n n e c t
1. A user is signed in to a web application using Azure AD (see the Web Browser to Web Application section
above). 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 application will display the permissions it requires, and if any
of these are administrator-level permissions, a normal user in the directory will not be able to consent. This
consent process only applies to multi-tenant applications, not single tenant applications, as the application will
already have the necessary permissions. When the user signed in, the web application received an ID token with
information about the user, as well as an authorization code.
2. Using the authorization code issued by Azure AD, the web application sends a request to Azure AD’s token
endpoint that includes the authorization code, details about the client application (Application ID and redirect
URI), and the desired resource (application ID URI for the web API).
3. The authorization code and information about the web application and web API are validated by Azure AD. Upon
successful validation, Azure AD returns two tokens: a JWT access token and a JWT refresh token.
4. Over HTTPS, 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 token,
and if validation is successful, returns the desired resource.
D e l e g a t e d U se r I d e n t i t y w i t h O A u t h 2 .0 A u t h o r i z a t i o n C o d e G r a n t
1. A user is already signed in to a web application, whose authentication mechanism is independent of Azure AD.
2. The web application requires an authorization code to acquire an access token, so it issues a request through the
browser to Azure AD’s authorization endpoint, providing the Application ID and redirect URI for the web
application after successful authentication. The user signs in to Azure AD.
3. 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 application will display the permissions it requires, and if any of these
are administrator-level permissions, a normal user in the directory will not be able to consent. This consent
process only applies to multi-tenant applications, not single tenant applications, as the application will already
have the necessary permissions.
4. After the user has consented, the web application receives the authorization code that it needs to acquire an
access token.
5. Using the authorization code issued by Azure AD, the web application sends a request to Azure AD’s token
endpoint that includes the authorization code, details about the client application (Application ID and redirect
URI), and the desired resource (application ID URI for the web API).
6. The authorization code and information about the web application and web API are validated by Azure AD. Upon
successful validation, Azure AD returns two tokens: a JWT access token and a JWT refresh token.
7. Over HTTPS, 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 token,
and if validation is successful, returns the desired resource.
Code Samples
See the code samples for Web Application to Web API scenarios. And, check back frequently -- we add new samples
all the time. Web Application to Web API.
Registering
Single Tenant: For both the application identity and delegated user identity cases, the web application and the
web API must be registered in the same directory in Azure AD. The web API can be configured to expose a set of
permissions, which are used to limit the web application’s access to its resources. If a delegated user identity
type is being used, the web application needs to select the desired permissions from the “Permissions to Other
Applications” drop-down menu in the Azure Portal. This step is not required if the application identity type is
being used.
Multi-Tenant: First, the web 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 userlevel permissions, which any user in the organization can consent to. Other applications require administratorlevel permissions, which a user in the organization cannot consent to. Only a directory administrator can give
consent to applications that require this level of permissions. When the user or administrator consents, the web
application and the web API are both registered in their directory.
Token Expiration
When the web application uses its authorization code to get a JWT access token, it also receives a JWT refresh
token. When the access token expires, the refresh token can be used to re-authenticate the user without requiring
them to sign in again. This refresh token is then used to authenticate the user, which results in a new access token
and refresh token.
Daemon or Server Application to Web API
This section describes a daemon or server application that needs to get resources from a web API. There are two
sub-scenarios that apply to this section: A daemon that needs to call a web API, built on OAuth 2.0 client credentials
grant type; and a server application (such as a web API) that needs to call a web API, built on OAuth 2.0 On-BehalfOf draft specification.
For the scenario when a daemon application needs to call a web API, it’s important to understand a few things. First,
user interaction is not possible with a daemon application, which requires the application to have its own identity.
An example of a daemon application is a batch job, or an operating system service running in the background. This
type of application requests an access token by using its application identity and presenting its Application 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.
For the scenario when a server application needs to call a web API, it’s helpful to use an example. Imagine that a
user has authenticated on a native application, and this native application needs to call a web API. Azure AD issues a
JWT access token to call the web API. If the web API needs to call another downstream web API, it can use the onbehalf-of flow to delegate the user’s identity and authenticate to the second-tier web API.
Diagram
Description of Protocol Flow
A p p l i c a t i o n I d e n t i t y w i t h O A u t h 2 .0 C l i e n t C r e d e n t i a l s G r a n t
1. First, the server application needs to authenticate with Azure AD as itself, without any human interaction such as
an interactive sign-on dialog. It makes a request to Azure AD’s token endpoint, providing the credential,
Application ID, and application ID URI.
2. Azure AD authenticates the application and returns a JWT access token that is used to call the web API.
3. Over HTTPS, 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 token,
and if validation is successful, returns the desired resource.
D e l e g a t e d U se r I d e n t i t y w i t h O A u t h 2 .0 O n - B e h a l f- O f D r a ft Sp e c i fi c a t i o n
The flow discussed below assumes that a user has been authenticated on another application (such as a native
application), and their user identity has been used to acquire an access token to the first-tier web API.
1. The native application sends the access token to the first-tier web API.
2. The first-tier web API sends a request to Azure AD’s token endpoint, providing its Application ID and credentials,
as well as the user’s 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.
3. 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.
4. 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.
Code Samples
See the code samples for Daemon or Server Application to Web API scenarios. And, check back frequently -- we add
new samples all the time. Server or Daemon Application to Web API
Registering
Single Tenant: For both the application identity and delegated user identity cases, the daemon or server
application must be registered in the same directory in Azure AD. The web API can be configured to expose a set
of permissions, which are used to limit the daemon or server’s access to its resources. If a delegated user identity
type is being used, the server application needs to select the desired permissions from the “Permissions to Other
Applications” drop-down menu in the Azure Portal. This step is not required if the application identity type is
being used.
Multi-Tenant: First, the daemon or server 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, which any user in the organization can consent to. Other applications require
administrator-level permissions, which a user in the organization cannot consent to. Only a directory
administrator can give consent to applications that require this level of permissions. When the user or
administrator consents, both of the web APIs are registered in their directory.
Token Expiration
When the first application uses its authorization code to get a JWT access token, it also receives a JWT refresh token.
When the access token expires, the refresh token can be used to re-authenticate the user without prompting for
credentials. This refresh token is then used to authenticate the user, which results in a new access token and refresh
token.
See Also
Azure Active Directory Developer's Guide
Azure Active Directory Code Samples
Important Information About Signing Key Rollover in Azure AD
OAuth 2.0 in Azure AD
Help secure AngularJS single-page apps by using
Azure AD
2/9/2017 • 5 min to read • Edit Online
NOTE
This article is part of the Azure Active Directory developer's guide.
Azure Active Directory (Azure AD) makes it simple and straightforward for you to add sign-in, sign-out, and secure
OAuth API calls to your single-page apps. It enables your apps to authenticate users with their Windows Server
Active Directory accounts and consume any web API that Azure AD helps protect, such as the Office 365 APIs or the
Azure API.
For JavaScript applications running in a browser, Azure AD provides the Active Directory Authentication Library
(ADAL), or adal.js. The sole purpose of adal.js is to make it easy for your app to get access tokens. To demonstrate
just how easy it is, here we'll build an AngularJS To Do List application that:
Signs the user in to the app by using Azure AD as the identity provider.
Displays some information about the user.
Securely calls the app's To Do List API by using bearer tokens from Azure AD.
Signs the user out of the app.
To build the complete, working application, you need to:
1. Register your app with Azure AD.
2. Install ADAL and configure the single-page app.
3. Use ADAL to help secure pages in the single-page app.
To get started, download the app skeleton or download the completed sample. You also need an Azure AD tenant
in which you can create users and register an application. If you don't already have a tenant, learn how to get one.
Step 1: Register the DirectorySearcher application
To enable your app to authenticate users and get tokens, you first need to register it in your Azure AD tenant:
1. Sign in to the Azure portal.
2. On the top bar, click your account. Under the Directory list, choose the Azure AD tenant where you want to
register your application.
3. Click More Services in the left pane, and then select Azure Active Directory.
4. Click App registrations, and then select Add.
5. Follow the prompts and create a new web application and/or web API:
Name describes your application to users.
Redirect Uri is the location to which Azure AD will return tokens. The default location for this sample is
https://localhost:44326/ .
6. After you finish registration, Azure AD assigns a unique application ID to your app. You'll need this value in the
next sections, so copy it from the application tab.
7. Adal.js uses the OAuth implicit flow to communicate with Azure AD. You must enable the implicit flow for your
application:
a. Click the application and select Manifest to open the inline manifest editor.
b. Locate the oauth2AllowImplicitFlow property. Set its value to true .
c. Click Save to save the manifest.
8. Grant permissions across your tenant for your application. Go to Settings > Properties > Required
Permissions, and click the Grant Permissions button on the top bar. Click Yes to confirm.
Step 2: Install ADAL and configure the single-page app
Now that you have an application in Azure AD, you can install adal.js and write your identity-related code.
Begin by adding adal.js to the TodoSPA project by using the Package Manager Console:
1. Download adal.js and add it to the App/Scripts/ project directory.
2. Download adal-angular.js and add it to the App/Scripts/ project directory.
3. Load each script before the end of the </body> in index.html :
...
<script src="App/Scripts/adal.js"></script>
<script src="App/Scripts/adal-angular.js"></script>
...
For the single-page app's back-end To Do List API to accept tokens from the browser, the back end needs
configuration information about the app registration. In the TodoSPA project, open web.config . Replace the values
of the elements in the <appSettings> section to reflect the values that you used in the Azure portal. Your code will
reference these values whenever it uses ADAL.
is the domain of your Azure AD tenant--for example, contoso.onmicrosoft.com.
ida:Audience is the client ID of your application that you copied from the portal.
ida:Tenant
Step 3: Use ADAL to help secure pages in the single-page app
Adal.js integrates with AngularJS route and HTTP providers, so you can help secure individual views in your singlepage app.
1. In
App/Scripts/app.js
, bring in the adal.js module:
angular.module('todoApp', ['ngRoute','AdalAngular'])
.config(['$routeProvider','$httpProvider', 'adalAuthenticationServiceProvider',
function ($routeProvider, $httpProvider, adalProvider) {
...
2. Initialize
adalProvider
App/Scripts/app.js
by using the configuration values of your application registration, also in
:
adalProvider.init(
{
instance: 'https://login.microsoftonline.com/',
tenant: 'Enter your tenant name here e.g. contoso.onmicrosoft.com',
clientId: 'Enter your client ID here e.g. e9a5a8b6-8af7-4719-9821-0deef255f68e',
extraQueryParameter: 'nux=1',
//cacheLocation: 'localStorage', // enable this for IE, as sessionStorage does not work for
localhost.
},
$httpProvider
);
3. Help secure the
TodoList
view in the app by using only one line of code:
requireADLogin
.
...
}).when("/TodoList", {
controller: "todoListCtrl",
templateUrl: "/App/Views/TodoList.html",
requireADLogin: true,
...
Summary
You now have a secure single-page app that can sign in users and issue bearer-token-protected requests to its
back-end API. When a user clicks the TodoList link, adal.js will automatically redirect to Azure AD for sign-in if
necessary. In addition, adal.js will automatically attach an access token to any Ajax requests that are sent to the
app's back end.
The preceding steps are the bare minimum necessary to build a single-page app by using adal.js. But a few other
features are useful in single-page app:
To explicitly issue sign-in and sign-out requests, you can define functions in your controllers that invoke
adal.js. In App/Scripts/homeCtrl.js :
...
$scope.login = function () {
adalService.login();
};
$scope.logout = function () {
adalService.logOut();
};
...
You might want to present user information in the app's UI. The ADAL service has already been added to the
userDataCtrl controller, so you can access the userInfo object in the associated view,
App/Views/UserData.html :
<p>{{userInfo.userName}}</p>
<p>aud:{{userInfo.profile.aud}}</p>
<p>iss:{{userInfo.profile.iss}}</p>
...
There are many scenarios in which you'll want to know if the user is signed in or not. You can also use the
userInfo object to gather this information. For instance, in index.html , you can show either the Login or
Logout button based on authentication status:
<li><a class="btn btn-link" ng-show="userInfo.isAuthenticated" ng-click="logout()">Logout</a></li>
<li><a class="btn btn-link" ng-hide=" userInfo.isAuthenticated" ng-click="login()">Login</a></li>
Your Azure AD-integrated single-page app can authenticate users, securely call its back end by using OAuth 2.0,
and get basic information about the user. If you haven't already, now is the time to populate your tenant with some
users. Run your To Do List single-page app, and sign in with one of those users. Add tasks to the user's to-do list,
sign out, and sign back in.
Adal.js makes it easy to incorporate common identity features into your application. It takes care of all the dirty
work for you: cache management, OAuth protocol support, presenting the user with a sign-in UI, refreshing expired
tokens, and more.
For reference, the completed sample (without your configuration values) is available in GitHub.
Next steps
You can now move on to additional scenarios. You might want to try: Call a CORS web API from a single-page app.
Additional resources
The Azure AD developer's guide
Azure AD samples on GitHub
CloudIdentity.com
Get security updates for our products
We encourage you to get notifications of when security incidents occur by visiting the TechCenter page for
Microsoft technical security notifications and subscribing to security advisory alerts.
Authentication Scenarios for Azure AD
4/27/2017 • 31 min to read • Edit Online
Azure Active Directory (Azure AD) simplifies authentication for developers by providing identity as a service, with
support for industry-standard protocols such as OAuth 2.0 and OpenID Connect, as well as open source libraries for
different platforms to help you start coding quickly. This document will help you understand the various scenarios
Azure AD supports and will show you how to get started. It’s divided into the following sections:
Basics of Authentication in Azure AD
Claims in Azure AD Security Tokens
Basics of Registering an Application in Azure AD
Application Types and Scenarios
Web Browser to Web Application
Single Page Application (SPA)
Native Application to Web API
Web Application to Web API
Daemon or Server Application to Web API
Basics of Authentication in Azure AD
If you are unfamiliar with basic concepts of authentication in Azure AD, read this section. Otherwise, you may want
to skip down to Application Types and Scenarios.
Let’s consider the most basic scenario where identity is required: a user in a web browser needs to authenticate to a
web application. This scenario is described in greater detail in the Web Browser to Web Application section, but it’s
a useful starting point to illustrate the capabilities of Azure AD and conceptualize how the scenario works. Consider
the following diagram for this scenario:
With the diagram above in mind, here’s what you need to know about its various components:
Azure AD is the identity provider, responsible for verifying the identity of users and applications that exist in an
organization’s directory, and ultimately issuing security tokens upon successful authentication of those users
and applications.
An application that wants to outsource authentication to Azure AD must be registered in Azure AD, which
registers and uniquely identifies the app in the directory.
Developers can use the open source Azure AD authentication libraries to make authentication easy by handling
the protocol details for you. See Azure Active Directory Authentication Libraries for more information.
• Once a user has been authenticated, the application must validate the user’s security token to ensure that
authentication was successful for the intended parties. Developers can use the provided authentication libraries to
handle validation of any token from Azure AD, including JSON Web Tokens (JWT) or SAML 2.0. If you want to
perform validation manually, see the JWT Token Handler documentation.
IMPORTANT
Azure AD uses public key cryptography to sign tokens and verify that they are valid. See Important Information About
Signing Key Rollover in Azure AD for more information on the necessary logic you must have in your application to ensure it’s
always updated with the latest keys.
• The flow of requests and responses for the authentication process is determined by the authentication protocol
that was used, such as OAuth 2.0, OpenID Connect, WS-Federation, or SAML 2.0. These protocols are discussed in
more detail in the Azure Active Directory Authentication Protocols topic and in the sections below.
NOTE
Azure AD supports the OAuth 2.0 and OpenID Connect standards that make extensive use of bearer tokens, including bearer
tokens represented as JWTs. A bearer token is a lightweight security token that grants the “bearer” access to a protected
resource. In this sense, the “bearer” is any party that can present the token. Though a party must first authenticate with Azure
AD to receive the bearer token, if the required steps are not taken to secure the token in transmission and storage, it can be
intercepted and used by an unintended party. While some security tokens have a built-in mechanism for preventing
unauthorized parties from using them, bearer tokens do not have this mechanism and must be transported in a secure
channel such as transport layer security (HTTPS). If a bearer token is transmitted in the clear, a man-in the middle attack can
be used by a malicious party to acquire the token and use it for an unauthorized access to a protected resource. The same
security principles apply when storing or caching bearer tokens for later use. Always ensure that your application transmits
and stores bearer tokens in a secure manner. For more security considerations on bearer tokens, see RFC 6750 Section 5.
Now that you have an overview of the basics, read the sections below to understand how provisioning works in
Azure AD and the common scenarios Azure AD supports.
Claims in Azure AD Security Tokens
Security tokens issued by Azure AD contain claims, or assertions of information about the subject that has been
authenticated. These claims can be used by the application for various tasks. For example, they can be used to
validate the token, identify the subject's directory tenant, display user information, determine the subject's
authorization, and so on. The claims present in any given security token are dependent upon the type of token, the
type of credential used to authenticate the user, and the application configuration. A brief description of each type
of claim emitted by Azure AD is provided in the table below. For more information, refer to Supported Token and
Claim Types.
CLAIM
DESCRIPTION
Application ID
Identifies the application that is using the token.
Audience
Identifies the recipient resource the token is intended for.
Application Authentication Context Class Reference
Indicates how the client was authenticated (public client vs.
confidential client).
Authentication Instant
Records the date and time when the authentication occurred.
CLAIM
DESCRIPTION
Authentication Method
Indicates how the subject of the token was authenticated
(password, certificate, etc.).
First Name
Provides the given name of the user as set in Azure AD.
Groups
Contains object Ids of Azure AD groups the user is a member
of.
Identity Provider
Records the identity provider that authenticated the subject of
the token.
Issued At
Records the time at which the token was issued, often used for
token freshness.
Issuer
Identifies the STS that emitted the token as well as the Azure
AD tenant.
Last Name
Provides the surname of the user as set in Azure AD.
Name
Provides a human readable value that identifies the subject of
the token.
Object Id
Contains an immutable, unique identifier of the subject in
Azure AD.
Roles
Contains friendly names of Azure AD Application Roles that
the user has been granted.
Scope
Indicates the permissions granted to the client application.
Subject
Indicates the principal about which the token asserts
information.
Tenant Id
Contains an immutable, unique identifier of the directory
tenant that issued the token.
Token Lifetime
Defines the time interval within which a token is valid.
User Principal Name
Contains the user principal name of the subject.
Version
Contains the version number of the token.
Basics of Registering an Application in Azure AD
Any application that outsources authentication to Azure AD must be registered in a directory. This step involves
telling Azure AD about your application, including the URL where it’s located, the URL to send replies after
authentication, the URI to identify your application, and more. This information is required for a few key reasons:
Azure AD needs coordinates to communicate with the application when handling sign-on or exchanging
tokens. These include the following:
Application ID URI: The identifier for an application. This value is sent to Azure AD during authentication
to indicate which application the caller wants a token for. Additionally, this value is included in the token
so that the application knows it was the intended target.
Reply URL and Redirect URI: In the case of a web API or web application, the Reply URL is the location to
which Azure AD will send the authentication response, including a token if authentication was successful.
In the case of a native application, the Redirect URI is a unique identifier to which Azure AD will redirect
the user-agent in an OAuth 2.0 request.
Application ID: The ID for an application, which is generated by Azure AD when the application is
registered. When requesting an authorization code or token, the Application ID and key are sent to Azure
AD during authentication.
Key: The key that is sent along with a Application ID when authenticating to Azure AD to call a web API.
Azure AD needs to ensure the application has the required permissions to access your directory data, other
applications in your organization, and so on
Provisioning becomes clearer when you understand that there are two categories of applications that can be
developed and integrated with Azure AD:
Single tenant application: A single tenant application is intended for use in one organization. These are typically
line-of-business (LoB) applications written by an enterprise developer. A single tenant application only needs to
be accessed by users in one directory, and as a result, it only needs to be provisioned in one directory. These
applications are typically registered by a developer in the organization.
Multi-tenant application: A multi-tenant application is intended for use in many organizations, not just one
organization. These are typically software-as-a-service (SaaS) applications written by an independent software
vendor (ISV). Multi-tenant applications need to be provisioned in each directory where they will be used, which
requires user or administrator consent to register them. This consent process starts when an application has
been registered in the directory and is given access to the Graph API or perhaps another web API. When a user
or administrator from a different organization signs up to use the application, they are presented with a dialog
that displays the permissions the application requires. The user or administrator can then consent to the
application, which gives the application access to the stated data, and finally registers the application in their
directory. For more information, see Overview of the Consent Framework.
Some additional considerations arise when developing a multi-tenant application instead of a single tenant
application. For example, if you are making your application available to users in multiple directories, you need a
mechanism to determine which tenant they’re in. A single tenant application only needs to look in its own directory
for a user, while a multi-tenant application needs to identify a specific user from all the directories in Azure AD. To
accomplish this task, Azure AD provides a common authentication endpoint where any multi-tenant application can
direct sign-in requests, instead of a tenant-specific endpoint. This endpoint is
https://login.microsoftonline.com/common for all directories in Azure AD, whereas a tenant-specific endpoint might
be https://login.microsoftonline.com/contoso.onmicrosoft.com. The common endpoint is especially important to
consider when developing your application because you’ll need the necessary logic to handle multiple tenants
during sign-in, sign-out, and token validation.
If you are currently developing a single tenant application but want to make it available to many organizations, you
can easily make changes to the application and its configuration in Azure AD to make it multi-tenant capable. In
addition, Azure AD uses the same signing key for all tokens in all directories, whether you are providing
authentication in a single tenant or multi-tenant application.
Each scenario listed in this document includes a sub-section that describes its provisioning requirements. For more
in-depth information about provisioning an application in Azure AD and the differences between single and multitenant applications, see Integrating Applications with Azure Active Directory for more information. Continue
reading to understand the common application scenarios in Azure AD.
Application Types and Scenarios
Each of the scenarios described in this document can be developed using various languages and platforms. They
are all backed by complete code samples which are available in our Code Samples guide, or directly from the
corresponding GitHub sample repositories. In addition, if your application needs a specific piece or segment of an
end-to-end scenario, in most cases that functionality can be added independently. For example, if you have a native
application that calls a web API, you can easily add a web application that also calls the web API. The following
diagram illustrates these scenarios and application types, and how different components can be added:
These are the five primary application scenarios 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 user needs to sign in to a single page application that is secured by Azure AD.
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.
Web Browser to Web Application
This section describes an application that authenticates a user in a web browser to a web application. In this
scenario, the web application directs the user’s browser to sign them in to Azure AD. Azure AD returns a sign-in
response through the user’s browser, which contains claims about the user in a security token. This scenario
supports sign-on using the WS-Federation, SAML 2.0, and OpenID Connect protocols.
Diagram
Description of Protocol Flow
1. When a user visits the application and needs to sign in, they are redirected via a sign-in request to the
authentication endpoint in Azure AD.
2. The user signs in on the sign-in page.
3. If authentication is successful, Azure AD creates an authentication token and returns a sign-in response to the
application’s Reply URL that was configured in the Azure Portal. For a production application, this Reply URL
should be HTTPS. The returned token includes claims about the user and Azure AD that are required by the
application to validate the token.
4. The application validates the token by using a public signing key and issuer information available at the
federation metadata document for Azure AD. After the application validates the token, Azure AD starts a new
session with the user. This session allows the user to access the application until it expires.
Code Samples
See the code samples for Web Browser to Web Application scenarios. And, check back frequently -- we add new
samples all the time. Web Browser to Web Application.
Registering
Single Tenant: If you are building an application just for your organization, it must be registered in your
company’s directory by using the Azure Portal.
Multi-Tenant: If you are building an application that can be used by users outside your organization, it must 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 your application available in their directory, you can include a sign-up process for
your customers that enables them to consent to your application. When they sign up for your application, they
will be presented with a dialog that shows the permissions the application requires, and then the option to
consent. Depending on the required permissions, an administrator in the other organization may be required to
give consent. When the user or administrator consents, the application is registered in their directory. For more
information, see Integrating Applications with Azure Active Directory.
Token Expiration
The user’s session expires when the lifetime of the token issued by Azure AD expires. Your application can shorten
this time period if desired, such as signing out users based on a period of inactivity. When the session expires, the
user will be prompted to sign in again.
Single Page Application (SPA )
This section describes authentication for a Single Page Application, that uses Azure AD and the OAuth 2.0 implicit
authorization grant to secure its web API back end. 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. To learn more about the implicit authorization grant, and help you
decide whether it's right for your application scenario, see Understanding the OAuth2 implicit grant flow in Azure
Active Directory.
In this scenario, when the user signs in, the JavaScript front end uses Active Directory Authentication Library for
JavaScript (ADAL.JS) and the implicit authorization grant to obtain an ID token (id_token) from Azure AD. The token
is cached and the client attaches it to the request as the bearer token when making calls to its Web API back end,
which is secured using the OWIN middleware.
Diagram
Description of Protocol Flow
1. The user navigates to the web application.
2. The application returns the JavaScript front end (presentation layer) to the browser.
3. The user initiates sign in, for example by clicking a sign in link. The browser sends a GET to the Azure AD
authorization endpoint to request an ID token. This request includes the application ID and reply URL in the
query parameters.
4. Azure AD validates the Reply URL against the registered Reply URL that was configured in the Azure Portal.
5. The user signs in on the sign-in page.
6. If authentication is successful, Azure AD creates an ID token and returns it as a URL fragment (#) to the
application’s Reply URL. For a production application, this Reply URL should be HTTPS. The returned token
includes claims about the user and Azure AD that are required by the application to validate the token.
7. The JavaScript client code running in the browser extracts the token from the response to use in securing calls to
the application’s web API back end.
8. The browser calls the application’s web API back end with the access token in the authorization header.
Code Samples
See the code samples for Single Page Application (SPA) scenarios. Be sure to check back frequently -- we add new
samples all the time. Single Page Application (SPA).
Registering
Single Tenant: If you are building an application just for your organization, it must be registered in your
company’s directory by using the Azure Portal.
Multi-Tenant: If you are building an application that can be used by users outside your organization, it must 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 your application available in their directory, you can include a sign-up process for
your customers that enables them to consent to your application. When they sign up for your application, they
will be presented with a dialog that shows the permissions the application requires, and then the option to
consent. Depending on the required permissions, an administrator in the other organization may be required to
give consent. When the user or administrator consents, the application is registered in their directory. For more
information, see Integrating Applications with Azure Active Directory.
After registering the application, it must be configured to use OAuth 2.0 Implicit Grant protocol. By default, this
protocol is disabled for applications. To enable the OAuth2 Implicit Grant protocol for your application, edit its
application manifest from the Azure Portal and set the “oauth2AllowImplicitFlow” value to true. For detailed
instructions, see Enabling OAuth 2.0 Implicit Grant for Single Page Applications.
Token Expiration
When you use ADAL.js to manage authentication with Azure AD, you benefit from several features that facilitate
refreshing an expired token as well as getting tokens for additional web API resources that may be called by the
application. When the user successfully authenticates with Azure AD, a session secured by a cookie is established
for the user between the browser and Azure AD. It’s important to note that the session exists between the user and
Azure AD and not between the user and the web application running on the server. When a token expires, ADAL.js
uses this session to silently obtain another token. It does this by using a hidden iFrame to send and receive the
request using the OAuth Implicit Grant protocol. ADAL.js can also use this same mechanism to silently obtain access
tokens from Azure AD for other web API resources that the application calls as long as these resources support
cross-origin resource sharing (CORS), are registered in the user’s directory, and any required consent was given by
the user during sign-in.
Native Application to Web API
This section describes a native application that calls a web API on behalf of a user. This scenario is built on the
OAuth 2.0 authorization code grant type with a public client, as described in section 4.1 of the OAuth 2.0
specification. The native application obtains an access token for the user by using the OAuth 2.0 protocol. This
access token is then sent in the request to the web API, which authorizes the user and returns the desired resource.
Diagram
Authentication flow for native application to API
Description of Protocol Flow
If you are using the AD Authentication Libraries, most of the protocol details described below are handled for you,
such as the browser pop-up, token caching, and handling of refresh tokens.
1. Using a browser pop-up, the native application makes a request to the authorization endpoint in Azure AD. This
request includes the Application ID and the redirect URI of the native application as shown in the Azure Portal,
and the application ID URI for the web API. If the user hasn’t already signed in, they are prompted to sign in
again
2. Azure AD authenticates the user. If it is a multi-tenant application and consent is required to use the application,
3.
4.
5.
6.
the user will be required to consent if they haven’t already done so. After granting consent and upon successful
authentication, Azure AD issues an authorization code response back to the client application’s redirect URI.
When Azure AD issues an authorization code response back to the redirect URI, the client application stops
browser interaction and extracts the authorization code from the response. Using this authorization code, the
client application sends a request to Azure AD’s token endpoint that includes the authorization code, details
about the client application (Application ID and redirect URI), and the desired resource (application ID URI for the
web API).
The authorization code and information about the client application and web API are validated by Azure AD.
Upon successful validation, Azure AD returns two tokens: a JWT access token and a JWT refresh token. In
addition, Azure AD returns basic information about the user, such as their display name and tenant ID.
Over HTTPS, the client 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 token,
and if validation is successful, returns the desired resource.
When the access token expires, the client application will receive an error that indicates the user needs to
authenticate again. If the application has a valid refresh token, it can be used to acquire a new access token
without prompting the user to sign in again. If the refresh token expires, the application will need to interactively
authenticate the user once again.
NOTE
The refresh token issued by Azure AD can be used to access multiple resources. For example, if you have a client application
that has permission to call two web APIs, the refresh token can be used to get an access token to the other web API as well.
Code Samples
See the code samples for Native Application to Web API scenarios. And, check back frequently -- we add new
samples all the time. Native Application to Web API.
Registering
Single Tenant: Both the native application and the web API must be registered in the same directory in Azure AD.
The web API can be configured to expose a set of permissions, which are used to limit the native application’s
access to its resources. The client application then selects the desired permissions from the “Permissions to
Other Applications” drop-down menu in the Azure Portal.
Multi-Tenant: First, the native application only ever registered in the developer or publisher’s directory. Second,
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,
which any user in the organization can consent to. Other applications require administrator-level permissions,
which a user in the organization cannot consent to. Only a directory administrator can give consent to
applications that require this level of permissions. When the user or administrator consents, only the web API is
registered in their directory. For more information, see Integrating Applications with Azure Active Directory.
Token Expiration
When the native application uses its authorization code to get a JWT access token, it also receives a JWT refresh
token. When the access token expires, the refresh token can be used to re-authenticate the user without requiring
them to sign in again. This refresh token is then used to authenticate the user, which results in a new access token
and refresh token.
Web Application to Web API
This section describes a web application that needs to get resources from a web API. In this scenario, there are two
identity types that the web application can use to authenticate and call the web API: an application identity, or a
delegated user identity.
Application identity: This scenario uses OAuth 2.0 client credentials grant to authenticate as the application and
access the web API. 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 via the application protocol, and 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.
Delegated user identity: This scenario can be accomplished in two ways: OpenID Connect, and OAuth 2.0
authorization code grant with a confidential client. 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.
Diagram
Description of Protocol Flow
Both the application identity and delegated user identity types are discussed in the flow below. The key difference
between them is that the delegated user identity must first acquire an authorization code before the user can signin and gain access to the web API.
A p p l i c a t i o n I d e n t i t y w i t h O A u t h 2 .0 C l i e n t C r e d e n t i a l s G r a n t
1. A user is signed in to Azure AD in the web application (see the Web Browser to Web Application above).
2. The web application needs to acquire an access token so that it can authenticate to the web API and retrieve the
desired resource. It makes a request to Azure AD’s token endpoint, providing the credential, Application ID, and
web API’s application ID URI.
3. Azure AD authenticates the application and returns a JWT access token that is used to call the web API.
4. Over HTTPS, 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 token,
and if validation is successful, returns the desired resource.
D e l e g a t e d U se r I d e n t i t y w i t h O p e n I D C o n n e c t
1. A user is signed in to a web application using Azure AD (see the Web Browser to Web Application section
above). 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 application will display the permissions it requires, and if any
of these are administrator-level permissions, a normal user in the directory will not be able to consent. This
consent process only applies to multi-tenant applications, not single tenant applications, as the application will
already have the necessary permissions. When the user signed in, the web application received an ID token with
information about the user, as well as an authorization code.
2. Using the authorization code issued by Azure AD, the web application sends a request to Azure AD’s token
endpoint that includes the authorization code, details about the client application (Application ID and redirect
URI), and the desired resource (application ID URI for the web API).
3. The authorization code and information about the web application and web API are validated by Azure AD. Upon
successful validation, Azure AD returns two tokens: a JWT access token and a JWT refresh token.
4. Over HTTPS, 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 token,
and if validation is successful, returns the desired resource.
D e l e g a t e d U se r I d e n t i t y w i t h O A u t h 2 .0 A u t h o r i z a t i o n C o d e G r a n t
1. A user is already signed in to a web application, whose authentication mechanism is independent of Azure AD.
2. The web application requires an authorization code to acquire an access token, so it issues a request through the
browser to Azure AD’s authorization endpoint, providing the Application ID and redirect URI for the web
application after successful authentication. The user signs in to Azure AD.
3. 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 application will display the permissions it requires, and if any of these
are administrator-level permissions, a normal user in the directory will not be able to consent. This consent
process only applies to multi-tenant applications, not single tenant applications, as the application will already
have the necessary permissions.
4. After the user has consented, the web application receives the authorization code that it needs to acquire an
access token.
5. Using the authorization code issued by Azure AD, the web application sends a request to Azure AD’s token
endpoint that includes the authorization code, details about the client application (Application ID and redirect
URI), and the desired resource (application ID URI for the web API).
6. The authorization code and information about the web application and web API are validated by Azure AD. Upon
successful validation, Azure AD returns two tokens: a JWT access token and a JWT refresh token.
7. Over HTTPS, 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 token,
and if validation is successful, returns the desired resource.
Code Samples
See the code samples for Web Application to Web API scenarios. And, check back frequently -- we add new samples
all the time. Web Application to Web API.
Registering
Single Tenant: For both the application identity and delegated user identity cases, the web application and the
web API must be registered in the same directory in Azure AD. The web API can be configured to expose a set of
permissions, which are used to limit the web application’s access to its resources. If a delegated user identity
type is being used, the web application needs to select the desired permissions from the “Permissions to Other
Applications” drop-down menu in the Azure Portal. This step is not required if the application identity type is
being used.
Multi-Tenant: First, the web 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 userlevel permissions, which any user in the organization can consent to. Other applications require administratorlevel permissions, which a user in the organization cannot consent to. Only a directory administrator can give
consent to applications that require this level of permissions. When the user or administrator consents, the web
application and the web API are both registered in their directory.
Token Expiration
When the web application uses its authorization code to get a JWT access token, it also receives a JWT refresh
token. When the access token expires, the refresh token can be used to re-authenticate the user without requiring
them to sign in again. This refresh token is then used to authenticate the user, which results in a new access token
and refresh token.
Daemon or Server Application to Web API
This section describes a daemon or server application that needs to get resources from a web API. There are two
sub-scenarios that apply to this section: A daemon that needs to call a web API, built on OAuth 2.0 client credentials
grant type; and a server application (such as a web API) that needs to call a web API, built on OAuth 2.0 On-BehalfOf draft specification.
For the scenario when a daemon application needs to call a web API, it’s important to understand a few things. First,
user interaction is not possible with a daemon application, which requires the application to have its own identity.
An example of a daemon application is a batch job, or an operating system service running in the background. This
type of application requests an access token by using its application identity and presenting its Application 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.
For the scenario when a server application needs to call a web API, it’s helpful to use an example. Imagine that a
user has authenticated on a native application, and this native application needs to call a web API. Azure AD issues a
JWT access token to call the web API. If the web API needs to call another downstream web API, it can use the onbehalf-of flow to delegate the user’s identity and authenticate to the second-tier web API.
Diagram
Description of Protocol Flow
A p p l i c a t i o n I d e n t i t y w i t h O A u t h 2 .0 C l i e n t C r e d e n t i a l s G r a n t
1. First, the server application needs to authenticate with Azure AD as itself, without any human interaction such as
an interactive sign-on dialog. It makes a request to Azure AD’s token endpoint, providing the credential,
Application ID, and application ID URI.
2. Azure AD authenticates the application and returns a JWT access token that is used to call the web API.
3. Over HTTPS, 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 token,
and if validation is successful, returns the desired resource.
D e l e g a t e d U se r I d e n t i t y w i t h O A u t h 2 .0 O n - B e h a l f- O f D r a ft Sp e c i fi c a t i o n
The flow discussed below assumes that a user has been authenticated on another application (such as a native
application), and their user identity has been used to acquire an access token to the first-tier web API.
1. The native application sends the access token to the first-tier web API.
2. The first-tier web API sends a request to Azure AD’s token endpoint, providing its Application ID and credentials,
as well as the user’s 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.
3. 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.
4. 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.
Code Samples
See the code samples for Daemon or Server Application to Web API scenarios. And, check back frequently -- we add
new samples all the time. Server or Daemon Application to Web API
Registering
Single Tenant: For both the application identity and delegated user identity cases, the daemon or server
application must be registered in the same directory in Azure AD. The web API can be configured to expose a set
of permissions, which are used to limit the daemon or server’s access to its resources. If a delegated user identity
type is being used, the server application needs to select the desired permissions from the “Permissions to Other
Applications” drop-down menu in the Azure Portal. This step is not required if the application identity type is
being used.
Multi-Tenant: First, the daemon or server 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, which any user in the organization can consent to. Other applications require
administrator-level permissions, which a user in the organization cannot consent to. Only a directory
administrator can give consent to applications that require this level of permissions. When the user or
administrator consents, both of the web APIs are registered in their directory.
Token Expiration
When the first application uses its authorization code to get a JWT access token, it also receives a JWT refresh token.
When the access token expires, the refresh token can be used to re-authenticate the user without prompting for
credentials. This refresh token is then used to authenticate the user, which results in a new access token and refresh
token.
See Also
Azure Active Directory Developer's Guide
Azure Active Directory Code Samples
Important Information About Signing Key Rollover in Azure AD
OAuth 2.0 in Azure AD
Help protect a web API by using bearer tokens from
Azure AD
3/17/2017 • 5 min to read • Edit Online
NOTE
This article is part of the Azure Active Directory developer's guide.
If you’re building an application that provides access to protected resources, you need to know how to prevent
unwarranted access to those resources. Azure Active Directory (Azure AD) makes it simple and straightforward to
help protect a web API by using OAuth 2.0 bearer access tokens with only a few lines of code.
In ASP.NET web apps, you can accomplish this protection by using the Microsoft implementation of the
community-driven OWIN middleware included in .NET Framework 4.5. Here we’ll use OWIN to build a "To Do
List" web API that:
Designates which APIs are protected.
Validates that the web API calls contain a valid access token.
To build the To Do List API, you first need to:
1. Register an application with Azure AD.
2. Set up the app to use the OWIN authentication pipeline.
3. Configure a client application to call the web API.
To get started, download the app skeleton or download the completed sample. Each is a Visual Studio 2013
solution. You also need an Azure AD tenant in which to register your application. If you don't have one already,
learn how to get one.
Step 1: Register an application with Azure AD
To help secure your application, you first need to create an application in your tenant and provide Azure AD with a
few key pieces of information.
1. Sign in to the Azure portal.
2. On the top bar, click your account. In the Directory list, choose the Azure AD tenant where you want to
register your application.
3. Click More Services in the left pane, and then select Azure Active Directory.
4. Click App registrations, and then select Add.
5. Follow the prompts and create a new Web Application and/or Web API.
Name describes your application to users. Enter To Do List Service.
Redirect Uri is a scheme and string combination that Azure AD uses to return any tokens that your app
has requested. Enter https://localhost:44321/ for this value.
6. From the Settings -> Properties page for your application, update the App ID URI. Enter a tenant-specific
identifier. For example, enter https://contoso.onmicrosoft.com/TodoListService .
7. Save the configuration. Leave the portal open, because you'll also need to register your client application
shortly.
Step 2: Set up the app to use the OWIN authentication pipeline
To validate incoming requests and tokens, you need to set up your application to communicate with Azure AD.
1. To begin, open the solution and add the OWIN middleware NuGet packages to the TodoListService project
by using the Package Manager Console.
PM> Install-Package Microsoft.Owin.Security.ActiveDirectory -ProjectName TodoListService
PM> Install-Package Microsoft.Owin.Host.SystemWeb -ProjectName TodoListService
2. Add an OWIN Startup class to the TodoListService project called Startup.cs . Right-click the project, select
Add > New Item, and then search for OWIN. The OWIN middleware will invoke the Configuration(…)
method when your app starts.
3. Change the class declaration to public partial class Startup . We’ve already implemented part of this
class for you in another file. In the Configuration(…) method, make a call to ConfgureAuth(…) to set up
authentication for your web app.
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
}
}
4. Open the file App_Start\Startup.Auth.cs and implement the ConfigureAuth(…) method. The parameters
that you provide in WindowsAzureActiveDirectoryBearerAuthenticationOptions will serve as coordinates for
your app to communicate with Azure AD.
public void ConfigureAuth(IAppBuilder app)
{
app.UseWindowsAzureActiveDirectoryBearerAuthentication(
new WindowsAzureActiveDirectoryBearerAuthenticationOptions
{
Audience = ConfigurationManager.AppSettings["ida:Audience"],
Tenant = ConfigurationManager.AppSettings["ida:Tenant"]
});
}
5. Now you can use [Authorize] attributes to help protect your controllers and actions with JSON Web
Token (JWT) bearer authentication. Decorate the Controllers\TodoListController.cs class with an
authorize tag. This will force the user to sign in before accessing that page.
[Authorize]
public class TodoListController : ApiController
{
When an authorized caller successfully invokes one of the TodoListController APIs, the action might need
access to information about the caller. OWIN provides access to the claims inside the bearer token via the
ClaimsPrincpal object.
6. A common requirement for web APIs is to validate the "scopes" present in the token. This ensures that the
user has consented to the permissions required to access the To Do List Service.
public IEnumerable<TodoItem> Get()
{
// user_impersonation is the default permission exposed by applications in Azure AD
if (ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/scope").Value
!= "user_impersonation")
{
throw new HttpResponseException(new HttpResponseMessage {
StatusCode = HttpStatusCode.Unauthorized,
ReasonPhrase = "The Scope claim does not contain 'user_impersonation' or scope claim not
found"
});
}
...
}
7. Open the web.config file in the root of the TodoListService project, and enter your configuration values in
the <appSettings> section.
is the name of your Azure AD tenant--for example, contoso.onmicrosoft.com.
ida:Audience is the App ID URI of the application that you entered in the Azure portal.
ida:Tenant
Step 3: Configure a client application and run the service
Before you can see the To Do List Service in action, you need to configure the To Do List client so it can get tokens
from Azure AD and make calls to the service.
1. Go back to the Azure portal.
2. Create a new application in your Azure AD tenant, and select Native Client Application in the resulting
prompt.
Name describes your application to users.
Enter http://TodoListClient/ for the Redirect Uri value.
3. After you finish registration, Azure AD assigns a unique application ID to your app. You’ll need this value in
the next steps, so copy it from the application page.
4. From the Settings page, select Required Permissions, and then select Add. Locate and select the To Do
List Service, add the Access TodoListService permission under Delegated Permissions, and then click
Done.
5. In Visual Studio, open App.config in the TodoListClient project, and then enter your configuration values
in the <appSettings> section.
is the name of your Azure AD tenant--for example, contoso.onmicrosoft.com.
ida:ClientId is the app ID that you copied from the Azure portal.
todo:TodoListResourceId is the App ID URI of the To Do List Service application that you entered in the
Azure portal.
ida:Tenant
Next steps
Finally, clean, build, and run each project. If you haven’t already, now is the time to create a new user in your
tenant with a *.onmicrosoft.com domain. Sign in to the To Do List client with that user, and add some tasks to the
user's to-do list.
For reference, the completed sample (without your configuration values) is available in GitHub. You can now
move on to more identity scenarios.
Additional resources
The Azure AD developer's guide
Azure AD samples on GitHub
CloudIdentity.com
Get security updates for our products
We encourage you to get notifications of when security incidents occur by visiting the TechCenter page for
Microsoft technical security notifications and subscribing to security advisory alerts.
Get started with web APIs for Node.js
4/17/2017 • 22 min to read • Edit Online
NOTE
This article is part of the Azure Active Directory developer's guide.
Passport is authentication middleware for Node.js. Flexible and modular, Passport can be unobtrusively dropped
in to any Express-based or Restify web application. A comprehensive set of strategies support authentication with
a username and password, Facebook, Twitter, and more. We have developed a strategy for Microsoft Azure Active
Directory (Azure AD). We install this module and then add the Microsoft Azure Active Directory passport-azure-ad
plug-in.
To do this, you need to:
1. Register an application with Azure AD.
2. Set up your app to use Passport's passport-azure-ad plug-in.
3. Configure a client application to call the To Do List web API.
The code for this tutorial is maintained on GitHub.
NOTE
This article doesn't cover how to implement sign-in, sign-up, or profile management with Azure AD B2C. It focuses on
calling web APIs after the user is already authenticated. We recommend that you start with How to integrate with Azure
Active Directory document to learn about the basics of Azure Active Directory.
We've released all the source code for this running example in GitHub under an MIT license, so feel free to clone
(or even better, fork), and provide feedback and pull requests.
About Node.js modules
We use Node.js modules in this walkthrough. Modules are loadable JavaScript packages that provide specific
functionality for your application. You usually install modules by using the Node.js an NPM command-line tool in
the NPM installation directory. However, some modules, such as the HTTP module, are included in the core
Node.js package.
Installed modules are saved in the node_modules directory at the root of your Node.js installation directory. Each
module in the node_modules directory maintains its own node_modules directory that contains any modules
that it depends on. Also, each required module has a node_modules directory. This recursive directory structure
represents the dependency chain.
This dependency chain structure results in a larger application footprint. But it also guarantees that all
dependencies are met and that the version of the modules that's used in development is also used in production.
This makes the production app behavior more predictable and prevents versioning problems that might affect
users.
Step 1: Register an Azure AD tenant
To use this sample, you need an Azure Active Directory tenant. If you're not sure what a tenant is or how to get
one, see How to get an Azure AD tenant.
Step 2: Create an application
Next you create an app in your directory that gives Azure AD information that it needs to securely communicate
with your app. Both the client app and web API are represented by a single Application ID in this case, because
they comprise one logical app. To create an app, follow these instructions. If you are building a line-of-business
app, these additional instructions might be useful.
To create an application:
1. Sign in to the Azure portal.
2. On the top menu, select your account. Then, under the Directory list, choose the Active Directory tenant
where you want to register your application.
3. In the menu on the left, select More Services, and then select Azure Active Directory.
4. Select App registrations, and then select Add.
5. Follow the prompts to create a Web Application and/or WebAPI.
The name of the application describes your application to end users.
The Sign-On URL is the base URL of your app. The default URL of the sample code is
https://localhost:8080 .
6. After you register, Azure AD assigns your app a unique Application ID. You need this value in the next
sections, so copy it from the application page.
7. From the Settings -> Properties page for your application, update the App ID URI. The App ID URI is a
unique identifier for your application. The convention is to use https://<tenant-domain>/<app-name> , for
example: https://contoso.onmicrosoft.com/my-first-aad-app .
8. Create a Key for your application from the Settings page, and then copy it somewhere. You'll need it
shortly.
Step 3: Download Node.js for your platform
To successfully use this sample, you must have a working installation of Node.js.
Install Node.js from http://nodejs.org.
Step 4: Install MongoDB on your platform
To successfully use this sample, you must have a working installation of MongoDB. You use MongoDB to make
the REST API persistent across server instances.
Install MongoDB from http://mongodb.org.
NOTE
This walkthrough assumes that you use the default installation and server endpoints for MongoDB, which at the time of this
writing is mongodb://localhost.
Step 5: Install the Restify modules in your web API
We are using Restify to build our REST API. Restify is a minimal and flexible Node.js application framework that's
derived from Express. It has a robust set of features for building REST APIs on top of Connect.
Install Restify
1. From the command line, change directories to the azuread directory. If the azuread directory does not
exist, create it.
`cd azuread - or- mkdir azuread; cd azuread`
2. Type the following command:
npm install restify
This command installs Restify.
Did you get an error?
When you use NPM on some operating systems, you might receive an error that says Error: EPERM, chmod
'/usr/local/bin/..' and a suggestion that you try running the account as an administrator. If this occurs, use the
sudo command to run NPM at a higher privilege level.
Did you get an error regarding DTRACE?
You might see an error like this when installing Restify:
clang: error: no such file or directory: 'HD/azuread/node_modules/restify/node_modules/dtraceprovider/libusdt'
make: *** [Release/DTraceProviderBindings.node] Error 1
gyp ERR! build error
gyp ERR! stack Error: `make` failed with exit code: 2
gyp ERR! stack
at ChildProcess.onExit (/usr/local/lib/node_modules/npm/node_modules/nodegyp/lib/build.js:267:23)
gyp ERR! stack
at ChildProcess.EventEmitter.emit (events.js:98:17)
gyp ERR! stack
at Process.ChildProcess._handle.onexit (child_process.js:789:12)
gyp ERR! System Darwin 13.1.0
gyp ERR! command "node" "/usr/local/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild"
gyp ERR! cwd /Volumes/Development HD/azuread/node_modules/restify/node_modules/dtrace-provider
gyp ERR! node -v v0.10.11
gyp ERR! node-gyp -v v0.10.0
gyp ERR! not ok
npm WARN optional dep failed, continuing [email protected]
Restify provides a powerful mechanism for tracing REST calls by using DTrace. However, many operating systems
do not have DTrace. You can safely ignore these errors.
The output of this command should look similar to the following output:
[email protected] node_modules/restify
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected] ([email protected])
├── [email protected]
├── [email protected] ([email protected], [email protected], [email protected])
└── [email protected] ([email protected])
Step 6: Install Passport.js in your web API
Passport is authentication middleware for Node.js. Flexible and modular, Passport can be unobtrusively dropped
in to any Express-based or Restify web application. A comprehensive set of strategies support authentication with
a username and password, Facebook, Twitter, and more.
We have developed a strategy for Azure Active Directory. We install this module and then add the Azure Active
Directory strategy plug-in.
1. From the command line, change directories to the azuread directory.
2. To install passport.js, enter the following command :
npm install passport
The output of the command should look similar to the following:
[email protected] node_modules\passport ├── [email protected] └── [email protected]
Step 7: Add Passport-Azure-AD to your web API
Next we add the OAuth strategy by using passport-azure-ad , a suite of strategies that connect Azure Active
Directory to Passport. We use this strategy for bearer tokens in this REST API sample.
NOTE
Although OAuth2 provides a framework in which any known token type can be issued, only certain token types are
commonly used. Bearer tokens are the most commonly used tokens for protecting endpoints. They are the most widely
issued type of token in OAuth2. Many implementations assume that bearer tokens are the only type of tokens that are
issued.
From the command line, change directories to the azuread directory.
Type the following command to install the Passport.js
passport-azure-ad module
npm install passport-azure-ad
The output of the command should look similar to the following output:
:
[email protected] node_modules/passport-azure-ad
├── [email protected]
├── [email protected]
├── [email protected] ([email protected])
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected] ([email protected])
├── [email protected] ([email protected], [email protected])
├── [email protected] ([email protected], [email protected])
├── [email protected] ([email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected],
[email protected], [email protected], [email protected], [email protected], [email protected], [email protected],
[email protected], [email protected], [email protected])
└── [email protected] ([email protected], [email protected])
Step 8: Add MongoDB modules to your web API
We use MongoDB as our datastore. For that reason, we need to install the widely used plug-in called Mongoose to
manage models and schemas. We also need to install the database driver for MongoDB (which is also called
MongoDB).
npm install mongoose
Step 9: Install additional modules
Next we install the remaining required modules.
1. From the command line, change directories to the azuread folder if you're not already there.
cd azuread
2. Enter the following commands to install these modules in your node_modules directory:
npm install assert-plus
npm install bunyan
npm update
Step 10: Create a server.js with your dependencies
The server.js file provides most of the functionality for our web API server. We add most of our code to this file.
For production purposes, we recommend that you refactor the functionality into smaller files, such as separate
routes and controllers. In this demo, we use server.js for this functionality.
1. From the command line, change directories to the azuread folder if you're not already there.
cd azuread
2. Create a
server.js
file in your favorite editor, and then add the following information:
'use strict';
/**
* Module dependencies.
*/
var fs = require('fs');
var path = require('path');
var util = require('util');
var assert = require('assert-plus');
var bunyan = require('bunyan');
var getopt = require('posix-getopt');
var mongoose = require('mongoose/');
var restify = require('restify');
var passport = require('passport');
var BearerStrategy = require('passport-azure-ad').BearerStrategy;
3. Save the file. We'll return to it shortly.
Step 11: Create a config file to store your Azure AD settings
This code file passes the configuration parameters from your Azure Active Directory portal to Passport.js. You
created these configuration values when you added the web API to the portal in the first part of the walkthrough.
We explain what to put in the values of these parameters after you copy the code.
1. From the command line, change directories to the azuread folder if you're not already there.
cd azuread
2. Create a
config.js
file in your favorite editor, and then add the following information:
exports.creds = {
mongoose_auth_local: 'mongodb://localhost/tasklist', // Your mongo auth uri goes here
clientID: 'your client ID',
audience: 'your application URL',
// you cannot have users from multiple tenants sign in to your server unless you use the common
endpoint
// example: https://login.microsoftonline.com/common/.well-known/openid-configuration
identityMetadata: 'https://login.microsoftonline.com/<your tenant id>/.well-known/openidconfiguration',
validateIssuer: true, // if you have validation on, you cannot have users from multiple
tenants sign in to your server
passReqToCallback: false,
loggingLevel: 'info' // valid are 'info', 'warn', 'error'. Error always goes to stderr in
Unix.
};
3. Save the file.
Step 12: Add configuration values to your server.js file
We need to read these values from the .config file that you created across our application. To do this, we add the
.config file as a required resource in our application. Then we set the global variables to match the variables in the
config.js document.
1. From the command line, change directories to the azuread folder if you're not already there.
cd azuread
2. Open your
server.js
file in your favorite editor, and then add the following information:
var config = require('./config');
3. Then add a new section to
server.js
with the following code:
var options = {
// The URL of the metadata document for your app. We will put the keys for token validation from
the URL found in the jwks_uri tag of the in the metadata.
identityMetadata: config.creds.identityMetadata,
clientID: config.creds.clientID,
validateIssuer: config.creds.validateIssuer,
audience: config.creds.audience,
passReqToCallback: config.creds.passReqToCallback,
loggingLevel: config.creds.loggingLevel
};
// Array to hold logged in users and the current logged in user (owner).
var users = [];
var owner = null;
// Our logger.
var log = bunyan.createLogger({
name: 'Azure Active Directory Bearer Sample',
streams: [
{
stream: process.stderr,
level: "error",
name: "error"
},
{
stream: process.stdout,
level: "warn",
name: "console"
}, ]
});
// If the logging level is specified, switch to it.
if (config.creds.loggingLevel) { log.levels("console", config.creds.loggingLevel); }
// MongoDB setup.
// Set up some configuration.
var serverPort = process.env.PORT || 8080;
var serverURI = (process.env.PORT) ? config.creds.mongoose_auth_mongohq :
config.creds.mongoose_auth_local;
4. Save the file.
Step 13: Add The MongoDB Model and schema information by using
Mongoose
Now all this preparation is going to start paying off as we combine these three files into a REST API service.
For this walkthrough, we use MongoDB to store our tasks as discussed in Step 4.
In the config.js file that we created in Step 11, we called our database tasklist , because that was what we put
at the end of our mogoose_auth_local connection URL. You don't need to create this database beforehand in
MongoDB. Instead, MongoDB creates this for us on the first run of our server application (assuming that the
database doesn't already exist).
Now that we've told the server which MongoDB database we'd like to use, we need to write some additional code
to create the model and schema for our server's tasks.
Discussion of the model
Our schema model is simple. You expand it as required.
NAME: The name of the person who is assigned to the task. A String.
TASK: The task itself. A String.
DATE: The date that the task is due. A DATETIME.
COMPLETED: If the task has been completed or not. A BOOLEAN.
Creating the schema in the code
1. From the command line, change directories to the azuread folder if you're not already there.
cd azuread
2. Open your server.js file in your favorite editor, and then add the following information below the
configuration entry:
// Connect to MongoDB.
global.db = mongoose.connect(serverURI);
var Schema = mongoose.Schema;
log.info('MongoDB Schema loaded');
// Here we create a schema to store our tasks and users. It's a fairly simple schema for now.
var TaskSchema = new Schema({
owner: String,
task: String,
completed: Boolean,
date: Date
});
// Use the schema to register a model.
mongoose.model('Task', TaskSchema);
var Task = mongoose.model('Task');
As you can tell from the code, we create our schema first. Then we create a model object that we use to
store our data throughout the code when we define our Routes.
Step 14: Add our routes for our task REST API server
Now that we have a database model to work with, let's add the routes we are going use for our REST API server.
About routes in Restify
Routes work in Restify the same way they do in the Express stack. You define routes by using the URI that you
expect the client applications to call. Usually, you define your routes in a separate file. For our purposes, we put
our routes in the server.js file. We recommend that you factor these routes into their own file for production use.
A typical pattern for a Restify route is as follows:
function createObject(req, res, next) {
// Do work on object.
_object.name = req.params.object; // passed value is in req.params under object
///...
return next(); // Keep the server going.
}
....
server.post('/service/:add/:object', createObject); // Calls createObject on routes that match this.
This is the pattern at its most basic level. Restify (and Express) provide much deeper functionality, such as defining
application types and providing complex routing across different endpoints. For our purposes, we are keeping
these routes simple.
Add default routes to our server
We now add the basic CRUD routes of Create, Retrieve, Update, and Delete.
1. From the command line, change directories to the azuread folder if you're not already there:
cd azuread
2. Open the server.js file in your favorite editor, and then add the following information below the previous
database entries that you made:
/**
*
* APIs for our REST Task server.
*/
// Create a task.
function createTask(req, res, next) {
// Restify currently has a bug which doesn't allow you to set default headers.
// These headers comply with CORS and allow us to mongodbServer our response to any origin.
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
// Create a new task model, fill it, and save it to Mongodb.
var _task = new Task();
if (!req.params.task) {
req.log.warn('createTodo: missing task');
next(new MissingTaskError());
return;
}
_task.owner = owner;
_task.task = req.params.task;
_task.date = new Date();
_task.save(function(err) {
if (err) {
req.log.warn(err, 'createTask: unable to save');
next(err);
} else {
res.send(201, _task);
}
});
return next();
}
// Delete a task by name.
function removeTask(req, res, next) {
Task.remove({
task: req.params.task,
owner: owner
}, function(err) {
if (err) {
req.log.warn(err,
'removeTask: unable to delete %s',
req.params.task);
next(err);
} else {
log.info('Deleted task:', req.params.task);
res.send(204);
next();
}
});
}
// Delete all tasks.
function removeAll(req, res, next) {
Task.remove();
res.send(204);
return next();
}
// Get a specific task based on name.
function getTask(req, res, next) {
log.info('getTask was called for: ', owner);
Task.find({
owner: owner
}, function(err, data) {
if (err) {
req.log.warn(err, 'get: unable to read %s', owner);
next(err);
return;
}
res.json(data);
});
return next();
}
/// Simple returns the list of TODOs that were loaded.
function listTasks(req, res, next) {
// Restify currently has a bug which doesn't allow you to set default headers.
// These headers comply with CORS and allow us to mongodbServer our response to any origin.
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
log.info("listTasks was called for: ", owner);
Task.find({
owner: owner
}).limit(20).sort('date').exec(function(err, data) {
if (err) {
return next(err);
}
if (data.length > 0) {
log.info(data);
}
if (!data.length) {
log.warn(err, "There is no tasks in the database. Did you initialize the database as stated in
the README?");
}
if (!owner) {
log.warn(err, "You did not pass an owner when listing tasks.");
} else {
res.json(data);
}
});
return next();
}
Add error handling in our APIs
///--- Errors for communicating something interesting back to the client.
function MissingTaskError() {
restify.RestError.call(this, {
statusCode: 409,
restCode: 'MissingTask',
message: '"task" is a required parameter',
constructorOpt: MissingTaskError
});
this.name = 'MissingTaskError';
}
util.inherits(MissingTaskError, restify.RestError);
function TaskExistsError(owner) {
assert.string(owner, 'owner');
restify.RestError.call(this, {
statusCode: 409,
restCode: 'TaskExists',
message: owner + ' already exists',
constructorOpt: TaskExistsError
});
this.name = 'TaskExistsError';
}
util.inherits(TaskExistsError, restify.RestError);
function TaskNotFoundError(owner) {
assert.string(owner, 'owner');
restify.RestError.call(this, {
statusCode: 404,
restCode: 'TaskNotFound',
message: owner + ' was not found',
constructorOpt: TaskNotFoundError
});
this.name = 'TaskNotFoundError';
}
util.inherits(TaskNotFoundError, restify.RestError);
Step 15: Create your server
We have defined our database and our routes are in place. The last thing to do is add the server instance that
manages our calls.
In Restify (and Express) you can do a lot of customization for a REST API server, but again we are going to use the
most basic setup for our purposes.
/**
* Our server.
*/
var server = restify.createServer({
name: "Azure Active Directroy TODO Server",
version: "2.0.1"
});
// Ensure we don't drop data on uploads.
server.pre(restify.pre.pause());
// Clean up sloppy paths like //todo//////1//.
server.pre(restify.pre.sanitizePath());
// Handle annoying user agents (curl).
server.pre(restify.pre.userAgentConnection());
// Set a per request bunyan logger (with requestid filled in).
server.use(restify.requestLogger());
// Allow five requests per second by IP, and burst to 10.
server.use(restify.throttle({
burst: 10,
rate: 5,
ip: true,
}));
// Use the common stuff you probably want.
server.use(restify.acceptParser(server.acceptable));
server.use(restify.dateParser());
server.use(restify.queryParser());
server.use(restify.gzipResponse());
server.use(restify.bodyParser({
mapParams: true
})); // Allow for JSON mapping to REST.
Step 16: Add the routes to the server (without authentication for now)
/// Now the real handlers. Here we just CRUD.
/**
/*
/* Each of these handlers is protected by our OIDCBearerStrategy by invoking 'oidc-bearer'.
/* In the pasport.authenticate() method. We set 'session: false' because REST is stateless and
/* we don't need to maintain session state. You can experiment with removing API protection
/* by removing the passport.authenticate() method as follows:
/*
/* server.get('/tasks', listTasks);
/*
**/
server.get('/tasks', listTasks);
server.get('/tasks', listTasks);
server.get('/tasks/:owner', getTask);
server.head('/tasks/:owner', getTask);
server.post('/tasks/:owner/:task', createTask);
server.post('/tasks', createTask);
server.del('/tasks/:owner/:task', removeTask);
server.del('/tasks/:owner', removeTask);
server.del('/tasks', removeTask);
server.del('/tasks', removeAll, function respond(req, res, next) {
res.send(204);
next();
});
// Register a default '/' handler.
server.get('/', function root(req, res, next) {
var routes = [
'GET /',
'POST /tasks/:owner/:task',
'POST /tasks (for JSON body)',
'GET /tasks',
'PUT /tasks/:owner',
'GET /tasks/:owner',
'DELETE /tasks/:owner/:task'
];
res.send(200, routes);
next();
});
server.listen(serverPort, function() {
var consoleMessage = '\n Microsoft Azure Active Directory Tutorial';
consoleMessage += '\n +++++++++++++++++++++++++++++++++++++++++++++++++++++';
consoleMessage += '\n %s server is listening at %s';
consoleMessage += '\n Open your browser to %s/tasks\n';
consoleMessage += '+++++++++++++++++++++++++++++++++++++++++++++++++++++ \n';
consoleMessage += '\n !!! why not try a $curl -isS %s | json to get some ideas? \n';
consoleMessage += '+++++++++++++++++++++++++++++++++++++++++++++++++++++ \n\n';
});
Step 17: Run the server (before adding OAuth support)
Test out your server before we add authentication.
The easiest way to test your server is by using curl in a command line. Before we do that, we need a utility that
allows us to parse output as JSON.
1. Install the following JSON tool (all the following examples use this tool):
$npm install -g jsontool
This installs the JSON tool globally. Now that we’ve accomplished that, let’s play with the server:
2. First, make sure that your mongoDB instance is running:
$sudo mongod
3. Then, change to the directory and start curling:
$ cd azuread
$ node server.js
$ curl -isS http://127.0.0.1:8080 | json
HTTP/1.1 200 OK
Connection: close
Content-Type: application/json
Content-Length: 171
Date: Tue, 14 Jul 2015 05:43:38 GMT
[
"GET /",
"POST /tasks/:owner/:task",
"POST /tasks (for JSON body)",
"GET /tasks",
"PUT /tasks/:owner",
"GET /tasks/:owner",
"DELETE /tasks/:owner/:task"
]
4. Then, we can add a task this way:
$ curl -isS -X POST http://127.0.0.1:8080/tasks/brandon/Hello
The response should be:
```Shell
HTTP/1.1 201 Created
Connection: close
Access-Control-Allow-Origin: *
Access-Control-Allow-Headers: X-Requested-With
Content-Type: application/x-www-form-urlencoded
Content-Length: 5
Date: Tue, 04 Feb 2014 01:02:26 GMT
Hello
```
And we can list tasks for Brandon this way:
`$ curl -isS http://127.0.0.1:8080/tasks/brandon/`
If all this works, we're ready to add OAuth to the REST API server.
You have a REST API server with MongoDB!
Step 18: Add authentication to our REST API server
Now that we have a running REST API, let's start making it useful with Azure AD.
From the command line, change directories to the azuread folder if you're not already there.
cd azuread
Use the OIDCBearerStrategy that is included with passport-azure -ad
So far we have built a typical REST TODO server without any kind of authorization. This is where we start putting
that together.
1. First, we need to indicate that we want to use Passport. Put this right after your other server configuration:
// Let's start using Passport.js.
server.use(passport.initialize()); // Starts passport.
server.use(passport.session()); // Provides session support.
TIP
When you write APIs, we recommend that you always link the data to something unique from the token that the
user can’t spoof. When this server stores TODO items, it stores them based on the object ID of the user in the token
(called through token.oid), which we put in the “owner” field. This ensures that only that user can access their
TODOs. There is no exposure in the API of “owner,” so an external user can request the TODOs of others even if
they are authenticated.
2. Next let’s use the bearer strategy that comes with passport-azure-ad . Look at the code for now and we'll
explain the rest shortly. Put this after what you pasted above:
/**
/*
/* Calling the OIDCBearerStrategy and managing users.
/*
/* Passport pattern provides the need to manage users and info tokens
/* with a FindorCreate() method that must be provided by the implementor.
/* Here we just auto-register any user and implement a FindById().
/* You'll want to do something smarter.
**/
var findById = function(id, fn) {
for (var i = 0, len = users.length; i < len; i++) {
var user = users[i];
if (user.sub === id) {
log.info('Found user: ', user);
return fn(null, user);
}
}
return fn(null, null);
};
var bearerStrategy = new BearerStrategy(options,
function(token, done) {
log.info('verifying the user');
log.info(token, 'was the token retreived');
findById(token.sub, function(err, user) {
if (err) {
return done(err);
}
if (!user) {
// "Auto-registration"
log.info('User was added automatically as they were new. Their sub is: ', token.sub);
users.push(token);
owner = token.sub;
return done(null, token);
}
owner = token.sub;
return done(null, user, token);
});
}
);
passport.use(bearerStrategy);
Passport uses a similar pattern for all its strategies (Twitter, Facebook, and so on) that all strategy writers adhere
to. Looking at the strategy, you see we pass it a function that has a token and a done as the parameters. The
strategy comes back to us after it does its work. After it does, we store the user and stash the token so we won’t
need to ask for it again.
IMPORTANT
The previous code takes any user that happens to authenticate to our server. This is known as auto-registration. In
production servers, you we recommend that you don't let anyone in without first having them go through a registration
process that you decide on. This is usually the pattern you see in consumer apps, which allow you to register with Facebook
but then ask you to fill out additional information. If this wasn’t a command-line program, we could have extracted the
email from the token object that is returned and then asked the user to fill out additional information. Because this is a test
server, we simply add them to the in-memory database.
Protect some endpoints
You protect endpoints by specifying the
passport.authenticate()
call with the protocol that you want to use.
To make our server code do something more interesting, let’s edit the route.
server.get('/tasks', passport.authenticate('oauth-bearer', {
session: false
}), listTasks);
server.get('/tasks', passport.authenticate('oauth-bearer', {
session: false
}), listTasks);
server.get('/tasks/:owner', passport.authenticate('oauth-bearer', {
session: false
}), getTask);
server.head('/tasks/:owner', passport.authenticate('oauth-bearer', {
session: false
}), getTask);
server.post('/tasks/:owner/:task', passport.authenticate('oauth-bearer', {
session: false
}), createTask);
server.post('/tasks', passport.authenticate('oauth-bearer', {
session: false
}), createTask);
server.del('/tasks/:owner/:task', passport.authenticate('oauth-bearer', {
session: false
}), removeTask);
server.del('/tasks/:owner', passport.authenticate('oauth-bearer', {
session: false
}), removeTask);
server.del('/tasks', passport.authenticate('oauth-bearer', {
session: false
}), removeTask);
server.del('/tasks', passport.authenticate('oauth-bearer', {
session: false
}), removeAll, function respond(req, res, next) {
res.send(204);
next();
});
Step 19: Run your server application again and ensure it rejects you
Let's use curl again to see if we now have OAuth2 protection against our endpoints. We do this test before
running any of our client SDKs against this endpoint. The headers that are returned should be enough to tell us if
we're going down the right path.
1. First, make sure that your mongoDB instance is running:
$sudo mongod
2. Then, change to the directory and start curling.
$ cd azuread
$ node server.js
3. Try a basic POST.
$ curl -isS -X POST http://127.0.0.1:8080/tasks/brandon/Hello
HTTP/1.1 401 Unauthorized
Connection: close
WWW-Authenticate: Bearer realm="Users"
Date: Tue, 14 Jul 2015 05:45:03 GMT
Transfer-Encoding: chunked
A 401 is the response you are looking for here. This response indicates that the Passport layer is trying to redirect
to the authorized endpoint, which is exactly what you want.
Next steps
You've gone as far as you can with this server without using an OAuth2 compatible client. You will need to go
through an additional walkthrough.
You've now learned how to implement a REST API by using Restify and OAuth2. You also have more than enough
code to keep developing your service and learning how to build on this example.
If you are interested in the next steps in your ADAL journey, here are some supported ADAL clients we
recommend that you keep working with.
Clone down to your developer machine and configure as described in the walkthrough.
ADAL for iOS
ADAL for Android
Additional resources
The Azure AD developer's guide
Azure AD samples on GitHub
CloudIdentity.com
Get security updates for our products
We encourage you to get notifications of when security incidents occur by visiting the TechCenter page for
Microsoft technical security notifications and subscribing to security advisory alerts.
Authentication Scenarios for Azure AD
4/27/2017 • 31 min to read • Edit Online
Azure Active Directory (Azure AD) simplifies authentication for developers by providing identity as a service, with
support for industry-standard protocols such as OAuth 2.0 and OpenID Connect, as well as open source libraries
for different platforms to help you start coding quickly. This document will help you understand the various
scenarios Azure AD supports and will show you how to get started. It’s divided into the following sections:
Basics of Authentication in Azure AD
Claims in Azure AD Security Tokens
Basics of Registering an Application in Azure AD
Application Types and Scenarios
Web Browser to Web Application
Single Page Application (SPA)
Native Application to Web API
Web Application to Web API
Daemon or Server Application to Web API
Basics of Authentication in Azure AD
If you are unfamiliar with basic concepts of authentication in Azure AD, read this section. Otherwise, you may
want to skip down to Application Types and Scenarios.
Let’s consider the most basic scenario where identity is required: a user in a web browser needs to authenticate to
a web application. This scenario is described in greater detail in the Web Browser to Web Application section, but
it’s a useful starting point to illustrate the capabilities of Azure AD and conceptualize how the scenario works.
Consider the following diagram for this scenario:
With the diagram above in mind, here’s what you need to know about its various components:
Azure AD is the identity provider, responsible for verifying the identity of users and applications that exist in an
organization’s directory, and ultimately issuing security tokens upon successful authentication of those users
and applications.
An application that wants to outsource authentication to Azure AD must be registered in Azure AD, which
registers and uniquely identifies the app in the directory.
Developers can use the open source Azure AD authentication libraries to make authentication easy by handling
the protocol details for you. See Azure Active Directory Authentication Libraries for more information.
• Once a user has been authenticated, the application must validate the user’s security token to ensure that
authentication was successful for the intended parties. Developers can use the provided authentication libraries to
handle validation of any token from Azure AD, including JSON Web Tokens (JWT) or SAML 2.0. If you want to
perform validation manually, see the JWT Token Handler documentation.
IMPORTANT
Azure AD uses public key cryptography to sign tokens and verify that they are valid. See Important Information About
Signing Key Rollover in Azure AD for more information on the necessary logic you must have in your application to ensure
it’s always updated with the latest keys.
• The flow of requests and responses for the authentication process is determined by the authentication protocol
that was used, such as OAuth 2.0, OpenID Connect, WS-Federation, or SAML 2.0. These protocols are discussed in
more detail in the Azure Active Directory Authentication Protocols topic and in the sections below.
NOTE
Azure AD supports the OAuth 2.0 and OpenID Connect standards that make extensive use of bearer tokens, including
bearer tokens represented as JWTs. A bearer token is a lightweight security token that grants the “bearer” access to a
protected resource. In this sense, the “bearer” is any party that can present the token. Though a party must first
authenticate with Azure AD to receive the bearer token, if the required steps are not taken to secure the token in
transmission and storage, it can be intercepted and used by an unintended party. While some security tokens have a builtin mechanism for preventing unauthorized parties from using them, bearer tokens do not have this mechanism and must
be transported in a secure channel such as transport layer security (HTTPS). If a bearer token is transmitted in the clear, a
man-in the middle attack can be used by a malicious party to acquire the token and use it for an unauthorized access to a
protected resource. The same security principles apply when storing or caching bearer tokens for later use. Always ensure
that your application transmits and stores bearer tokens in a secure manner. For more security considerations on bearer
tokens, see RFC 6750 Section 5.
Now that you have an overview of the basics, read the sections below to understand how provisioning works in
Azure AD and the common scenarios Azure AD supports.
Claims in Azure AD Security Tokens
Security tokens issued by Azure AD contain claims, or assertions of information about the subject that has been
authenticated. These claims can be used by the application for various tasks. For example, they can be used to
validate the token, identify the subject's directory tenant, display user information, determine the subject's
authorization, and so on. The claims present in any given security token are dependent upon the type of token, the
type of credential used to authenticate the user, and the application configuration. A brief description of each type
of claim emitted by Azure AD is provided in the table below. For more information, refer to Supported Token and
Claim Types.
CLAIM
DESCRIPTION
Application ID
Identifies the application that is using the token.
Audience
Identifies the recipient resource the token is intended for.
Application Authentication Context Class Reference
Indicates how the client was authenticated (public client vs.
confidential client).
CLAIM
DESCRIPTION
Authentication Instant
Records the date and time when the authentication occurred.
Authentication Method
Indicates how the subject of the token was authenticated
(password, certificate, etc.).
First Name
Provides the given name of the user as set in Azure AD.
Groups
Contains object Ids of Azure AD groups the user is a member
of.
Identity Provider
Records the identity provider that authenticated the subject
of the token.
Issued At
Records the time at which the token was issued, often used
for token freshness.
Issuer
Identifies the STS that emitted the token as well as the Azure
AD tenant.
Last Name
Provides the surname of the user as set in Azure AD.
Name
Provides a human readable value that identifies the subject of
the token.
Object Id
Contains an immutable, unique identifier of the subject in
Azure AD.
Roles
Contains friendly names of Azure AD Application Roles that
the user has been granted.
Scope
Indicates the permissions granted to the client application.
Subject
Indicates the principal about which the token asserts
information.
Tenant Id
Contains an immutable, unique identifier of the directory
tenant that issued the token.
Token Lifetime
Defines the time interval within which a token is valid.
User Principal Name
Contains the user principal name of the subject.
Version
Contains the version number of the token.
Basics of Registering an Application in Azure AD
Any application that outsources authentication to Azure AD must be registered in a directory. This step involves
telling Azure AD about your application, including the URL where it’s located, the URL to send replies after
authentication, the URI to identify your application, and more. This information is required for a few key reasons:
Azure AD needs coordinates to communicate with the application when handling sign-on or exchanging
tokens. These include the following:
Application ID URI: The identifier for an application. This value is sent to Azure AD during authentication
to indicate which application the caller wants a token for. Additionally, this value is included in the token
so that the application knows it was the intended target.
Reply URL and Redirect URI: In the case of a web API or web application, the Reply URL is the location to
which Azure AD will send the authentication response, including a token if authentication was
successful. In the case of a native application, the Redirect URI is a unique identifier to which Azure AD
will redirect the user-agent in an OAuth 2.0 request.
Application ID: The ID for an application, which is generated by Azure AD when the application is
registered. When requesting an authorization code or token, the Application ID and key are sent to
Azure AD during authentication.
Key: The key that is sent along with a Application ID when authenticating to Azure AD to call a web API.
Azure AD needs to ensure the application has the required permissions to access your directory data, other
applications in your organization, and so on
Provisioning becomes clearer when you understand that there are two categories of applications that can be
developed and integrated with Azure AD:
Single tenant application: A single tenant application is intended for use in one organization. These are typically
line-of-business (LoB) applications written by an enterprise developer. A single tenant application only needs
to be accessed by users in one directory, and as a result, it only needs to be provisioned in one directory. These
applications are typically registered by a developer in the organization.
Multi-tenant application: A multi-tenant application is intended for use in many organizations, not just one
organization. These are typically software-as-a-service (SaaS) applications written by an independent software
vendor (ISV). Multi-tenant applications need to be provisioned in each directory where they will be used, which
requires user or administrator consent to register them. This consent process starts when an application has
been registered in the directory and is given access to the Graph API or perhaps another web API. When a user
or administrator from a different organization signs up to use the application, they are presented with a dialog
that displays the permissions the application requires. The user or administrator can then consent to the
application, which gives the application access to the stated data, and finally registers the application in their
directory. For more information, see Overview of the Consent Framework.
Some additional considerations arise when developing a multi-tenant application instead of a single tenant
application. For example, if you are making your application available to users in multiple directories, you need a
mechanism to determine which tenant they’re in. A single tenant application only needs to look in its own
directory for a user, while a multi-tenant application needs to identify a specific user from all the directories in
Azure AD. To accomplish this task, Azure AD provides a common authentication endpoint where any multi-tenant
application can direct sign-in requests, instead of a tenant-specific endpoint. This endpoint is
https://login.microsoftonline.com/common for all directories in Azure AD, whereas a tenant-specific endpoint
might be https://login.microsoftonline.com/contoso.onmicrosoft.com. The common endpoint is especially
important to consider when developing your application because you’ll need the necessary logic to handle
multiple tenants during sign-in, sign-out, and token validation.
If you are currently developing a single tenant application but want to make it available to many organizations,
you can easily make changes to the application and its configuration in Azure AD to make it multi-tenant capable.
In addition, Azure AD uses the same signing key for all tokens in all directories, whether you are providing
authentication in a single tenant or multi-tenant application.
Each scenario listed in this document includes a sub-section that describes its provisioning requirements. For
more in-depth information about provisioning an application in Azure AD and the differences between single and
multi-tenant applications, see Integrating Applications with Azure Active Directory for more information. Continue
reading to understand the common application scenarios in Azure AD.
Application Types and Scenarios
Each of the scenarios described in this document can be developed using various languages and platforms. They
are all backed by complete code samples which are available in our Code Samples guide, or directly from the
corresponding GitHub sample repositories. In addition, if your application needs a specific piece or segment of an
end-to-end scenario, in most cases that functionality can be added independently. For example, if you have a
native application that calls a web API, you can easily add a web application that also calls the web API. The
following diagram illustrates these scenarios and application types, and how different components can be added:
These are the five primary application scenarios 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 user needs to sign in to a single page application that is secured by Azure AD.
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.
Web Browser to Web Application
This section describes an application that authenticates a user in a web browser to a web application. In this
scenario, the web application directs the user’s browser to sign them in to Azure AD. Azure AD returns a sign-in
response through the user’s browser, which contains claims about the user in a security token. This scenario
supports sign-on using the WS-Federation, SAML 2.0, and OpenID Connect protocols.
Diagram
Description of Protocol Flow
1. When a user visits the application and needs to sign in, they are redirected via a sign-in request to the
authentication endpoint in Azure AD.
2. The user signs in on the sign-in page.
3. If authentication is successful, Azure AD creates an authentication token and returns a sign-in response to the
application’s Reply URL that was configured in the Azure Portal. For a production application, this Reply URL
should be HTTPS. The returned token includes claims about the user and Azure AD that are required by the
application to validate the token.
4. The application validates the token by using a public signing key and issuer information available at the
federation metadata document for Azure AD. After the application validates the token, Azure AD starts a new
session with the user. This session allows the user to access the application until it expires.
Code Samples
See the code samples for Web Browser to Web Application scenarios. And, check back frequently -- we add new
samples all the time. Web Browser to Web Application.
Registering
Single Tenant: If you are building an application just for your organization, it must be registered in your
company’s directory by using the Azure Portal.
Multi-Tenant: If you are building an application that can be used by users outside your organization, it must 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 your application available in their directory, you can include a sign-up process
for your customers that enables them to consent to your application. When they sign up for your application,
they will be presented with a dialog that shows the permissions the application requires, and then the option
to consent. Depending on the required permissions, an administrator in the other organization may be
required to give consent. When the user or administrator consents, the application is registered in their
directory. For more information, see Integrating Applications with Azure Active Directory.
Token Expiration
The user’s session expires when the lifetime of the token issued by Azure AD expires. Your application can shorten
this time period if desired, such as signing out users based on a period of inactivity. When the session expires, the
user will be prompted to sign in again.
Single Page Application (SPA )
This section describes authentication for a Single Page Application, that uses Azure AD and the OAuth 2.0 implicit
authorization grant to secure its web API back end. 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. To learn more about the implicit authorization grant, and help
you decide whether it's right for your application scenario, see Understanding the OAuth2 implicit grant flow in
Azure Active Directory.
In this scenario, when the user signs in, the JavaScript front end uses Active Directory Authentication Library for
JavaScript (ADAL.JS) and the implicit authorization grant to obtain an ID token (id_token) from Azure AD. The
token is cached and the client attaches it to the request as the bearer token when making calls to its Web API back
end, which is secured using the OWIN middleware.
Diagram
Description of Protocol Flow
1. The user navigates to the web application.
2. The application returns the JavaScript front end (presentation layer) to the browser.
3. The user initiates sign in, for example by clicking a sign in link. The browser sends a GET to the Azure AD
authorization endpoint to request an ID token. This request includes the application ID and reply URL in the
query parameters.
4. Azure AD validates the Reply URL against the registered Reply URL that was configured in the Azure Portal.
5. The user signs in on the sign-in page.
6. If authentication is successful, Azure AD creates an ID token and returns it as a URL fragment (#) to the
application’s Reply URL. For a production application, this Reply URL should be HTTPS. The returned token
includes claims about the user and Azure AD that are required by the application to validate the token.
7. The JavaScript client code running in the browser extracts the token from the response to use in securing calls
to the application’s web API back end.
8. The browser calls the application’s web API back end with the access token in the authorization header.
Code Samples
See the code samples for Single Page Application (SPA) scenarios. Be sure to check back frequently -- we add new
samples all the time. Single Page Application (SPA).
Registering
Single Tenant: If you are building an application just for your organization, it must be registered in your
company’s directory by using the Azure Portal.
Multi-Tenant: If you are building an application that can be used by users outside your organization, it must 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 your application available in their directory, you can include a sign-up process
for your customers that enables them to consent to your application. When they sign up for your application,
they will be presented with a dialog that shows the permissions the application requires, and then the option
to consent. Depending on the required permissions, an administrator in the other organization may be
required to give consent. When the user or administrator consents, the application is registered in their
directory. For more information, see Integrating Applications with Azure Active Directory.
After registering the application, it must be configured to use OAuth 2.0 Implicit Grant protocol. By default, this
protocol is disabled for applications. To enable the OAuth2 Implicit Grant protocol for your application, edit its
application manifest from the Azure Portal and set the “oauth2AllowImplicitFlow” value to true. For detailed
instructions, see Enabling OAuth 2.0 Implicit Grant for Single Page Applications.
Token Expiration
When you use ADAL.js to manage authentication with Azure AD, you benefit from several features that facilitate
refreshing an expired token as well as getting tokens for additional web API resources that may be called by the
application. When the user successfully authenticates with Azure AD, a session secured by a cookie is established
for the user between the browser and Azure AD. It’s important to note that the session exists between the user
and Azure AD and not between the user and the web application running on the server. When a token expires,
ADAL.js uses this session to silently obtain another token. It does this by using a hidden iFrame to send and
receive the request using the OAuth Implicit Grant protocol. ADAL.js can also use this same mechanism to silently
obtain access tokens from Azure AD for other web API resources that the application calls as long as these
resources support cross-origin resource sharing (CORS), are registered in the user’s directory, and any required
consent was given by the user during sign-in.
Native Application to Web API
This section describes a native application that calls a web API on behalf of a user. This scenario is built on the
OAuth 2.0 authorization code grant type with a public client, as described in section 4.1 of the OAuth 2.0
specification. The native application obtains an access token for the user by using the OAuth 2.0 protocol. This
access token is then sent in the request to the web API, which authorizes the user and returns the desired
resource.
Diagram
Authentication flow for native application to API
Description of Protocol Flow
If you are using the AD Authentication Libraries, most of the protocol details described below are handled for you,
such as the browser pop-up, token caching, and handling of refresh tokens.
1. Using a browser pop-up, the native application makes a request to the authorization endpoint in Azure AD.
This request includes the Application ID and the redirect URI of the native application as shown in the Azure
Portal, and the application ID URI for the web API. If the user hasn’t already signed in, they are prompted to
sign in again
2. Azure AD authenticates the user. If it is a multi-tenant application and consent is required to use the
3.
4.
5.
6.
application, the user will be required to consent if they haven’t already done so. After granting consent and
upon successful authentication, Azure AD issues an authorization code response back to the client application’s
redirect URI.
When Azure AD issues an authorization code response back to the redirect URI, the client application stops
browser interaction and extracts the authorization code from the response. Using this authorization code, the
client application sends a request to Azure AD’s token endpoint that includes the authorization code, details
about the client application (Application ID and redirect URI), and the desired resource (application ID URI for
the web API).
The authorization code and information about the client application and web API are validated by Azure AD.
Upon successful validation, Azure AD returns two tokens: a JWT access token and a JWT refresh token. In
addition, Azure AD returns basic information about the user, such as their display name and tenant ID.
Over HTTPS, the client 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
token, and if validation is successful, returns the desired resource.
When the access token expires, the client application will receive an error that indicates the user needs to
authenticate again. If the application has a valid refresh token, it can be used to acquire a new access token
without prompting the user to sign in again. If the refresh token expires, the application will need to
interactively authenticate the user once again.
NOTE
The refresh token issued by Azure AD can be used to access multiple resources. For example, if you have a client application
that has permission to call two web APIs, the refresh token can be used to get an access token to the other web API as well.
Code Samples
See the code samples for Native Application to Web API scenarios. And, check back frequently -- we add new
samples all the time. Native Application to Web API.
Registering
Single Tenant: Both the native application and the web API must be registered in the same directory in Azure
AD. The web API can be configured to expose a set of permissions, which are used to limit the native
application’s access to its resources. The client application then selects the desired permissions from the
“Permissions to Other Applications” drop-down menu in the Azure Portal.
Multi-Tenant: First, the native application only ever registered in the developer or publisher’s directory. Second,
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, which any user in the organization can consent to. Other applications require administrator-level
permissions, which a user in the organization cannot consent to. Only a directory administrator can give
consent to applications that require this level of permissions. When the user or administrator consents, only
the web API is registered in their directory. For more information, see Integrating Applications with Azure
Active Directory.
Token Expiration
When the native application uses its authorization code to get a JWT access token, it also receives a JWT refresh
token. When the access token expires, the refresh token can be used to re-authenticate the user without requiring
them to sign in again. This refresh token is then used to authenticate the user, which results in a new access token
and refresh token.
Web Application to Web API
This section describes a web application that needs to get resources from a web API. In this scenario, there are two
identity types that the web application can use to authenticate and call the web API: an application identity, or a
delegated user identity.
Application identity: This scenario uses OAuth 2.0 client credentials grant to authenticate as the application and
access the web API. 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 via the application protocol, and 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.
Delegated user identity: This scenario can be accomplished in two ways: OpenID Connect, and OAuth 2.0
authorization code grant with a confidential client. 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.
Diagram
Description of Protocol Flow
Both the application identity and delegated user identity types are discussed in the flow below. The key difference
between them is that the delegated user identity must first acquire an authorization code before the user can
sign-in and gain access to the web API.
A p p l i c a t i o n I d e n t i t y w i t h O A u t h 2 .0 C l i e n t C r e d e n t i a l s G r a n t
1. A user is signed in to Azure AD in the web application (see the Web Browser to Web Application above).
2. The web application needs to acquire an access token so that it can authenticate to the web API and retrieve
the desired resource. It makes a request to Azure AD’s token endpoint, providing the credential, Application ID,
and web API’s application ID URI.
3. Azure AD authenticates the application and returns a JWT access token that is used to call the web API.
4. Over HTTPS, 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
token, and if validation is successful, returns the desired resource.
D e l e g a t e d U se r I d e n t i t y w i t h O p e n I D C o n n e c t
1. A user is signed in to a web application using Azure AD (see the Web Browser to Web Application section
above). 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 application will display the permissions it requires, and if
any of these are administrator-level permissions, a normal user in the directory will not be able to consent.
This consent process only applies to multi-tenant applications, not single tenant applications, as the application
will already have the necessary permissions. When the user signed in, the web application received an ID token
with information about the user, as well as an authorization code.
2. Using the authorization code issued by Azure AD, the web application sends a request to Azure AD’s token
endpoint that includes the authorization code, details about the client application (Application ID and redirect
URI), and the desired resource (application ID URI for the web API).
3. The authorization code and information about the web application and web API are validated by Azure AD.
Upon successful validation, Azure AD returns two tokens: a JWT access token and a JWT refresh token.
4. Over HTTPS, 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
token, and if validation is successful, returns the desired resource.
D e l e g a t e d U se r I d e n t i t y w i t h O A u t h 2 .0 A u t h o r i z a t i o n C o d e G r a n t
1. A user is already signed in to a web application, whose authentication mechanism is independent of Azure AD.
2. The web application requires an authorization code to acquire an access token, so it issues a request through
the browser to Azure AD’s authorization endpoint, providing the Application ID and redirect URI for the web
application after successful authentication. The user signs in to Azure AD.
3. 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 application will display the permissions it requires, and if any of
these are administrator-level permissions, a normal user in the directory will not be able to consent. This
consent process only applies to multi-tenant applications, not single tenant applications, as the application will
already have the necessary permissions.
4. After the user has consented, the web application receives the authorization code that it needs to acquire an
access token.
5. Using the authorization code issued by Azure AD, the web application sends a request to Azure AD’s token
endpoint that includes the authorization code, details about the client application (Application ID and redirect
URI), and the desired resource (application ID URI for the web API).
6. The authorization code and information about the web application and web API are validated by Azure AD.
Upon successful validation, Azure AD returns two tokens: a JWT access token and a JWT refresh token.
7. Over HTTPS, 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
token, and if validation is successful, returns the desired resource.
Code Samples
See the code samples for Web Application to Web API scenarios. And, check back frequently -- we add new
samples all the time. Web Application to Web API.
Registering
Single Tenant: For both the application identity and delegated user identity cases, the web application and the
web API must be registered in the same directory in Azure AD. The web API can be configured to expose a set
of permissions, which are used to limit the web application’s access to its resources. If a delegated user identity
type is being used, the web application needs to select the desired permissions from the “Permissions to Other
Applications” drop-down menu in the Azure Portal. This step is not required if the application identity type is
being used.
Multi-Tenant: First, the web 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, which any user in the organization can consent to. Other applications require
administrator-level permissions, which a user in the organization cannot consent to. Only a directory
administrator can give consent to applications that require this level of permissions. When the user or
administrator consents, the web application and the web API are both registered in their directory.
Token Expiration
When the web application uses its authorization code to get a JWT access token, it also receives a JWT refresh
token. When the access token expires, the refresh token can be used to re-authenticate the user without requiring
them to sign in again. This refresh token is then used to authenticate the user, which results in a new access token
and refresh token.
Daemon or Server Application to Web API
This section describes a daemon or server application that needs to get resources from a web API. There are two
sub-scenarios that apply to this section: A daemon that needs to call a web API, built on OAuth 2.0 client
credentials grant type; and a server application (such as a web API) that needs to call a web API, built on OAuth 2.0
On-Behalf-Of draft specification.
For the scenario when a daemon application needs to call a web API, it’s important to understand a few things.
First, user interaction is not possible with a daemon application, which requires the application to have its own
identity. An example of a daemon application is a batch job, or an operating system service running in the
background. This type of application requests an access token by using its application identity and presenting its
Application 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.
For the scenario when a server application needs to call a web API, it’s helpful to use an example. Imagine that a
user has authenticated on a native application, and this native application needs to call a web API. Azure AD issues
a JWT access token to call the web API. If the 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.
Diagram
Description of Protocol Flow
A p p l i c a t i o n I d e n t i t y w i t h O A u t h 2 .0 C l i e n t C r e d e n t i a l s G r a n t
1. First, the server application needs to authenticate with Azure AD as itself, without any human interaction such
as an interactive sign-on dialog. It makes a request to Azure AD’s token endpoint, providing the credential,
Application ID, and application ID URI.
2. Azure AD authenticates the application and returns a JWT access token that is used to call the web API.
3. Over HTTPS, 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
token, and if validation is successful, returns the desired resource.
D e l e g a t e d U se r I d e n t i t y w i t h O A u t h 2 .0 O n - B e h a l f- O f D r a ft Sp e c i fi c a t i o n
The flow discussed below assumes that a user has been authenticated on another application (such as a native
application), and their user identity has been used to acquire an access token to the first-tier web API.
1. The native application sends the access token to the first-tier web API.
2. The first-tier web API sends a request to Azure AD’s token endpoint, providing its Application ID and
credentials, as well as the user’s 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.
3. 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.
4. 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.
Code Samples
See the code samples for Daemon or Server Application to Web API scenarios. And, check back frequently -- we
add new samples all the time. Server or Daemon Application to Web API
Registering
Single Tenant: For both the application identity and delegated user identity cases, the daemon or server
application must be registered in the same directory in Azure AD. The web API can be configured to expose a
set of permissions, which are used to limit the daemon or server’s access to its resources. If a delegated user
identity type is being used, the server application needs to select the desired permissions from the
“Permissions to Other Applications” drop-down menu in the Azure Portal. This step is not required if the
application identity type is being used.
Multi-Tenant: First, the daemon or server 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, which any user in the organization can consent to. Other
applications require administrator-level permissions, which a user in the organization cannot consent to. Only
a directory administrator can give consent to applications that require this level of permissions. When the user
or administrator consents, both of the web APIs are registered in their directory.
Token Expiration
When the first application uses its authorization code to get a JWT access token, it also receives a JWT refresh
token. When the access token expires, the refresh token can be used to re-authenticate the user without
prompting for credentials. This refresh token is then used to authenticate the user, which results in a new access
token and refresh token.
See Also
Azure Active Directory Developer's Guide
Azure Active Directory Code Samples
Important Information About Signing Key Rollover in Azure AD
OAuth 2.0 in Azure AD
Azure Active Directory Code Samples
2/13/2017 • 6 min to read • Edit Online
NOTE
This article is part of the Azure Active Directory developer's guide.
You can use Microsoft Azure Active Directory (Azure AD) to add authentication and authorization to your web
applications and web APIs. This section links you to samples that show you how it's done and code snippets that
you can use in your applications. On the code sample page, 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.
To understand the basic scenario for each sample type, see Authentication Scenarios for Azure AD.
Contribute to our samples on GitHub: Microsoft Azure Active Directory Samples and Documentation.
Web Browser to Web Application
These samples show how to write a web application that directs the user’s browser to sign them in to Azure AD.
LANGUAGE/PLATFORM
SAMPLE
DESCRIPTION
C#/.NET
WebApp-OpenIDConnect-DotNet
Use OpenID Connect (ASP.Net OpenID
Connect OWIN middleware) to
authenticate users from an Azure AD
tenant.
C#/.NET
WebApp-MultiTenant-OpenIdConnectDotNet
A multi-tenant .NET MVC web
application that uses OpenID Connect
(ASP.Net OpenID Connect OWIN
middleware) to authenticate users from
multiple Azure AD tenants.
C#/.NET
WebApp-WSFederation-DotNet
Use WS-Federation (ASP.Net WSFederation OWIN middleware) to
authenticate users from an Azure AD
tenant.
Single Page Application (SPA)
This sample shows how to write a single page application secured with Azure AD.
LANGUAGE/PLATFORM
SAMPLE
DESCRIPTION
JavaScript, C#/.NET
SinglePageApp-DotNet
Use ADAL for JavaScript and Azure AD
to secure an AngularJS-based single
page app implemented with an ASP.NET
web API back end.
Native Application to Web API
These code samples show how to build native client applications that call web APIs that are secured by Azure AD.
They use Azure AD Authentication Library (ADAL) and OAuth 2.0 in Azure AD.
LANGUAGE/PLATFORM
SAMPLE
DESCRIPTION
Javascript
NativeClient-MultiTarget-Cordova
Use the ADAL plugin for Apache
Cordova to build an Apache Cordova
app that calls a web API and uses Azure
AD for authentication.
C#/.NET
NativeClient-DotNet
A .NET WPF application that calls a web
API that is secured by using Azure AD.
C#/.NET
NativeClient-WindowsStore
A Windows Store application that calls a
web API that is secured with Azure AD.
C#/.NET
NativeClient-WebAPI-MultiTenantWindowsStore
A Windows Store application calling a
multi-tenant web API that is secured
with Azure AD.
C#/.NET
WebAPI-OnBehalfOf-DotNet
A native client application that calls a
web API, which gets a token to act on
behalf of the original user, and then
uses the token to call another web API.
C#/.NET
NativeClient-WindowsPhone8.1
A Windows Store application for
Windows Phone 8.1 that calls a web API
that is secured by Azure AD.
ObjC
NativeClient-iOS
An iOS application that calls a web API
that requires Azure AD for
authentication.
C#/.NET
WebAPI-ManuallyValidateJwt-DotNet
A native client application that includes
logic to process a JWT token in a web
API, instead of using OWIN middleware.
C#/Xamarin
NativeClient-Xamarin-Android
A Xamarin binding to the native Azure
AD Authentication Library (ADAL) for
the Android library.
C#/Xamarin
NativeClient-Xamarin-iOS
A Xamarin binding to the native Azure
AD Authentication Library (ADAL) for
iOS.
C#/Xamarin
NativeClient-MultiTarget-DotNet
A Xamarin project that targets five
platforms and calls a web API that is
secured by Azure AD.
C#/.NET
NativeClient-Headless-DotNet
A native application that performs noninteractive authentication and calls a
web API that is secured by Azure AD.
Web Application to Web API
These code samples show how use OAuth 2.0 in Azure AD to build web applications that call web APIs that are
secured by Azure AD.
LANGUAGE/PLATFORM
SAMPLE
DESCRIPTION
C#/.NET
WebApp-WebAPI-OpenIDConnectDotNet
Call a web API with the signed-in user's
permissions.
C#/.NET
WebApp-WebAPI-OAuth2-AppIdentityDotNet
Call a web API with the application's
permissions.
C#/.NET
WebApp-WebAPI-OAuth2UserIdentity-Dotnet
Add authorization with OAuth 2.0 in
Azure AD to an existing web application
so it can call a web API.
JavaScript
WebAPI-Nodejs
Set up a REST API service that's
integrated with Azure AD for API
protection. Includes a Node.js server
with a Web API.
C#/.NET
WebApp-WebAPI-MultiTenantOpenIdConnect-DotNet
A multi-tenant MVC web application
that uses OpenID Connect (ASP.Net
OpenID Connect OWIN middleware) to
authenticate users from an Azure AD
tenant. Uses an authorization code to
invoke the Graph API.
Server or Daemon Application to Web API
These code samples show how to build a daemon or server application that gets resources from a web API by using
Azure AD Authentication Library (ADAL) and OAuth 2.0 in Azure AD.
LANGUAGE/PLATFORM
SAMPLE
DESCRIPTION
C#/.NET
Daemon-DotNet
A console application calls a web API.
The client credential is a password.
C#/.NET
Daemon-CertificateCredential-DotNet
A console application that calls a web
API. The client credential is a certificate.
Calling Azure AD Graph API
These code sample show how to build applications that call the Azure AD Graph API to read and write directory
data.
LANGUAGE/PLATFORM
SAMPLE
DESCRIPTION
Java
WebApp-GraphAPI-Java
A web application that uses the Graph
API to access Azure AD directory data.
PHP
WebApp-GraphAPI-PHP
A web application that uses the Graph
API to access Azure AD directory data.
C#/.NET
WebApp-GraphAPI-DotNet
A web application that uses the Graph
API to access Azure AD directory data.
LANGUAGE/PLATFORM
SAMPLE
DESCRIPTION
C#/.NET
ConsoleApp-GraphAPI-DotNet
This console app demonstrates common
Read and Write calls to the Graph API,
and shows how to execute user license
assignment and update a user's
thumbnail photo and links.
C#/.NET
ConsoleApp-GraphAPI-DiffQueryDotNet
A console application that uses the
differential query in the Graph API to
get periodic changes to user objects in
an Azure AD tenant.
C#/.NET
WebApp-GraphAPIDirectoryExtensions-DotNet
An MVC application uses Graph API
queries to generate a simple company
organizational chart.
PHP
WebApp-GraphAPIDirectoryExtensions-PHP
A PHP application that calls the Graph
API to register an extension and then
read, update, and delete values in the
extension attribute.
Authorization
These code samples show how to use Azure AD for authorization.
LANGUAGE/PLATFORM
SAMPLE
DESCRIPTION
C#/.NET
WebApp-GroupClaims-DotNet
Perform role based access control
(RBAC) using Azure Active Directory
group claims in an application that is
integrated with Azure AD.
C#/.NET
WebApp-RoleClaims-DotNet
Perform role based access control
(RBAC) using Azure Active Directory
application roles in an application that is
integrated with Azure AD.
Legacy Walkthroughs
These walkthroughs use slightly older technology, but still might be of interest.
LANGUAGE/PLATFORM
SAMPLE
DESCRIPTION
C#/.NET
Role-Based and ACL-Based
Authorization in a Microsoft Azure AD
Application
Perform role-based authorization
(RBAC) and ACL-based authorization in
an application that is integrated with
Azure AD.
C#/.NET
AAL - Windows Store app to REST
service - Authentication
Use Azure AD Authentication Library
(ADAL) (formerly AAL) for Windows
Store Beta to add user authentication
capabilities to a Windows Store app.
LANGUAGE/PLATFORM
SAMPLE
DESCRIPTION
C#/.NET
ADAL - Native App to REST service Authentication with AAD via Browser
Dialog
Use Azure AD Authentication Library
(ADAL) to add user authentication
capabilities to a WPF client.
C#/.NET
ADAL - Native App to REST service Authentication with ACS via Browser
Dialog
Use Azure AD Authentication Library
(ADAL) and Access Control Service 2.0
(ACS) to add user authentication
capabilities to a WPF client.
C#/.NET
ADAL - Server to Server Authentication
Use Azure AD Authentication Library
(ADAL) to secure service calls from a
server side process to an MVC4 Web
API REST service.
C#/.NET
Adding Sign-On to Your Web
Application Using Azure AD
Configure a .NET application to perform
web single sign-on against your Azure
AD enterprise directory.
C#/.NET
Developing Multi-Tenant Web
Applications with Azure AD
Use Azure AD to add to the single signon and directory access capabilities of
one .NET application to work across
multiple organizations.
JAVA
Java Sample App for Azure AD Graph
API
Use the Graph API to access directory
data from Azure AD.
PHP
PHP Sample App for Azure AD Graph
API
Use the Graph API to access directory
data from Azure AD.
C#/.NET
Sample App for Azure AD Graph API
Use the Graph API to access directory
data from Azure AD.
C#/.NET
Sample App for Azure AD Graph
Differential Query
Use the differential query in the Graph
API to get periodic changes to user
objects in an Azure AD tenant.
C#/.NET
Sample App for Integrating MultiTenant Cloud Application for Azure AD
Integrate a multi-tenant application into
Azure AD.
C#/.NET
Securing a Windows Store Application
and REST Web Service Using Azure AD
Create a simple web API resource and a
Windows Store client application using
Azure AD and the Azure AD
Authentication Library (ADAL).
C#/.NET
Using the Graph API to Query Azure AD
Configure a Microsoft .NET application
to use the Azure AD Graph API to
access data from an Azure AD tenant
directory.
See also
O t h e r R e so u r c e s
Azure Active Directory Developer's Guide
Azure AD Graph API Conceptual and Reference
Azure AD Graph API Helper Library
Service to service calls using client credentials
2/13/2017 • 2 min to read • Edit Online
The OAuth 2.0 Client Credentials Grant Flow permits a web service (a confidential client) to use its own
credentials to authenticate when calling another web service, instead of impersonating a user. In this scenario, the
client is typically a middle-tier web service, a daemon service, or web site.
Client credentials grant flow diagram
The following diagram explains how the client credentials grant flow works in Azure Active Directory (Azure AD).
1.
2.
3.
4.
The client application authenticates to the Azure AD token issuance endpoint and requests an access token.
The Azure AD token issuance endpoint issues the access token.
The access token is used to authenticate to the secured resource.
Data from the secured resource is returned to the web application.
Register the Services in Azure AD
Register both the calling service and the receiving service in Azure Active Directory (Azure AD). For detailed
instructions, see Integrating applications with Azure Active Directory.
Request an Access Token
To request an access token, use an HTTP POST to the tenant-specific Azure AD endpoint.
https://login.microsoftonline.com/<tenant id>/oauth2/token
Service-to-service access token request
A service-to-service access token request contains the following parameters.
PARAMETER
response_type
DESCRIPTION
required
Specifies the requested response type.
In a Client Credentials Grant flow, the
value must be client_credentials.
PARAMETER
DESCRIPTION
client_id
required
Specifies the Azure AD client id of the
calling web service. To find the calling
application's client ID, in the Azure
Management Portal, click Active
Directory, click the directory, click the
application, and then click Configure.
client_secret
required
Enter a key registered for the calling
web service in Azure AD. To create a
key, in the Azure Management Portal,
click Active Directory, click the
directory, click the application, and then
click Configure.
resource
required
Enter the App ID URI of the receiving
web service. To find the App ID URI, in
the Azure Management Portal, click
Active Directory, click the directory,
click the application, and then click
Configure.
Example
The following HTTP POST requests an access token for the https://service.contoso.com/ web service. The
identifies the web service that requests the access token.
client_id
POST contoso.com/oauth2/token HTTP/1.1
Host: login.microsoftonline.com
Content-Type: application/x-www-form-urlencoded
grant_type=client_credentials&client_id=625bc9f6-3bf6-4b6d-94bae97cf07a22de&client_secret=qkDwDJlDfig2IpeuUZYKH1Wb8q1V0ju6sILxQQqhJ+s=&resource=https%3A%2F%2Fservice.contoso.
com%2F
Service-to-Service Access Token Response
A success response contains a JSON OAuth 2.0 response with the following parameters.
PARAMETER
DESCRIPTION
access_token
The requested access token. The calling web service can use
this token to authenticate to the receiving web service.
access_type
Indicates the token type value. The only type that Azure AD
supports is Bearer. For more information about bearer
tokens, see The OAuth 2.0 Authorization Framework: Bearer
Token Usage (RFC 6750).
expires_in
How long the access token is valid (in seconds).
expires_on
The time when the access token expires. The date is
represented as the number of seconds from 1970-0101T0:0:0Z UTC until the expiration time. This value is used to
determine the lifetime of cached tokens.
PARAMETER
DESCRIPTION
resource
The App ID URI of the receiving web service.
Example
The following example shows a success response to a request for an access token to a web service.
{
"access_token":"eyJhbGciOiJSUzI1NiIsIng1dCI6IjdkRC1nZWNOZ1gxWmY3R0xrT3ZwT0IyZGNWQSIsInR5cCI6IkpXVCJ9.eyJhdWQiOi
JodHRwczovL3NlcnZpY2UuY29udG9zby5jb20vIiwiaXNzIjoiaHR0cHM6Ly9zdHMud2luZG93cy5uZXQvN2ZlODE0NDctZGE1Ny00Mzg1LWJlY
2ItNmRlNTdmMjE0NzdlLyIsImlhdCI6MTM4ODQ0ODI2NywibmJmIjoxMzg4NDQ4MjY3LCJleHAiOjEzODg0NTIxNjcsInZlciI6IjEuMCIsInRp
ZCI6IjdmZTgxNDQ3LWRhNTctNDM4NS1iZWNiLTZkZTU3ZjIxNDc3ZSIsIm9pZCI6ImE5OTE5MTYyLTkyMTctNDlkYS1hZTIyLWYxMTM3YzI1Y2R
lYSIsInN1YiI6ImE5OTE5MTYyLTkyMTctNDlkYS1hZTIyLWYxMTM3YzI1Y2RlYSIsImlkcCI6Imh0dHBzOi8vc3RzLndpbmRvd3MubmV0LzdmZT
gxNDQ3LWRhNTctNDM4NS1iZWNiLTZkZTU3ZjIxNDc3ZS8iLCJhcHBpZCI6ImQxN2QxNWJjLWM1NzYtNDFlNS05MjdmLWRiNWYzMGRkNThmMSIsI
mFwcGlkYWNyIjoiMSJ9.aqtfJ7G37CpKV901Vm9sGiQhde0WMg6luYJR4wuNR2ffaQsVPPpKirM5rbc6o5CmW1OtmaAIdwDcL6i9ZT9ooIIicSR
rjCYMYWHX08ip-tj-uWUihGztI02xKdWiycItpWiHxapQm0a8Ti1CWRjJghORC1B1-fah_yWx6Cjuf4QE8xJcu-ZHX0pVZNPX22PHYV5KmvPTq2HtIqdboKyZy3Y4y3geOrRIFElZYoqjqSv5q9Jgtj5ERsNQIjefpyxW3EwPtFqMcDm4ebiAEpoEWRN4QYOMxnC9OUBeG9oLA0lTfmhgHLAt
vJogJcYFzwngTsVo6HznsvPWy7UP3MINA",
"token_type":"Bearer",
"expires_in":"3599",
"expires_on":"1388452167",
"resource":"https://service.contoso.com/"
}
See also
OAuth 2.0 in Azure AD
Integrating applications with Azure Active
Directory
3/31/2017 • 21 min to read • Edit Online
NOTE
This article is part of the Azure Active Directory developer's guide.
Enterprise developers and software-as-a-service (SaaS) providers can develop commercial cloud
services or line of business applications that can be integrated with Azure Active Directory (Azure AD) to
provide secure sign in and authorization for their services. To integrate an application or service with
Azure AD, a developer must first register the details about their application with Azure AD through the
Azure classic portal.
This article shows you how to add, update, or remove an application in Azure AD. You will learn about
the different types of applications that can be integrated with Azure AD, how to configure your
applications to access other resources such as web APIs, and more.
To learn more about the two Azure AD objects that represent a registered application and the
relationship between them, see Application Objects and Service Principal Objects; to learn more about
the branding guidelines you should use when developing applications with Azure Active Directory, see
Branding Guidelines for Integrated Apps.
Adding an application
Any application that wants to use the capabilities of Azure AD must first be registered in an Azure AD
tenant. This registration process involves giving Azure AD details about your application, such as the URL
where it’s located, the URL to send replies after a user is authenticated, the URI that identifies the app,
and so on.
If you’re building a web application that just needs to support sign-in for users in Azure AD, you can
simply follow the instructions below. If your application needs credentials or permissions to access to a
web API, or needs to allow users from other Azure AD tenants to access it, see Updating an Application
section to continue configuring your application.
To register a new application in the Azure portal
1. Sign in to the Azure portal.
2. Choose your Azure AD tenant by selecting your account in the top right corner of the page.
3. In the left-hand navigation pane, choose More Services, click App Registrations, and click Add.
4. Follow the prompts and create a new application. If you'd like specific examples for web applications
or native applications, check out our quickstarts.
For Web Applications, provide the Sign-On URL, which is the base URL of your app, where
users can sign in e.g http://localhost:12345 .
For Native Applications, provide a Redirect URI, which Azure AD uses to return token
responses. Enter a value specific to your application, .e.g http://MyFirstAADApp
5. Once you've completed registration, Azure AD assigns your application a unique client identifier, the
Application ID. Your application has been added, and you will be taken to the Quick Start page for
your application. Depending on whether your application is a web or native application, you will see
different options on how to add additional capabilities to your application. Once your application has
been added, you can begin updating your application to enable users to sign in, access web APIs in
other applications, or configure multi-tenant application (which allows other organizations to access
your application).
NOTE
By default, the newly created application registration is configured to allow users from your directory to sign in to
your application.
Updating an application
Once your application has been registered with Azure AD, it may need to be updated to provide access
to web APIs, be made available in other organizations, and more. This section describes various ways in
which you may need to configure your application further. First we will start with an overview of the
Consent Framework, which is important to understand if you are building resource/API applications that
will be consumed by client applications built by developers in your organization or another organization.
For more information on the way authentication works in Azure AD, see Authentication Scenarios for
Azure AD.
Overview of the consent framework
Azure AD’s consent framework makes it easy to develop multi-tenant web and native client applications
that need to access web APIs secured by an Azure AD tenant, different from the one where the client
application is registered. These web APIs include the Microsoft Graph API (to access Azure Active
Directory, Intune, and services in Office 365) and other Microsoft services APIs, in addition to your own
web APIs. The framework is based on a user or an administrator giving consent to an application that
asks to be registered in their directory, which may involve accessing directory data.
For example, if a web client application needs to read calendar information about the user from Office
365, that user will be required to consent to the client application. After consent is given, the client
application will be able to call the Microsoft Graph API on behalf of the user, and use the calendar
information as needed. The Microsoft Graph API provides access to data in Office 365 (like calendars and
messages from Exchange, sites and lists from SharePoint, documents from OneDrive, notebooks from
OneNote, tasks from Planner, workbooks from Excel, etc.), as well as users and groups from Azure AD
and other data objects from more Microsoft cloud services.
The consent framework is built on OAuth 2.0 and its various flows, such as authorization code grant and
client credentials grant, using public or confidential clients. By using OAuth 2.0, Azure AD makes it
possible to build many different types of client applications, such as on a phone, tablet, server, or a web
application, and gain access to the required resources.
For more detailed information about the consent framework, see OAuth 2.0 in Azure AD, Authentication
Scenarios for Azure AD, and for infomation about getting authorized access to Office 365 via Microsoft
Graph, see App authentication with Microsoft Graph.
Example of the consent experience
The following steps will show you how the consent experience works for both the application developer
and user.
1. On your web client application’s configuration page in the Azure portal, set the permissions your
application requires by using the menus in the Required Permissions section.
2. Consider that your application’s permissions have been updated, the application is running, and a
user is about to use it for the first time. If the application has not already acquired an access or refresh
token, the application needs to go to Azure AD’s authorization endpoint to obtain an authorization
code that can be used to acquire a new access and refresh token.
3. If the user is not already authenticated, they’ll be asked to sign in to Azure AD.
4. After the user has signed in, Azure AD will determine if the user needs to be shown a consent
page. This determination is based on whether the user (or their organization’s administrator) has
already granted the application consent. If consent has not already been granted, Azure AD will
prompt the user for consent and will display the required permissions it needs to function. The set
of permissions that is displayed in the consent dialog are the same as what was selected in the
Delegated Permissions in the Azure portal.
5. After the user grants consent, an authorization code is returned to your application, which can be
redeemed to acquire an access token and refresh token. For more information about this flow, see
the web Application to web API section section in Authentication Scenarios for Azure AD.
6. As an administrator, you can also consent to an application's delegated permissions on behalf of
all the users in your tenant. This will prevent the consent dialog from appearing for every user in
the tenant. You can do this from the Azure portal from your application page. From the Settings
blade for your application, click Required Permissions and click on the Grant Permissions
button.
NOTE
Granting explicit consent using the Grant Permissions button is currently required for single page applications
(SPA) using ADAL.js, as the access token is requested without a consent prompt, which will fail if consent is not
already granted.
Configuring a client application to access web APIs
In order for a web/confidential client application to be able to participate in an authorization grant flow
that requires authentication (and obtain an access token), it must establish secure credentials. The default
authentication method supported by the Azure portal is Client ID + symmetric key. This section will
cover the configuration steps required to provide the secret key your client's credentials.
Additionally, before a client can access a web API exposed by a resource application (ie: Microsoft Graph
API), the consent framework will ensure the client obtains the permission grant required, based on the
permissions requested. By default, all applications can choose permissions from Azure Active Directory
(Graph API) and Azure Service Management API, with the Azure AD “Enable sign on and read user’s
profile” permission already selected by default. If your client application is being registered in an Office
365 Azure AD tenant, web APIs and permissions for SharePoint and Exchange Online will also be
available for selection. You can select from two types of permissions in the drop-down menus next to the
desired web API:
Application Permissions: Your client application needs to access the web API directly as itself (no user
context). This type of permission requires administrator consent and is also not available for native
client applications.
Delegated 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.
NOTE
Adding a delegated permission to an application does not automatically grant consent to the users within the
tenant, as it did in the Azure Classic Portal. The users must still manually consent for the added delegated
permissions at runtime, unless the administrator clicks the Grant Permissions button from the Required
Permissions section of the application page in the Azure portal.
To add credentials, or permissions to access web APIs
1. Sign in to the Azure portal.
2. Choose your Azure AD tenant by selecting your account in the top right corner of the page.
3. On the top menu, choose Azure Active Directory, click App Registrations, and then click the
application you want to configure. This will take you to the application's QuickStart page, as well as
open up the Settings blade for the application.
4. To add a secret key for your web application's credentials, click the "Keys" section from the
Settings blade.
Add a description for your key and select either a 1 or 2 year duration.
The right-most column will contain the key value, after you save the configuration changes. Be
sure to come back to this section and copy it after you hit save, so you will have it for use in
your client application during authentication at run-time.
5. To add permission(s) to access resource APIs from your client, click the "Required Permissions"
section from the Settings blade.
First, click the "Add" button.
Click "Select an API" to select the type of resources you want to pick from.
Browse through the list of available APIs or use the search box to select from the available
resource applications in your directory that expose a web API. Click the resource you are
interested in, then click Select.
Once selected, you can move to the Select Permissions menu, where you can select the
"Application Permissions" and "Delegated Permissions" for your application.
6. When finished, click the Done button.
NOTE
Clicking the Done button also automatically sets the permissions for your application in your directory based on
the permissions to other applications that you configured. You can view these application permissions by looking
at the application Settings blade.
Configuring a resource application to expose web APIs
You can develop a web API and make it available to client applications by exposing access scopes and
roles. A correctly configured web API is made available just like the other Microsoft web APIs, including
the Graph API and the Office 365 APIs. Access scopes and roles are exposed through your application's
manifest, which is a JSON file that represents your application’s identity configuration.
The following section will show you how to expose access scopes, by modifying the resource
application's manifest.
Adding access scopes to your resource application
1. Sign in to the Azure portal.
2. Choose your Azure AD tenant by selecting your account in the top right corner of the page.
3. On the top menu, choose Azure Active Directory, click App Registrations, and then click the
application you want to configure. This will take you to the application's QuickStart page, as well as
open up the Settings blade for the application.
4. Click Manifest from the application page to open the inline manifest editor.
5. Replace “oauth2Permissions” node with the following JSON snippet. This snippet is an example of
how to expose a scope known as "user impersonation", which allows a resource owner to give a
client application a type of delegated access to a resource. Make sure that you change the text and
values for your own application:
"oauth2Permissions": [
{
"adminConsentDescription": "Allow the application full access to the Todo List service
on behalf of the signed-in
user",
"adminConsentDisplayName": "Have full access to the Todo List service",
"id": "b69ee3c9-c40d-4f2a-ac80-961cd1534e40",
"isEnabled": true,
"type": "User",
"userConsentDescription": "Allow the application full access to the todo service on your
behalf",
"userConsentDisplayName": "Have full access to the todo service",
"value": "user_impersonation"
}
],
The id value must be a new generated GUID that you create by using a GUID generation tool or
programmatically. It represents a unique identifier for the permission that is exposed by the web
API. Once your client is appropriately configured to request access to your web API and calls the
web API, it will present an OAuth 2.0 JWT token that has the scope (scp) claim set to the value
above, which in this case is user_impersonation.
NOTE
You can expose additional scopes later as necessary. Consider that your web API might expose multiple
scopes associated with a variety of different functions. Now you can control access to the web API by
using the scope (scp) claim in the received OAuth 2.0 JWT token.
6. Click Save to save the manifest. Your web API is now configured to be used by other applications in
your directory.
To verify the web API is exposed to other applications in your directory
1. On the top menu, click App Registrations, select the desired client application you want to configure
access to the web API and navigate to the Settings blade.
2. From the Required Permissions section, select the web API that you just exposed a permission for.
From the Delegated Permissions drop-down menu, select the new permission.
More on the application manifest
The application manifest actually serves as a mechanism for updating the Application entity, which
defines all attributes of an Azure AD application's identity configuration, including the API access scopes
we discussed. For more information on the Application entity, please see the Graph API Application
entity documentation. In it, you will find complete reference information on the Application entity
members used to specify permissions for your API:
the appRoles member, which is a collection of AppRole entities that can be used to define the
Application Permissions for a web API
the oauth2Permissions member, which is a collection of OAuth2Permission entities that can be used
to define the Delegated Permissions for a web API
For more information on application manifest concepts in general, please refer to Understanding the
Azure Active Directory application manifest.
Accessing the Azure AD Graph and Office 365 via Microsoft Graph APIs
As mentioned earlier, in addition to exposing/accessing APIs on your own resource applications, you can
also update your client application to access APIs exposed by Microsoft resources. The Microsoft Graph
API, which is called “Microsoft Graph” in the list of Permissions to other applications, is available or all
applications that are registered with Azure AD. If you are registering your client application in an Azure
AD tenant that was provisioned by Office 365, you can also access all of the permissions exposed by the
Microsoft Graph API to various Office 365 resources.
For a complete discussion on access scopes exposed by Microsoft Graph API, please see the Permission
scopes | Microsoft Graph API concepts article.
NOTE
Due to a current limitation, native client applications can only call into the Azure AD Graph API if they use the
“Access your organization's directory” permission. This restriction does not apply for web applications.
Configuring multi-tenant applications
When adding an application to Azure AD, you may want your application to be accessed only by users in
your organization. Alternatively, you may want your application to be accessed by users in external
organizations. These two application types are called single tenant and multi-tenant applications. You
can modify the configuration of a single tenant application to make it a multi-tenant application, which
this section discusses below.
It’s important to note the differences between a single tenant and multi-tenant application:
A single tenant application is intended for use in one organization. They are typically a line-ofbusiness (LoB) application written by an enterprise developer. A single tenant application only needs
to be accessed by users in one directory, and as a result, it only needs to be provisioned in one
directory.
A multi-tenant application intended for use in many organizations. They are a software-as-a-service
(SaaS) web application typically written by an independent software vendor (ISV). Multi-tenant
applications need to be provisioned in each directory where they will be used, which requires user or
administrator consent to register them, supported via the Azure AD consent framework. Note that all
native client applications are multi-tenant by default as they are installed on the resource owner's
device. See the Overview of the Consent Framework section above for more details on the consent
framework.
Enabling external users to grant your application access to their resources
If you are writing an application that you want to make available to your customers or partners outside
of your organization, you will need to update the application definition in the Azure portal.
NOTE
When enabling multi-tenant, you must ensure that your application’s App ID URI belongs in a verified domain.
Additionally, the Return URL must begin with https://. For more information, see Application Objects and Service
Principal Objects.
To enable access to your app for external users:
1. Sign in to the Azure portal.
2. Choose your Azure AD tenant by selecting your account in the top right corner of the page.
3. On the top menu, choose Azure Active Directory, click App Registrations, and then click the
application you want to configure. This will take you to the application's QuickStart page, as well as
open up the Settings blade for the application.
4. From the Settings blade, click Properties and flip the Multi-tenanted switch to Yes.
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.
Triggering the Azure AD consent framework at runtime
To use the consent framework, multi-tenant client applications must request authorization using OAuth
2.0. Code samples are available to show you how a web application, native application, or
server/daemon application requests authorization codes and access tokens to call web APIs.
Your web application may also offer a sign-up experience for users. If you do offer a sign-up experience,
it is expected that the user will click on a sign up button that will redirect the browser to the Azure AD
OAuth2.0 authorize endpoint or an OpenID Connect userinfo endpoint. These endpoints allow the
application to get information about the new user by inspecting the id_token. Following the sign-up
phase the user will be presented with a consent prompt similar to the one shown above in the Overview
of the Consent Framework section.
Alternatively, your web application may also 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. In this case though, you pass a prompt=admin_consent parameter to the authorize endpoint
to force the administrator consent experience, where the administrator will grant consent on behalf of
their organization. Only a user that authenticates with an account that belongs to the Global Admin role
can provide consent; others will receive an error. 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.
Enabling OAuth 2.0 implicit grant for Single Page Applications
Single Page Application’s (SPAs) are typically structured with a JavaScript-heavy front end that runs in
the browser, which calls the application’s web API back end to perform its business logic. For SPAs
hosted in Azure AD, you use OAuth 2.0 Implicit Grant to authenticate the user with Azure AD and obtain
a token that you can use to secure calls from the application's JavaScript client to its back end web API.
After the user has granted consent, this same authentication protocol can be used to obtain tokens to
secure calls between the client and other web API resources configured for the application. To learn
more about the implicit authorization grant, and help you decide whether it's right for your application
scenario, see Understanding the OAuth2 implicit grant flow in Azure Active Directory .
By default, OAuth 2.0 implicit Grant is disabled for applications. You can enable OAuth 2.0 Implicit Grant
for your application by setting the oauth2AllowImplicitFlow value in its application manifest, which is a
JSON file that represents your application's identity configuration.
To enable OAuth 2.0 implicit grant
1. Sign in to the Azure portal.
2. Choose your Azure AD tenant by selecting your account in the top right corner of the page.
3. On the top menu, choose Azure Active Directory, click App Registrations, and then click the
application you want to configure. This will take you to the application's QuickStart page, as well as
open up the Settings blade for the application.
4. From the application page, click Manifest to open the inline manifest editor. Locate and set the
“oauth2AllowImplicitFlow” value to “true”. By default, it is “false”.
"oauth2AllowImplicitFlow": true,
5. Save the updated manifest. Once saved, your web API is now configured to use OAuth 2.0 Implicit
Grant to authenticate users.
Removing an application
This section describes how to remove an application from your Azure AD tenant.
Removing an application authored by your organization
These are the applications that show under the "Applications my company owns" filter on the main
"Applications" page for your Azure AD tenant. In technical terms, these are applications you registered
either manually via the Azure classic portal, or programmatically via PowerShell or the Graph API. More
specifically, they are represented by both an Application and Service Principal object in your tenant. See
Application Objects and Service Principal Objects for more information.
To remove a single tenant application from your directory
1. Sign in to the Azure portal.
2. Choose your Azure AD tenant by selecting your account in the top right corner of the page.
3. On the top menu, choose Azure Active Directory, click App Registrations, and then click the
application you want to configure. This will take you to the application's QuickStart page, as well as
open up the Settings blade for the application.
4. From the application page, click Delete.
5. Click Yes in the confirmation message.
To remove a multi-tenant application from your directory
1. Sign in to the Azure portal.
2. Choose your Azure AD tenant by selecting your account in the top right corner of the page.
3. On the top menu, choose Azure Active Directory, click App Registrations, and then click the
application you want to configure. This will take you to the application's QuickStart page, as well as
open up the Settings blade for the application.
4. From the Settings blade, choose Properties and flip the Multi-tenanted switch to No. This converts
your application to be single tenant, but the application will still remain in an organization who has
already consented to it.
5. Click on the Delete button from the application page.
6. Click Yes in the confirmation message.
Removing a multi-tenant application authorized by another organization
These are a subset of the applications that show under the "Applications my company uses" filter on the
main "Applications" page for your Azure AD tenant, specifically the ones that are not listed under the
"Applications my company owns" list. In technical terms, these are multi-tenant applications registered
during the consent process. More specifically, they are represented by only a Service Principal object in
your tenant. See Application Objects and Service Principal Objects for more information.
In order to remove a multi-tenant application’s access to your directory (after having granted consent),
the company administrator must have an Azure subscription to remove access through the Azure portal.
Alternatively, the company administrator can use the Azure AD PowerShell Cmdlets to remove access.
Next steps
See the Branding Guidelines for Integrated Apps for tips on visual guidance for your app.
For more details on the relationship between an application's Application and Service Principal
object(s), see Application Objects and Service Principal Objects.
To learn more about the role the app manifest plays, see Understanding the Azure Active Directory
application manifest
See the Azure AD developer glossary for definitions of some of the core Azure Active Directory (AD)
developer concepts.
Visit the Active Directory developer's guide for an overview of all developer related content.
How to sign in any Azure Active Directory (AD) user
using the multi-tenant application pattern
4/26/2017 • 14 min to read • Edit Online
If you offer a Software as a Service application to many organizations, you can configure your application to accept
sign-ins from any Azure AD tenant. In Azure AD this is called making your application multi-tenant. Users in any
Azure AD tenant will be able to sign in to your application after consenting to use their account with your
application.
If you have an existing application that has its own account system, or supports other kinds of sign-in from other
cloud providers, adding Azure AD sign-in from any tenant is simple. Just register your app, add sign-in code via
OAuth2, OpenID Connect, or SAML, and put a "Sign In with Microsoft" button on your application. Click the
following button to learn more about branding your application.
This article assumes you’re already familiar with building a single tenant application for Azure AD. If you’re not,
head back up to the developer guide homepage and try one of our quick starts!
There are four simple steps to convert your application into an Azure AD multi-tenant app:
1.
2.
3.
4.
Update your application registration to be multi-tenant
Update your code to send requests to the /common endpoint
Update your code to handle multiple issuer values
Understand user and admin consent and make appropriate code changes
Let’s look at each step in detail. You can also jump straight to this list of multi-tenant samples.
Update registration to be multi-tenant
By default, web app/API registrations in Azure AD are single tenant. You can make your registration multi-tenant
by finding the “Multi-Tenanted” switch on the properties page of your application registration in the Azure portal
and setting it to “Yes”.
Also note, before an application can be made multi-tenant, Azure AD requires the App ID URI of the application to
be globally unique. The App ID URI is one of the ways an application is identified in protocol messages. For a single
tenant application, it is sufficient for the App ID URI to be unique within that tenant. For a multi-tenant application,
it must be globally unique so Azure AD can find the application across all tenants. Global uniqueness is enforced by
requiring the App ID URI to have a host name that matches a verified domain of the Azure AD tenant. For example,
if the name of your tenant was contoso.onmicrosoft.com then a valid App ID URI would be
https://contoso.onmicrosoft.com/myapp . If your tenant had a verified domain of contoso.com , then a valid App ID
URI would also be https://contoso.com/myapp . Setting an application as multi-tenant will fail if the App ID URI
doesn’t follow this pattern.
Native client registrations are multi-tenant by default. You don’t need to take any action to make a native client
application registration multi-tenant.
Update your code to send requests to /common
In a single tenant application, sign-in requests are sent to the tenant’s sign-in endpoint. For example, for
contoso.onmicrosoft.com the endpoint would be:
https://login.microsoftonline.com/contoso.onmicrosoft.com
Requests sent to a tenant’s endpoint can sign in users (or guests) in that tenant to applications in that tenant. With
a multi-tenant application, the application doesn’t know up front what tenant the user is from, so you can’t send
requests to a tenant’s endpoint. Instead, requests are sent to an endpoint that multiplexes across all Azure AD
tenants:
https://login.microsoftonline.com/common
When Azure AD receives a request on the /common endpoint, it signs the user in and as a consequence discovers
which tenant the user is from. The /common endpoint works with all of the authentication protocols supported by
Azure AD: OpenID Connect, OAuth 2.0, SAML 2.0, and WS-Federation.
The sign-in response to the application then contains a token representing the user. The issuer value in the token
tells an application what tenant the user is from. When a response returns from the /common endpoint, the issuer
value in the token will correspond to the user’s tenant. It’s important to note the /common endpoint is not a tenant
and is not an issuer, it’s just a multiplexer. When using /common, the logic in your application to validate tokens
needs to be updated to take this into account.
As mentioned earlier, multi-tenant applications should also provide a consistent sign-in experience for users,
following the Azure AD application branding guidelines. Click the following button to learn more about branding
your application.
Let’s take a look at the use of the /common endpoint and your code implementation in more detail.
Update your code to handle multiple issuer values
Web applications and web APIs receive and validate tokens from Azure AD.
NOTE
While native client applications request and receive tokens from Azure AD, they do so to send them to APIs, where they are
validated. Native applications do not validate tokens and must treat them as opaque.
Let’s look at how an application validates tokens it receives from Azure AD. A single tenant application will
normally take an endpoint value like:
https://login.microsoftonline.com/contoso.onmicrosoft.com
and use it to construct a metadata URL (in this case, OpenID Connect) like:
https://login.microsoftonline.com/contoso.onmicrosoft.com/.well-known/openid-configuration
to download two critical pieces of information that are used to validate tokens: the tenant’s signing keys and issuer
value. Each Azure AD tenant has a unique issuer value of the form:
https://sts.windows.net/31537af4-6d77-4bb9-a681-d2394888ea26/
where the GUID value is the rename-safe version of the tenant ID of the tenant. If you click on the preceding
metadata link for contoso.onmicrosoft.com , you can see this issuer value in the document.
When a single tenant application validates a token, it checks the signature of the token against the signing keys
from the metadata document. This allows it to make sure the issuer value in the token matches the one that was
found in the metadata document.
Since the /common endpoint doesn’t correspond to a tenant and isn’t an issuer, when you examine the issuer
value in the metadata for /common it has a templated URL instead of an actual value:
https://sts.windows.net/{tenantid}/
Therefore, a multi-tenant application can’t validate tokens just by matching the issuer value in the metadata with
the issuer value in the token. A multi-tenant application needs logic to decide which issuer values are valid and
which are not, based on the tenant ID portion of the issuer value.
For example, if a multi-tenant application only allows sign-in from specific tenants who have signed up for their
service, then it must check either the issuer value or the tid claim value in the token to make sure that tenant is in
their list of subscribers. If a multi-tenant application only deals with individuals and doesn’t make any access
decisions based on tenants, then it can ignore the issuer value altogether.
In the multi-tenant samples in the Related Content section at the end of this article, issuer validation is disabled to
enable any Azure AD tenant to sign in.
Now let’s look at the user experience for users that are signing in to multi-tenant applications.
Understanding user and admin consent
For a user to sign in to an application in Azure AD, the application must be represented in the user’s tenant. This
allows the organization to do things like apply unique policies when users from their tenant sign in to the
application. For a single tenant application, this registration is simple; it’s the one that happens when you register
the application in the Azure portal.
For a multi-tenant application, the initial registration for the application lives in the Azure AD tenant used by the
developer. When a user from a different tenant signs in to the application for the first time, Azure AD asks them to
consent to the permissions requested by the application. If they consent, then a representation of the application
called a service principal is created in the user’s tenant, and sign-in can continue. A delegation is also created in the
directory that records the user’s consent to the application. See Application Objects and Service Principal Objects
for details on the application's Application and ServicePrincipal objects, and how they relate to each other.
This consent experience is affected by the permissions requested by the application. Azure AD supports two kinds
of permissions, app-only and delegated:
A delegated permission grants an application the ability to act as a signed in user for a subset of the things the
user can do. For example, you can grant an application the delegated permission to read the signed in user’s
calendar.
An app-only permission is granted directly to the identity of the application. For example, you can grant an
application the app-only permission to read the list of users in a tenant, regardless of who is signed in to the
application.
Some permissions can be consented to by a regular user, while others require a tenant administrator’s consent.
Admin consent
App-only permissions always require a tenant administrator’s consent. If your application requests an app-only
permission and a user tries to sign in to the application, an error message will be displayed saying the user isn’t
able to consent.
Certain delegated permissions also require a tenant administrator’s consent. For example, the ability to write back
to Azure AD as the signed in user requires a tenant administrator’s consent. Like app-only permissions, if an
ordinary user tries to sign in to an application that requests a delegated permission that requires administrator
consent, your application will receive an error. Whether or not a permission requires admin consent is determined
by the developer that published the resource, and can be found in the documentation for the resource. Links to
topics describing the available permissions for the Azure AD Graph API and Microsoft Graph API are in the Related
Content section of this article.
If your application uses permissions that require admin consent, you need to have a gesture such as a button or
link where the admin can initiate the action. The request your application sends for this action is a usual
OAuth2/OpenID Connect authorization request, but that also includes the prompt=admin_consent query string
parameter. Once the admin has consented and the service principal is created in the customer’s tenant, subsequent
sign-in requests do not need the prompt=admin_consent parameter. Since the administrator has decided the
requested permissions are acceptable, no other users in the tenant will be prompted for consent from that point
forward.
The prompt=admin_consent parameter can also be used by applications that request permissions that do not require
admin consent. This is done when the applicaton requires an experience where the tenant admin “signs up” one
time, and no other users are prompted for consent from that point on.
If an application requires admin consent, and an admin signs in but the prompt=admin_consent parameter is not
sent, the admin will successfully consent to the application only for their user account. Regular users will still not
be able to sign in and consent to the application. This is useful if you want to give the tenant administrator the
ability to explore your application before allowing other users access.
A tenant administrator can disable the ability for regular users to consent to applications. If this capability is
disabled, admin consent is always required for the application to be set up in the tenant. If you want to test your
application with regular user consent disabled, you can find the configuration switch in the Azure AD tenant
configuration section of the Azure portal.
NOTE
Some applications want an experience where regular users are able to consent initially, and later the application can involve
the administrator and request permissions that require admin consent. There is no way to do this with a single application
registration in Azure AD today. The upcoming Azure AD v2 endpoint will allow applications to request permissions at
runtime, instead of at registration time, which will enable this scenario. For more information, see the Azure AD App Model
v2 Developer Guide.
Consent and multi-tier applications
Your application may have multiple tiers, each represented by its own registration in Azure AD. For example, a
native application that calls a web API, or a web application that calls a web API. In both of these cases, the client
(native app or web app) requests permissions to call the resource (web API). For the client to be successfully
consented into a customer’s tenant, all resources to which it requests permissions must already exist in the
customer’s tenant. If this condition isn’t met, Azure AD will return an error that the resource must be added first.
Multiple tiers in a single tenant
This can be a problem if your logical application consists of two or more application registrations, for example a
separate client and resource. How do you get the resource into the customer tenant first? Azure AD covers this
case by enabling client and resource to be consented in a single step. The user sees the sum total of the
permissions requested by both the client and resource on the consent page. To enable this behavior, the resource’s
application registration must include the client’s App ID as a knownClientApplications in its application manifest.
For example:
knownClientApplications": ["94da0930-763f-45c7-8d26-04d5938baab2"]
This property can be updated via the resource application’s manifest. This is demonstrated in a multi-tier native
client calling web API sample in the Related Content section at the end of this article. The following diagram
provides an overview of consent for a multi-tier app registered in a single tenant :
Multiple tiers in multiple tenants
A similar case happens if the different tiers of an application are registered in different tenants. For example,
consider the case of building a native client application that calls the Office 365 Exchange Online API. To develop
the native application, and later for the native application to run in a customer’s tenant, the Exchange Online
service principal must be present. In this case, the developer and customer must purchase Exchange Online for the
service principal to be created in their tenants.
In the case of an API built by an organization other than Microsoft, the developer of the API needs to provide a way
for their customers to consent the application into their customers' tenants. The recommended design is for the
3rd party developer to build the API such that it can also function as a web client to implement sign-up :
1. Follow the earlier sections to ensure the API implements the multi-tenant application registration/code
requirements
2. In addition to exposing the API's scopes/roles, ensure the registration includes the "Sign in and read user
profile" Azure AD permission (provided by default)
3. Implement a sign-in/sign-up page in the web client, following the admin consent guidance discussed earlier
4. Once the user consents to the application, the service principal and consent delegation links are created in their
tenant, and the native application can get tokens for the API
The following diagram provides an overview of consent for a multi-tier app registered in different tenants:
Revoking Consent
Users and administrators can revoke consent to your application at any time:
Users revoke access to individual applications by removing them from their Access Panel Applications list.
Administrators revoke access to applications by removing them from Azure AD using the Azure AD
management section of the Azure portal.
If an administrator consents to an application for all users in a tenant, users cannot revoke access individually. Only
the administrator can revoke access, and only for the whole application.
Consent and Protocol Support
Consent is supported in Azure AD via the OAuth, OpenID Connect, WS-Federation, and SAML protocols. The SAML
and WS-Federation protocols do not support the prompt=admin_consent parameter, so admin consent is only
possible via OAuth and OpenID Connect.
Multi-Tenant Applications and Caching Access Tokens
Multi-tenant applications can also get access tokens to call APIs that are protected by Azure AD. A common error
when using the Active Directory Authentication Library (ADAL) with a multi-tenant application, is to initially request
a token for a user using /common, receive a response, then request a subsequent token for that same user also
using /common. Since the response from Azure AD comes from a tenant, not /common, ADAL caches the token as
being from the tenant. The subsequent call to /common to get an access token for the user misses the cache entry,
and the user is prompted to sign in again. To avoid missing the cache, make sure subsequent calls for an already
signed in user are made to the tenant’s endpoint.
Next steps
In this article, you learned how to build an application that can sign in a user from any Azure Active Directory
tenant. After enabling Single Sign-On between your app and Azure Active Directory, you can also update your
application to access APIs exposed by Microsoft resources, like Office 365. So you can offer a personalized
experience in your application, for example showing contextual information to the users, like their profile picture or
their next calendar appointment. To learn more about making API calls to Azure Active Directory and Office 365
services like Exchange, SharePoint, OneDrive, OneNote, Planner, Excel and more, visit: Microsoft Graph API.
Related content
Multi-tenant application samples
Branding Guidelines for Applications
Azure AD Developer's Guide
Application Objects and Service Principal Objects
Integrating Applications with Azure Active Directory
Overview of the Consent Framework
Microsoft Graph API Permission Scopes
Azure AD Graph API Permission Scopes
Please use the following comments section to provide feedback and help us refine and shape our content.
Authorize access to web applications using OpenID
Connect and Azure Active Directory
2/23/2017 • 11 min to read • Edit Online
OpenID Connect is a simple identity layer built on top of the OAuth 2.0 protocol. OAuth 2.0 defines mechanisms to
obtain and use access tokens to access protected resources, but they do not define standard methods to provide
identity information. OpenID Connect implements authentication as an extension to the OAuth 2.0 authorization
process. It provides information about the end user in the form of an id_token that verifies the identity of the user
and provides basic profile information about the user.
OpenID Connect is our recommendation if you are building a web application that is hosted on a server and
accessed via a browser.
Register your application with your AD tenant
First, you will need to register your application with your Azure Active Directory (Azure AD) tenant. This will give
you an Application ID for your application, as well as enable it to receive tokens.
Sign in to the Azure Portal.
Choose your Azure AD tenant by clicking on your account in the top right corner of the page.
In the left hand navigation pane, click on Azure Active Directory.
Click on App Registrations and click on Add.
Follow the prompts and create a new application. It doesn't matter if it is a web application or a native
application for this tutorial, but if you'd like specific examples for web applications or native applications, check
out our quickstarts.
For Web Applications, provide the Sign-On URL which is the base URL of your app, where users can sign
in e.g http://localhost:12345 .
For Native Applications, provide a Redirect URI, which Azure AD will use to return token responses. Enter
a value specific to your application, .e.g http://MyFirstAADApp
Once you've completed registration, Azure AD will assign your application a unique client identifier, the
Application ID. You will need this value in the next sections, so copy it from the application page.
Authentication flow using OpenID Connect
The most basic sign-in flow contains the following steps - each of them is described in detail below.
OpenID Connect metadata document
OpenID Connect describes a metadata document that contains most of the information required for an app to
perform sign-in. This includes information such as the URLs to use and the location of the service's public signing
keys. The OpenID Connect metadata document can be found at:
https://login.microsoftonline.com/{tenant}/.well-known/openid-configuration
The metadata is a simple JavaScript Object Notation (JSON) document. See the following snippet for an example.
The snippet's contents are fully described in the OpenID Connect specification.
{
"authorization_endpoint": "https://login.microsoftonline.com/common/oauth2/authorize",
"token_endpoint": "https://login.microsoftonline.com/common/oauth2/token",
"token_endpoint_auth_methods_supported":
[
"client_secret_post",
"private_key_jwt"
],
"jwks_uri": "https://login.microsoftonline.com/common/discovery/keys"
...
}
Send the sign-in request
When your web application needs to authenticate the user, it must direct the user to the /authorize endpoint. This
request is similar to the first leg of the OAuth 2.0 Authorization Code Flow, with a few important distinctions:
The request must include the scope openid in the scope parameter.
The response_type parameter must include id_token .
The request must include the nonce parameter.
So a sample request would look like this:
// Line breaks for legibility only
GET https://login.microsoftonline.com/{tenant}/oauth2/authorize?
client_id=6731de76-14a6-49ae-97bc-6eba6914391e
&response_type=id_token
&redirect_uri=http%3A%2F%2Flocalhost%2Fmyapp%2F
&response_mode=form_post
&scope=openid
&state=12345
&nonce=7362CAEA-9CA5-4B43-9BA3-34D7C303EBA7
PARAMETER
DESCRIPTION
tenant
required
The {tenant} value in the path of the
request can be used to control who can
sign into the application. The allowed
values are tenant identifiers, for
example,
8eaef023-2b34-4da1-9baa-8bc8c9d6a490 or
contoso.onmicrosoft.com or common for
tenant-independent tokens
client_id
required
The Application Id assigned to your app
when you registered it with Azure AD.
You can find this in the Azure Portal.
Click Azure Active Directory, click
App Registrations, choose the
application and locate the Application Id
on the application page.
response_type
required
Must include id_token for OpenID
Connect sign-in. It may also include
other response_types, such as code .
PARAMETER
DESCRIPTION
scope
required
A space-separated list of scopes. For
OpenID Connect, it must include the
scope openid , which translates to the
"Sign you in" permission in the consent
UI. You may also include other scopes in
this request for requesting consent.
nonce
required
A value included in the request,
generated by the app, that is included in
the resulting id_token as a claim. The
app can then verify this value to
mitigate token replay attacks. The value
is typically a randomized, unique string
or GUID that can be used to identify the
origin of the request.
redirect_uri
recommended
The redirect_uri of your app, where
authentication responses can be sent
and received by your app. It must
exactly match one of the redirect_uris
you registered in the portal, except it
must be url encoded.
response_mode
recommended
Specifies the method that should be
used to send the resulting
authorization_code back to your app.
Supported values are form_post for
HTTP form post or fragment for URL
fragment. For web applications, we
recommend using
response_mode=form_post to ensure the
most secure transfer of tokens to your
application.
state
recommended
A value included in the request that is
returned in the token response. It can
be a string of any content that you
wish. A randomly generated unique
value is typically used for preventing
cross-site request forgery attacks. The
state is also used to encode information
about the user's state in the app before
the authentication request occurred,
such as the page or view they were on.
PARAMETER
DESCRIPTION
prompt
optional
Indicates the type of user interaction
that is required. Currently, the only valid
values are 'login', 'none', and 'consent'.
prompt=login forces the user to enter
their credentials on that request,
negating single-sign on. prompt=none is
the opposite - it ensures that the user is
not presented with any interactive
prompt whatsoever. If the request
cannot be completed silently via singlesign on, the endpoint returns an error.
prompt=consent triggers the OAuth
consent dialog after the user signs in,
asking the user to grant permissions to
the app.
login_hint
optional
Can be used to pre-fill the
username/email address field of the
sign-in page for the user, if you know
their username ahead of time. Often
apps use this parameter during
reauthentication, having already
extracted the username from a previous
sign-in using the preferred_username
claim.
At this point, the user is asked to enter their credentials and complete the authentication.
Sample response
A sample response, after the user has authenticated, could look like this:
POST /myapp/ HTTP/1.1
Host: localhost
Content-Type: application/x-www-form-urlencoded
id_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik1uQ19WWmNB...&state=12345
PARAMETER
DESCRIPTION
id_token
The
id_token that the app requested. You can use the
id_token to verify the user's identity and begin a session with
the user.
state
Error response
Error responses may also be sent to the
A value included in the request that is also returned in the
token response. A randomly generated unique value is
typically used for preventing cross-site request forgery attacks.
The state is also used to encode information about the user's
state in the app before the authentication request occurred,
such as the page or view they were on.
redirect_uri
so the app can handle them appropriately:
POST /myapp/ HTTP/1.1
Host: localhost
Content-Type: application/x-www-form-urlencoded
error=access_denied&error_description=the+user+canceled+the+authentication
PARAMETER
DESCRIPTION
error
An error code string that can be used to classify types of
errors that occur, and can be used to react to errors.
error_description
A specific error message that can help a developer identify the
root cause of an authentication error.
Error codes for authorization endpoint errors
The following table describes the various error codes that can be returned in the
response.
error
parameter of the error
ERROR CODE
DESCRIPTION
CLIENT ACTION
invalid_request
Protocol error, such as a missing
required parameter.
Fix and resubmit the request. This is a
development error, and is typically
caught during initial testing.
unauthorized_client
The client application is not permitted to
request an authorization code.
This usually occurs when the client
application is not registered in Azure AD
or is not added to the user's Azure AD
tenant. The application can prompt the
user with instruction for installing the
application and adding it to Azure AD.
access_denied
Resource owner denied consent
The client application can notify the user
that it cannot proceed unless the user
consents.
unsupported_response_type
The authorization server does not
support the response type in the
request.
Fix and resubmit the request. This is a
development error, and is typically
caught during initial testing.
server_error
The server encountered an unexpected
error.
Retry the request. These errors can
result from temporary conditions. The
client application might explain to the
user that its response is delayed due to
a temporary error.
temporarily_unavailable
The server is temporarily too busy to
handle the request.
Retry the request. The client application
might explain to the user that its
response is delayed due to a temporary
condition.
invalid_resource
The target resource is invalid because it
does not exist, Azure AD cannot find it,
or it is not correctly configured.
This indicates the resource, if it exists,
has not been configured in the tenant.
The application can prompt the user
with instruction for installing the
application and adding it to Azure AD.
Validate the id_token
Just receiving an id_token is not sufficient to authenticate the user; you must validate the signature and verify the
claims in the id_token per your app's requirements. The Azure AD endpoint uses JSON Web Tokens (JWTs) and
public key cryptography to sign tokens and verify that they are valid.
You can choose to validate the id_token in client code, but a common practice is to send the id_token to a
backend server and perform the validation there. Once you've validated the signature of the id_token , there are a
few claims you are required to verify.
You may also wish to validate additional claims depending on your scenario. Some common validations include:
Ensuring the user/organization has signed up for the app.
Ensuring the user has proper authorization/privileges
Ensuring a certain strength of authentication has occurred, such as multi-factor authentication.
Once you have validated the id_token , you can begin a session with the user and use the claims in the id_token to
obtain information about the user in your app. This information can be used for display, records, authorizations, etc.
For more information about the token types and claims, read Supported Token and Claim Types.
Send a sign-out request
When you wish to sign the user out of the app, it is not sufficient to clear your app's cookies or otherwise end the
session with the user. You must also redirect the user to the end_session_endpoint for sign-out. If you fail to do so,
the user will be able to reauthenticate to your app without entering their credentials again, because they will have a
valid single sign-on session with the Azure AD endpoint.
You can simply redirect the user to the
end_session_endpoint
listed in the OpenID Connect metadata document:
GET https://login.microsoftonline.com/common/oauth2/logout?
post_logout_redirect_uri=http%3A%2F%2Flocalhost%2Fmyapp%2F
PARAMETER
post_logout_redirect_uri
DESCRIPTION
recommended
The URL that the user should be
redirected to after successful logout. If
not included, the user is shown a
generic message.
Single sign-out
When you redirect the user to the end_session_endpoint , Azure AD clears the user's session from the browser.
However, the user may still be signed in to other applications that use Azure AD for authentication. To enable those
applications to sign the user out simultaneously, Azure AD sends an HTTP GET request to the registered LogoutUrl
of all the applications that the user is currently signed in to. Applications must respond to this request by clearing
any session that identifies the user and returning a 200 response. If you wish to support single sign out in your
application, you must implement such a LogoutUrl in your application's code. You can set the LogoutUrl from the
Azure portal:
1. Navigate to the Azure Portal.
2. Choose your Active Directory by clicking on your account in the top right corner of the page.
3. From the left hand navigation panel, choose Azure Active Directory, then choose App registrations and select
your application.
4. Click on Properties and find the Logout URL text box.
Token Acquisition
Many web apps need to not only sign the user in, but also access a web service on behalf of that user using OAuth.
This scenario combines OpenID Connect for user authentication while simultaneously acquiring an
authorization_code that can be used to get access_tokens using the OAuth Authorization Code Flow.
Get Access Tokens
To acquire access tokens, you need to modify the sign-in request from above:
// Line breaks for legibility only
GET https://login.microsoftonline.com/{tenant}/oauth2/authorize?
client_id=6731de76-14a6-49ae-97bc-6eba6914391e
// Your registered Application Id
&response_type=id_token+code
&redirect_uri=http%3A%2F%2Flocalhost%2Fmyapp%2F
// Your registered Redirect Uri, url encoded
&response_mode=form_post
// form_post', or 'fragment'
&scope=openid
&resource=https%3A%2F%2Fservice.contoso.com%2F
&state=12345
// Any value, provided by your app
&nonce=678910
// Any value, provided by your app
By including permission scopes in the request and using response_type=code+id_token , the authorize endpoint
ensures that the user has consented to the permissions indicated in the scope query parameter, and return your
app an authorization code to exchange for an access token.
Successful Response
A successful response using
response_mode=form_post
looks like:
POST /myapp/ HTTP/1.1
Host: localhost
Content-Type: application/x-www-form-urlencoded
id_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik1uQ19WWmNB...&code=AwABAAAAvPM1KaPlrEqdFSBzjqfTGBCmLdgfS
TLEMPGYuNHSUYBrq...&state=12345
PARAMETER
DESCRIPTION
id_token
The
id_token that the app requested. You can use the
id_token to verify the user's identity and begin a session with
the user.
code
The authorization_code that the app requested. The app can
use the authorization code to request an access token for the
target resource. Authorization_codes are short lived, and
typically expire after about 10 minutes.
state
If a state parameter is included in the request, the same value
should appear in the response. The app should verify that the
state values in the request and response are identical.
Error response
Error responses may also be sent to the
redirect_uri
so the app can handle them appropriately:
POST /myapp/ HTTP/1.1
Host: localhost
Content-Type: application/x-www-form-urlencoded
error=access_denied&error_description=the+user+canceled+the+authentication
PARAMETER
DESCRIPTION
error
An error code string that can be used to classify types of
errors that occur, and can be used to react to errors.
error_description
A specific error message that can help a developer identify the
root cause of an authentication error.
For a description of the possible error codes and their recommended client action, see Error codes for authorization
endpoint errors.
Once you've gotten an authorization code and an id_token , you can sign the user in and get access tokens on
their behalf. To sign the user in, you must validate the id_token exactly as described above. To get access tokens,
you can follow the steps described in the "Use the authorization code to request an access token" section of our
OAuth protocol documentation.
Authorize access to web applications using OAuth 2.0
and Azure Active Directory
2/13/2017 • 20 min to read • Edit Online
Azure Active Directory (Azure AD) uses OAuth 2.0 to enable you to authorize access to web applications and web
APIs in your Azure AD tenant. This guide is language independent, and describes how to send and receive HTTP
messages without using any of our open-source libraries.
The OAuth 2.0 authorization code flow is described in section 4.1 of the OAuth 2.0 specification. It is used to
perform authentication and authorization in most application types, including web apps and natively installed apps.
Register your application with your AD tenant
First, you will need to register your application with your Azure Active Directory (Azure AD) tenant. This will give
you an Application ID for your application, as well as enable it to receive tokens.
Sign in to the Azure Portal.
Choose your Azure AD tenant by clicking on your account in the top right corner of the page.
In the left hand navigation pane, click on Azure Active Directory.
Click on App Registrations and click on Add.
Follow the prompts and create a new application. It doesn't matter if it is a web application or a native
application for this tutorial, but if you'd like specific examples for web applications or native applications, check
out our quickstarts.
For Web Applications, provide the Sign-On URL which is the base URL of your app, where users can sign
in e.g http://localhost:12345 .
For Native Applications, provide a Redirect URI, which Azure AD will use to return token responses. Enter
a value specific to your application, .e.g http://MyFirstAADApp
Once you've completed registration, Azure AD will assign your application a unique client identifier, the
Application ID. You will need this value in the next sections, so copy it from the application page.
OAuth 2.0 authorization flow
At a high level, the entire authorization flow for an application looks a bit like this:
Request an authorization code
The authorization code flow begins with the client directing the user to the /authorize endpoint. In this request, the
client indicates the permissions it needs to acquire from the user. You can get the OAuth 2.0 endpoints from your
application's page in Azure Classic Portal, in the View Endpoints button in the bottom drawer.
// Line breaks for legibility only
https://login.microsoftonline.com/{tenant}/oauth2/authorize?
client_id=6731de76-14a6-49ae-97bc-6eba6914391e
&response_type=code
&redirect_uri=http%3A%2F%2Flocalhost%2Fmyapp%2F
&response_mode=query
&resource=https%3A%2F%2Fservice.contoso.com%2F
&state=12345
PARAMETER
DESCRIPTION
PARAMETER
DESCRIPTION
tenant
required
The {tenant} value in the path of the
request can be used to control who can
sign into the application. The allowed
values are tenant identifiers, for
example,
8eaef023-2b34-4da1-9baa-8bc8c9d6a490 or
contoso.onmicrosoft.com or common for
tenant-independent tokens
client_id
required
The Application Id assigned to your app
when you registered it with Azure AD.
You can find this in the Azure Portal.
Click Active Directory, click the
directory, choose the application, and
click Configure
response_type
required
Must include
code flow.
redirect_uri
recommended
The redirect_uri of your app, where
authentication responses can be sent
and received by your app. It must
exactly match one of the redirect_uris
you registered in the portal, except it
must be url encoded. For native &
mobile apps, you should use the default
value of urn:ietf:wg:oauth:2.0:oob .
response_mode
recommended
Specifies the method that should be
used to send the resulting token back
to your app. Can be query or
form_post .
state
recommended
A value included in the request that is
also returned in the token response. A
randomly generated unique value is
typically used for preventing cross-site
request forgery attacks. The state is also
used to encode information about the
user's state in the app before the
authentication request occurred, such as
the page or view they were on.
resource
optional
The App ID URI of the web API (secured
resource). To find the App ID URI of the
web API, in the Azure Portal, click
Active Directory, click the directory,
click the application and then click
Configure.
code
for the authorization
PARAMETER
prompt
DESCRIPTION
optional
Indicate the type of user interaction that
is required.
Valid values are:
login: The user should be prompted
to reauthenticate.
consent: User consent has been
granted, but needs to be updated.
The user should be prompted to
consent.
admin_consent: An administrator
should be prompted to consent on
behalf of all users in their
organization
login_hint
optional
Can be used to pre-fill the
username/email address field of the
sign-in page for the user, if you know
their username ahead of time. Often
apps use this parameter during
reauthentication, having already
extracted the username from a previous
sign-in using the preferred_username
claim.
domain_hint
optional
Provides a hint about the tenant or
domain that the user should use to sign
in. The value of the domain_hint is a
registered domain for the tenant. If the
tenant is federated to an on-premises
directory, AAD redirects to the specified
tenant federation server.
NOTE
If the user is part of an organization, an administrator of the organization can consent or decline on the user's behalf, or
permit the user to consent. The user is given the option to consent only when the administrator permits it.
At this point, the user is asked to enter their credentials and consent to the permissions indicated in the scope
query parameter. Once the user authenticates and grants consent, Azure AD sends a response to your app at the
redirect_uri address in your request.
Successful response
A successful response could look like this:
GET HTTP/1.1 302 Found
Location: http://localhost/myapp/?code=
AwABAAAAvPM1KaPlrEqdFSBzjqfTGBCmLdgfSTLEMPGYuNHSUYBrqqf_ZT_p5uEAEJJ_nZ3UmphWygRNy2C3jJ239gV_DBnZ2syeg95Ki374WHUP-i3yIhv5i-7KU2CEoPXwURQp6IVYMwDjAOzn7C3JCu5wpngXmbZKtJdWmiBzHpcO2aICJPu1KvJrDLDP20chJBXzVYJtkfjviLNNW7l7Y3ydcHDsBRKZc3GuMQanmcghXPyoDg41g8Xbw
PudVh7uCmUponBQpIhbuffFP_tbV8SNzsPoFz9CLpBCZagJVXeqWoYMPe2dSsPiLO9Alf_YIe5zpizY4C3aLw5g9at35eZTfNd0gBRpR5ojkMIcZZ6IgAA&session_state=7B29111D-C220-4263-99AB-6F6E135D75EF&state=D79E5777702E-4260-9A62-37F75FF22CCE
PARAMETER
DESCRIPTION
admin_consent
The value is True if an administrator consented to a consent
request prompt.
code
The authorization code that the application requested. The
application can use the authorization code to request an
access token for the target resource.
session_state
A unique value that identifies the current user session. This
value is a GUID, but should be treated as an opaque value
that is passed without examination.
state
If a state parameter is included in the request, the same value
should appear in the response. It's a good practice for the
application to verify that the state values in the request and
response are identical before using the response. This helps to
detect Cross-Site Request Forgery (CSRF) attacks against the
client.
Error response
Error responses may also be sent to the
redirect_uri
so that the application can handle them appropriately.
GET http://localhost:12345/?
error=access_denied
&error_description=the+user+canceled+the+authentication
PARAMETER
DESCRIPTION
error
An error code value defined in Section 5.2 of the OAuth 2.0
Authorization Framework. The next table describes the error
codes that Azure AD returns.
error_description
A more detailed description of the error. This message is not
intended to be end-user friendly.
state
The state value is a randomly generated non-reused value that
is sent in the request and returned in the response to prevent
cross-site request forgery (CSRF) attacks.
Error codes for authorization endpoint errors
The following table describes the various error codes that can be returned in the
response.
error
parameter of the error
ERROR CODE
DESCRIPTION
CLIENT ACTION
invalid_request
Protocol error, such as a missing
required parameter.
Fix and resubmit the request. This is a
development error, and is typically
caught during initial testing.
unauthorized_client
The client application is not permitted to
request an authorization code.
This usually occurs when the client
application is not registered in Azure AD
or is not added to the user's Azure AD
tenant. The application can prompt the
user with instruction for installing the
application and adding it to Azure AD.
ERROR CODE
DESCRIPTION
CLIENT ACTION
access_denied
Resource owner denied consent
The client application can notify the user
that it cannot proceed unless the user
consents.
unsupported_response_type
The authorization server does not
support the response type in the
request.
Fix and resubmit the request. This is a
development error, and is typically
caught during initial testing.
server_error
The server encountered an unexpected
error.
Retry the request. These errors can
result from temporary conditions. The
client application might explain to the
user that its response is delayed due to
a temporary error.
temporarily_unavailable
The server is temporarily too busy to
handle the request.
Retry the request. The client application
might explain to the user that its
response is delayed due to a temporary
condition.
invalid_resource
The target resource is invalid because it
does not exist, Azure AD cannot find it,
or it is not correctly configured.
This indicates the resource, if it exists,
has not been configured in the tenant.
The application can prompt the user
with instruction for installing the
application and adding it to Azure AD.
Use the authorization code to request an access token
Now that you've acquired an authorization code and have been granted permission by the user, you can redeem
the code for an access token to the desired resource, by sending a POST request to the /token endpoint:
// Line breaks for legibility only
POST /{tenant}/oauth2/token HTTP/1.1
Host: https://login.microsoftonline.com
Content-Type: application/x-www-form-urlencoded
grant_type=authorization_code
&client_id=2d4d11a2-f814-46a7-890a-274a72a7309e
&code=AwABAAAAvPM1KaPlrEqdFSBzjqfTGBCmLdgfSTLEMPGYuNHSUYBrqqf_ZT_p5uEAEJJ_nZ3UmphWygRNy2C3jJ239gV_DBnZ2syeg95Ki
-374WHUP-i3yIhv5i-7KU2CEoPXwURQp6IVYMwDjAOzn7C3JCu5wpngXmbZKtJdWmiBzHpcO2aICJPu1KvJrDLDP20chJBXzVYJtkfjviLNNW7l7Y3ydcHDsBRKZc3GuMQanmcghXPyoDg41g8Xbw
PudVh7uCmUponBQpIhbuffFP_tbV8SNzsPoFz9CLpBCZagJVXeqWoYMPe2dSsPiLO9Alf_YIe5zpizY4C3aLw5g9at35eZTfNd0gBRpR5ojkMIcZZ6IgAA
&redirect_uri=https%3A%2F%2Flocalhost%2Fmyapp%2F
&resource=https%3A%2F%2Fservice.contoso.com%2F
&client_secret=p@ssw0rd
//NOTE: client_secret only required for web apps
PARAMETER
DESCRIPTION
PARAMETER
DESCRIPTION
tenant
required
The {tenant} value in the path of the
request can be used to control who can
sign into the application. The allowed
values are tenant identifiers, for
example,
8eaef023-2b34-4da1-9baa-8bc8c9d6a490 or
contoso.onmicrosoft.com or common for
tenant-independent tokens
client_id
required
The Application Id assigned to your app
when you registered it with Azure AD.
You can find this in the Azure Classic
Portal. Click Active Directory, click the
directory, choose the application, and
click Configure
grant_type
required
Must be authorization_code for the
authorization code flow.
code
required
The authorization_code that you acquired
in the previous section
redirect_uri
required
The same redirect_uri value that was
used to acquire the authorization_code .
client_secret
required for web apps
The application secret that you created
in the app registration portal for your
app. It should not be used in a native
app, because client_secrets cannot be
reliably stored on devices. It is required
for web apps and web APIs, which have
the ability to store the client_secret
securely on the server side.
resource
required if specified in authorization
code request, else optional
The App ID URI of the web API (secured
resource).
To find the App ID URI, in the Azure Management Portal, click Active Directory, click the directory, click the
application, and then click Configure.
Successful response
Azure AD returns an access token upon a successful response. To minimize network calls from the client application
and their associated latency, the client application should cache access tokens for the token lifetime that is specified
in the OAuth 2.0 response. To determine the token lifetime, use either the expires_in or expires_on parameter
values.
If a web API resource returns an invalid_token error code, this might indicate that the resource has determined
that the token is expired. If the client and resource clock times are different (known as a "time skew"), the resource
might consider the token to be expired before the token is cleared from the client cache. If this occurs, clear the
token from the cache, even if it is still within its calculated lifetime.
A successful response could look like this:
{
"access_token": "
eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik5HVEZ2ZEstZnl0aEV1THdqcHdBSk9NOW4tQSJ9.eyJhdWQiOiJodHRwczovL3Nlcn
ZpY2UuY29udG9zby5jb20vIiwiaXNzIjoiaHR0cHM6Ly9zdHMud2luZG93cy5uZXQvN2ZlODE0NDctZGE1Ny00Mzg1LWJlY2ItNmRlNTdmMjE0N
zdlLyIsImlhdCI6MTM4ODQ0MDg2MywibmJmIjoxMzg4NDQwODYzLCJleHAiOjEzODg0NDQ3NjMsInZlciI6IjEuMCIsInRpZCI6IjdmZTgxNDQ3
LWRhNTctNDM4NS1iZWNiLTZkZTU3ZjIxNDc3ZSIsIm9pZCI6IjY4Mzg5YWUyLTYyZmEtNGIxOC05MWZlLTUzZGQxMDlkNzRmNSIsInVwbiI6ImZ
yYW5rbUBjb250b3NvLmNvbSIsInVuaXF1ZV9uYW1lIjoiZnJhbmttQGNvbnRvc28uY29tIiwic3ViIjoiZGVOcUlqOUlPRTlQV0pXYkhzZnRYdD
JFYWJQVmwwQ2o4UUFtZWZSTFY5OCIsImZhbWlseV9uYW1lIjoiTWlsbGVyIiwiZ2l2ZW5fbmFtZSI6IkZyYW5rIiwiYXBwaWQiOiIyZDRkMTFhM
i1mODE0LTQ2YTctODkwYS0yNzRhNzJhNzMwOWUiLCJhcHBpZGFjciI6IjAiLCJzY3AiOiJ1c2VyX2ltcGVyc29uYXRpb24iLCJhY3IiOiIxIn0.
JZw8jC0gptZxVC7l5sFkdnJgP3_tRjeQEPgUn28XctVe3QqmheLZw7QVZDPCyGycDWBaqy7FLpSekET_BftDkewRhyHk9FW_KeEz0ch2c3i08NGNDbr6XYGVayNuS
esYk5Aw_p3ICRlUV1bqEwk-Jkzs9EEkQg4hbefqJS6yS1HoV_2EsEhpd_wCQpxK89WPs3hLYZETRJtG5kvCCEOvSHXmDE6eTHGTnEgsIk-UlPe275Dvou4gEAwLofhLDQbMSjnlV5VLsjimNBVcSRFShoxmQwBJR_b2011Y5IuD6St5zPnzruBbZYkGNurQK63TJPWmRd3mbJsGM0mf3CUQ",
"token_type": "Bearer",
"expires_in": "3600",
"expires_on": "1388444763",
"resource": "https://service.contoso.com/",
"refresh_token": "AwABAAAAvPM1KaPlrEqdFSBzjqfTGAMxZGUTdM0t4B4rTfgV29ghDOHRc2BC_hHeJaJICqjZ3mY2b_YNqmf9SoAylD1PycGCB90xzZeEDg6oBzOIPfYsbDWNf621pKo2Q3GGTHYlmNfwocOlrxK69hkha2CF12azM_NYhgO668yfcUl4VBbiSHZyd1NVZG5QTIOcbObu3qnLutbpadZGAxqjIbMkQ2bQS09fTrjMBtDE3D6kSMIodpCecoANo
n9b0LATkpitimVCrl-NyfN3oyG4ZCWu18M9-vEou4Sq-1oMDzExgAf61noxzkNiaTecM-Ve5cq6wHqYQjfV9DOz4lbceuYCAA",
"scope": "https%3A%2F%2Fgraph.microsoft.com%2Fmail.read",
"id_token": "
eyJ0eXAiOiJKV1QiLCJhbGciOiJub25lIn0.eyJhdWQiOiIyZDRkMTFhMi1mODE0LTQ2YTctODkwYS0yNzRhNzJhNzMwOWUiLCJpc3MiOiJodHR
wczovL3N0cy53aW5kb3dzLm5ldC83ZmU4MTQ0Ny1kYTU3LTQzODUtYmVjYi02ZGU1N2YyMTQ3N2UvIiwiaWF0IjoxMzg4NDQwODYzLCJuYmYiOj
EzODg0NDA4NjMsImV4cCI6MTM4ODQ0NDc2MywidmVyIjoiMS4wIiwidGlkIjoiN2ZlODE0NDctZGE1Ny00Mzg1LWJlY2ItNmRlNTdmMjE0NzdlI
iwib2lkIjoiNjgzODlhZTItNjJmYS00YjE4LTkxZmUtNTNkZDEwOWQ3NGY1IiwidXBuIjoiZnJhbmttQGNvbnRvc28uY29tIiwidW5pcXVlX25h
bWUiOiJmcmFua21AY29udG9zby5jb20iLCJzdWIiOiJKV3ZZZENXUGhobHBTMVpzZjd5WVV4U2hVd3RVbTV5elBtd18talgzZkhZIiwiZmFtaWx
5X25hbWUiOiJNaWxsZXIiLCJnaXZlbl9uYW1lIjoiRnJhbmsifQ.”
}
PARAMETER
DESCRIPTION
access_token
The requested access token. The app can use this token to
authenticate to the secured resource, such as a web API.
token_type
Indicates the token type value. The only type that Azure AD
supports is Bearer. For more information about Bearer tokens,
see OAuth2.0 Authorization Framework: Bearer Token Usage
(RFC 6750)
expires_in
How long the access token is valid (in seconds).
expires_on
The time when the access token expires. The date is
represented as the number of seconds from 1970-0101T0:0:0Z UTC until the expiration time. This value is used to
determine the lifetime of cached tokens.
resource
The App ID URI of the web API (secured resource).
scope
Impersonation permissions granted to the client application.
The default permission is user_impersonation . The owner of the
secured resource can register additional values in Azure AD.
refresh_token
An OAuth 2.0 refresh token. The app can use this token to
acquire additional access tokens after the current access token
expires. Refresh tokens are long-lived, and can be used to
retain access to resources for extended periods of time.
PARAMETER
DESCRIPTION
id_token
An unsigned JSON Web Token (JWT). The app can base64Url
decode the segments of this token to request information
about the user who signed in. The app can cache the values
and display them, but it should not rely on them for any
authorization or security boundaries.
JWT Token Claims
The JWT token in the value of the
id_token
parameter can be decoded into the following claims:
{
"typ": "JWT",
"alg": "none"
}.
{
"aud": "2d4d11a2-f814-46a7-890a-274a72a7309e",
"iss": "https://sts.windows.net/7fe81447-da57-4385-becb-6de57f21477e/",
"iat": 1388440863,
"nbf": 1388440863,
"exp": 1388444763,
"ver": "1.0",
"tid": "7fe81447-da57-4385-becb-6de57f21477e",
"oid": "68389ae2-62fa-4b18-91fe-53dd109d74f5",
"upn": "[email protected]",
"unique_name": "[email protected]",
"sub": "JWvYdCWPhhlpS1Zsf7yYUxShUwtUm5yzPmw_-jX3fHY",
"family_name": "Miller",
"given_name": "Frank"
}.
For more information about JSON web tokens, see the JWT IETF draft specification. For more information about the
token types and claims, read Supported Token and Claim Types
The
id_token
parameter includes the following claim types:
CLAIM TYPE
DESCRIPTION
aud
Audience of the token. When the token is issued to a client
application, the audience is the client_id of the client.
exp
Expiration time. The time when the token expires. For the
token to be valid, the current date/time must be less than or
equal to the exp value. The time is represented as the
number of seconds from January 1, 1970 (1970-0101T0:0:0Z) UTC until the time the token was issued.
family_name
User’s last name or surname. The application can display this
value.
given_name
User’s first name. The application can display this value.
iat
Issued at time. The time when the JWT was issued. The time is
represented as the number of seconds from January 1, 1970
(1970-01-01T0:0:0Z) UTC until the time the token was issued.
iss
Identifies the token issuer
CLAIM TYPE
DESCRIPTION
nbf
Not before time. The time when the token becomes effective.
For the token to be valid, the current date/time must be
greater than or equal to the Nbf value. The time is represented
as the number of seconds from January 1, 1970 (1970-0101T0:0:0Z) UTC until the time the token was issued.
oid
Object identifier (ID) of the user object in Azure AD.
sub
Token subject identifier. This is a persistent and immutable
identifier for the user that the token describes. Use this value
in caching logic.
tid
Tenant identifier (ID) of the Azure AD tenant that issued the
token.
unique_name
A unique identifier for that can be displayed to the user. This is
usually a user principal name (UPN).
upn
User principal name of the user.
ver
Version. The version of the JWT token, typically 1.0.
Error response
The token issuance endpoint errors are HTTP error codes, because the client calls the token issuance endpoint
directly. In addition to the HTTP status code, the Azure AD token issuance endpoint also returns a JSON document
with objects that describe the error.
A sample error response could look like this:
{
"error": "invalid_grant",
"error_description": "AADSTS70002: Error validating credentials. AADSTS70008: The provided authorization code
or refresh token is expired. Send a new interactive authorization request for this user and resource.\r\nTrace
ID: 3939d04c-d7ba-42bf-9cb7-1e5854cdce9e\r\nCorrelation ID: a8125194-2dc8-4078-90ba-7b6592a7f231\r\nTimestamp:
2016-04-11 18:00:12Z",
"error_codes": [
70002,
70008
],
"timestamp": "2016-04-11 18:00:12Z",
"trace_id": "3939d04c-d7ba-42bf-9cb7-1e5854cdce9e",
"correlation_id": "a8125194-2dc8-4078-90ba-7b6592a7f231"
}
PARAMETER
DESCRIPTION
error
An error code string that can be used to classify types of
errors that occur, and can be used to react to errors.
error_description
A specific error message that can help a developer identify the
root cause of an authentication error.
error_codes
A list of STS-specific error codes that can help in diagnostics.
PARAMETER
DESCRIPTION
timestamp
The time at which the error occurred.
trace_id
A unique identifier for the request that can help in diagnostics.
correlation_id
A unique identifier for the request that can help in diagnostics
across components.
HTTP status codes
The following table lists the HTTP status codes that the token issuance endpoint returns. In some cases, the error
code is sufficient to describe the response, but if there are errors, you need to parse the accompanying JSON
document and examine its error code.
HTTP CODE
DESCRIPTION
400
Default HTTP code. Used in most cases and is typically due to
a malformed request. Fix and resubmit the request.
401
Authentication failed. For example, the request is missing the
client_secret parameter.
403
Authorization failed. For example, the user does not have
permission to access the resource.
500
An internal error has occurred at the service. Retry the request.
Error codes for token endpoint errors
ERROR CODE
DESCRIPTION
CLIENT ACTION
invalid_request
Protocol error, such as a missing
required parameter.
Fix and resubmit the request
invalid_grant
The authorization code is invalid or has
expired.
Try a new request to the
endpoint
unauthorized_client
The authenticated client is not
authorized to use this authorization
grant type.
This usually occurs when the client
application is not registered in Azure AD
or is not added to the user's Azure AD
tenant. The application can prompt the
user with instruction for installing the
application and adding it to Azure AD.
invalid_client
Client authentication failed.
The client credentials are not valid. To
fix, the application administrator
updates the credentials.
unsupported_grant_type
The authorization server does not
support the authorization grant type.
Change the grant type in the request.
This type of error should occur only
during development and be detected
during initial testing.
/authorize
ERROR CODE
DESCRIPTION
CLIENT ACTION
invalid_resource
The target resource is invalid because it
does not exist, Azure AD cannot find it,
or it is not correctly configured.
This indicates the resource, if it exists,
has not been configured in the tenant.
The application can prompt the user
with instruction for installing the
application and adding it to Azure AD.
interaction_required
The request requires user interaction.
For example, an additional
authentication step is required.
Retry the request with the same
resource.
temporarily_unavailable
The server is temporarily too busy to
handle the request.
Retry the request. The client application
might explain to the user that its
response is delayed due to a temporary
condition.
Use the access token to access the resource
Now that you've successfully acquired an access_token , you can use the token in requests to Web APIs, by
including it in the Authorization header. The RFC 6750 specification explains how to use bearer tokens in HTTP
requests to access protected resources.
Sample request
GET /data HTTP/1.1
Host: service.contoso.com
Authorization: Bearer
eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik5HVEZ2ZEstZnl0aEV1THdqcHdBSk9NOW4tQSJ9.eyJhdWQiOiJodHRwczovL3Nlcn
ZpY2UuY29udG9zby5jb20vIiwiaXNzIjoiaHR0cHM6Ly9zdHMud2luZG93cy5uZXQvN2ZlODE0NDctZGE1Ny00Mzg1LWJlY2ItNmRlNTdmMjE0N
zdlLyIsImlhdCI6MTM4ODQ0MDg2MywibmJmIjoxMzg4NDQwODYzLCJleHAiOjEzODg0NDQ3NjMsInZlciI6IjEuMCIsInRpZCI6IjdmZTgxNDQ3
LWRhNTctNDM4NS1iZWNiLTZkZTU3ZjIxNDc3ZSIsIm9pZCI6IjY4Mzg5YWUyLTYyZmEtNGIxOC05MWZlLTUzZGQxMDlkNzRmNSIsInVwbiI6ImZ
yYW5rbUBjb250b3NvLmNvbSIsInVuaXF1ZV9uYW1lIjoiZnJhbmttQGNvbnRvc28uY29tIiwic3ViIjoiZGVOcUlqOUlPRTlQV0pXYkhzZnRYdD
JFYWJQVmwwQ2o4UUFtZWZSTFY5OCIsImZhbWlseV9uYW1lIjoiTWlsbGVyIiwiZ2l2ZW5fbmFtZSI6IkZyYW5rIiwiYXBwaWQiOiIyZDRkMTFhM
i1mODE0LTQ2YTctODkwYS0yNzRhNzJhNzMwOWUiLCJhcHBpZGFjciI6IjAiLCJzY3AiOiJ1c2VyX2ltcGVyc29uYXRpb24iLCJhY3IiOiIxIn0.
JZw8jC0gptZxVC7l5sFkdnJgP3_tRjeQEPgUn28XctVe3QqmheLZw7QVZDPCyGycDWBaqy7FLpSekET_BftDkewRhyHk9FW_KeEz0ch2c3i08NGNDbr6XYGVayNuS
esYk5Aw_p3ICRlUV1bqEwk-Jkzs9EEkQg4hbefqJS6yS1HoV_2EsEhpd_wCQpxK89WPs3hLYZETRJtG5kvCCEOvSHXmDE6eTHGTnEgsIk-UlPe275Dvou4gEAwLofhLDQbMSjnlV5VLsjimNBVcSRFShoxmQwBJR_b2011Y5IuD6St5zPnzruBbZYkGNurQK63TJPWmRd3mbJsGM0mf3CUQ
Error Response
Secured resources that implement RFC 6750 issue HTTP status codes. If the request does not include authentication
credentials or is missing the token, the response includes an WWW-Authenticate header. When a request fails, the
resource server responds with the HTTP status code and an error code.
The following is an example of an unsuccessful response when the client request does not include the bearer token:
HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer authorization_uri="https://login.window.net/contoso.com/oauth2/authorize",
error="invalid_token", error_description="The access token is missing.",
Error parameters
PARAMETER
DESCRIPTION
PARAMETER
DESCRIPTION
authorization_uri
The URI (physical endpoint) of the authorization server. This
value is also used as a lookup key to get more information
about the server from a discovery endpoint.
The client must validate that the authorization server is
trusted. When the resource is protected by Azure AD, it is
sufficient to verify that the URL begins with
https://login.windows.net or another hostname that Azure
AD supports. A tenant-specific resource should always
return a tenant-specific authorization URI.
error
An error code value defined in Section 5.2 of the OAuth 2.0
Authorization Framework.
error_description
A more detailed description of the error. This message is not
intended to be end-user friendly.
resource_id
Returns the unique identifier of the resource. The client
application can use this identifier as the value of the resource
parameter when it requests a token for the resource.
It is important for the client application to verify this value,
otherwise a malicious service might be able to induce an
elevation-of-privileges attack
The recommended strategy for preventing an attack is to
verify that the resource_id matches the base of the web
API URL that being accessed. For example, if
https://service.contoso.com/data is being accessed, the
resource_id can be htttps://service.contoso.com/. The client
application must reject a resource_id that does not begin
with the base URL unless there is a reliable alternate way
to verify the id.
Bearer scheme error codes
The RFC 6750 specification defines the following errors for resources that use the WWW-Authenticate header and
Bearer scheme in the response.
HTTP STATUS CODE
ERROR CODE
DESCRIPTION
CLIENT ACTION
400
invalid_request
The request is not wellformed. For example, it
might be missing a
parameter or using the same
parameter twice.
Fix the error and retry the
request. This type of error
should occur only during
development and be
detected in initial testing.
401
invalid_token
The access token is missing,
invalid, or is revoked. The
value of the
error_description parameter
provides additional detail.
Request a new token from
the authorization server. If
the new token fails, an
unexpected error has
occurred. Send an error
message to the user and
retry after random delays.
HTTP STATUS CODE
ERROR CODE
DESCRIPTION
CLIENT ACTION
403
insufficient_scope
The access token does not
contain the impersonation
permissions required to
access the resource.
Send a new authorization
request to the authorization
endpoint. If the response
contains the scope
parameter, use the scope
value in the request to the
resource.
403
insufficient_access
The subject of the token
does not have the
permissions that are
required to access the
resource.
Prompt the user to use a
different account or to
request permissions to the
specified resource.
Refreshing the access tokens
Access Tokens are short-lived and must be refreshed after they expire to continue accessing resources. You can
refresh the access_token by submitting another POST request to the /token endpoint, but this time providing the
refresh_token instead of the code .
Refresh tokens do not have specified lifetimes. Typically, the lifetimes of refresh tokens are relatively long. However,
in some cases, refresh tokens expire, are revoked, or lack sufficient privileges for the desired action. Your application
needs to expect and handle errors returned by the token issuance endpoint correctly.
When you receive a response with a refresh token error, discard the current refresh token and request a new
authorization code or access token. In particular, when using a refresh token in the Authorization Code Grant flow, if
you receive a response with the interaction_required or invalid_grant error codes, discard the refresh token and
request a new authorization code.
A sample request to the tenant-specific endpoint (you can also use the common endpoint) to get a new access
token using a refresh token looks like this:
// Line breaks for legibility only
POST /{tenant}/oauth2/token HTTP/1.1
Host: https://login.microsoftonline.com
Content-Type: application/x-www-form-urlencoded
client_id=6731de76-14a6-49ae-97bc-6eba6914391e
&refresh_token=OAAABAAAAiL9Kn2Z27UubvWFPbm0gLWQJVzCTE9UkP3pSx1aXxUjq...
&grant_type=refresh_token
&resource=https%3A%2F%2Fservice.contoso.com%2F
&client_secret=JqQX2PNo9bpM0uEihUPzyrh
// NOTE: Only required for web apps
PARAMETER
DESCRIPTION
access_token
The new access token that was requested.
expires_in
The remaining lifetime of the token in seconds. A typical value
is 3600 (one hour).
expires_on
The date and time on which the token expires. The date is
represented as the number of seconds from 1970-0101T0:0:0Z UTC until the expiration time.
PARAMETER
DESCRIPTION
refresh_token
A new OAuth 2.0 refresh_token that can be used to request
new access tokens when the one in this response expires.
resource
Identifies the secured resource that the access token can be
used to access.
scope
Impersonation permissions granted to the native client
application. The default permission is user_impersonation.
The owner of the target resource can register alternate values
in Azure AD.
token_type
The token type. The only supported value is bearer.
Successful response
A successful token response will look like:
{
"token_type": "Bearer",
"expires_in": "3600",
"expires_on": "1460404526",
"resource": "https://service.contoso.com/",
"access_token":
"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik5HVEZ2ZEstZnl0aEV1THdqcHdBSk9NOW4tQSJ9.eyJhdWQiOiJodHRwczovL3Nlc
nZpY2UuY29udG9zby5jb20vIiwiaXNzIjoiaHR0cHM6Ly9zdHMud2luZG93cy5uZXQvN2ZlODE0NDctZGE1Ny00Mzg1LWJlY2ItNmRlNTdmMjE0
NzdlLyIsImlhdCI6MTM4ODQ0MDg2MywibmJmIjoxMzg4NDQwODYzLCJleHAiOjEzODg0NDQ3NjMsInZlciI6IjEuMCIsInRpZCI6IjdmZTgxNDQ
3LWRhNTctNDM4NS1iZWNiLTZkZTU3ZjIxNDc3ZSIsIm9pZCI6IjY4Mzg5YWUyLTYyZmEtNGIxOC05MWZlLTUzZGQxMDlkNzRmNSIsInVwbiI6Im
ZyYW5rbUBjb250b3NvLmNvbSIsInVuaXF1ZV9uYW1lIjoiZnJhbmttQGNvbnRvc28uY29tIiwic3ViIjoiZGVOcUlqOUlPRTlQV0pXYkhzZnRYd
DJFYWJQVmwwQ2o4UUFtZWZSTFY5OCIsImZhbWlseV9uYW1lIjoiTWlsbGVyIiwiZ2l2ZW5fbmFtZSI6IkZyYW5rIiwiYXBwaWQiOiIyZDRkMTFh
Mi1mODE0LTQ2YTctODkwYS0yNzRhNzJhNzMwOWUiLCJhcHBpZGFjciI6IjAiLCJzY3AiOiJ1c2VyX2ltcGVyc29uYXRpb24iLCJhY3IiOiIxIn0
.JZw8jC0gptZxVC7l5sFkdnJgP3_tRjeQEPgUn28XctVe3QqmheLZw7QVZDPCyGycDWBaqy7FLpSekET_BftDkewRhyHk9FW_KeEz0ch2c3i08NGNDbr6XYGVayNuS
esYk5Aw_p3ICRlUV1bqEwk-Jkzs9EEkQg4hbefqJS6yS1HoV_2EsEhpd_wCQpxK89WPs3hLYZETRJtG5kvCCEOvSHXmDE6eTHGTnEgsIk-UlPe275Dvou4gEAwLofhLDQbMSjnlV5VLsjimNBVcSRFShoxmQwBJR_b2011Y5IuD6St5zPnzruBbZYkGNurQK63TJPWmRd3mbJsGM0mf3CUQ",
"refresh_token": "AwABAAAAv YNqmf9SoAylD1PycGCB90xzZeEDg6oBzOIPfYsbDWNf621pKo2Q3GGTHYlmNfwocOlrxK69hkha2CF12azM_NYhgO668yfcUl4VBbiSHZyd1NVZG5QTIOcbObu3qnLutbpadZGAxqjIbMkQ2bQS09fTrjMBtDE3D6kSMIodpCecoANo
n9b0LATkpitimVCrl PM1KaPlrEqdFSBzjqfTGAMxZGUTdM0t4B4rTfgV29ghDOHRc2BC_hHeJaJICqjZ3mY2b_YNqmf9SoAylD1PycGCB90xzZeEDg6oBzOIPfYsbDWNf621pKo2Q3GGTHYlmNfwocOlrxK69hkha2CF12azM_NYhgO668yfmVCrl-NyfN3oyG4ZCWu18M9-vEou4Sq-1oMDzExgAf61noxzkNiaTecMVe5cq6wHqYQjfV9DOz4lbceuYCAA"
}
Error response
A sample error response could look like this:
{
"error": "invalid_resource",
"error_description": "AADSTS50001: The application named https://foo.microsoft.com/mail.read was not found in
the tenant named 295e01fc-0c56-4ac3-ac57-5d0ed568f872. This can happen if the application has not been
installed by the administrator of the tenant or consented to by any user in the tenant. You might have sent
your authentication request to the wrong tenant.\r\nTrace ID: ef1f89f6-a14f-49de-986861bd4072f0a9\r\nCorrelation ID: b6908274-2c58-4e91-aea9-1f6b9c99347c\r\nTimestamp: 2016-04-11 18:59:01Z",
"error_codes": [
50001
],
"timestamp": "2016-04-11 18:59:01Z",
"trace_id": "ef1f89f6-a14f-49de-9868-61bd4072f0a9",
"correlation_id": "b6908274-2c58-4e91-aea9-1f6b9c99347c"
}
PARAMETER
DESCRIPTION
error
An error code string that can be used to classify types of
errors that occur, and can be used to react to errors.
error_description
A specific error message that can help a developer identify the
root cause of an authentication error.
error_codes
A list of STS-specific error codes that can help in diagnostics.
timestamp
The time at which the error occurred.
trace_id
A unique identifier for the request that can help in diagnostics.
correlation_id
A unique identifier for the request that can help in diagnostics
across components.
For a description of the error codes and the recommended client action, see Error codes for token endpoint errors.
Understanding the OAuth2 implicit grant flow in
Azure Active Directory (AD)
1/30/2017 • 7 min to read • Edit Online
The OAuth2 implicit grant is notorious for being the grant with the longest list of security concerns in the OAuth2
specification. And yet, that is the approach implemented by ADAL JS and the one we recommend when writing
SPA applications. What gives? It’s all a matter of tradeoffs: and as it turns out, the implicit grant is the best
approach you can pursue for applications that consume a Web API via JavaScript from a browser.
What is the OAuth2 implicit grant?
The quintessential OAuth2 authorization code grant is the authorization grant which uses two separate
endpoints. The authorization endpoint is used for the user interaction phase, which results in an authorization
code. The token endpoint is then used by the client for exchanging the code for an access token, and often a
refresh token as well. Web applications are required to present their own application credentials to the token
endpoint, so that the authorization server can authenticate the client.
The OAuth2 implicit grant is a variant of other authorization grants. It allows a client to obtain an access token
(and id_token, when using OpenId Connect) directly from the authorization endpoint, without contacting the
token endpoint nor authenticating the client. This variant was specifically designed for JavaScript based
applications running in a Web browser: in the original OAuth2 specification, tokens are returned in a URI
fragment. That makes the token bits available to the JavaScript code in the client, but it guarantees they won’t be
included in redirects toward the server. Returning tokens via browser redirects directly from the authorization
endpoint. It also has the advantage of eliminating any requirements for cross origin calls, which are necessary if
the JavaScript application is required to contact the token endpoint.
An important characteristic of the OAuth2 implicit grant is the fact that such flows never return refresh tokens to
the client. As we will see in the next section, that isn’t really necessary and would in fact be a security issue.
Suitable scenarios for the OAuth2 implicit grant
As the OAuth2 specification itself declares, the implicit grant has been devised to enable user-agent applications
– that is to say, JavaScript applications executing within a browser. The defining characteristic of such
applications is that JavaScript code is used for accessing server resources (typically a Web API) and for updating
the application UX accordingly. Think of applications like Gmail or Outlook Web Access: when you select a
message from your inbox, only the message visualization panel changes to display the new selection, while the
rest of the page remains unmodified. This is in contrast with traditional redirect-based Web apps, where every
user interaction results in a full page postback and a full page rendering of the new server response.
Applications that take the JavaScript based approach to its extreme are called Single Page Applications, or SPAs:
the idea is that those applications only serve an initial HTML page and associated JavaScript, with all subsequent
interactions being driven by Web API calls performed via JavaScript. However, hybrid approaches, where the
application is mostly postback-driven but performs occasional JS calls, are not uncommon – the discussion about
implicit flow usage is relevant for those as well.
Redirect-based applications typically secure their requests via cookies, however, that approach does not work as
well for JavaScript applications. Cookies only work against the domain they have been generated for, while
JavaScript calls might be directed toward other domains. In fact, that will frequently be the case: think of
applications invoking Microsoft Graph API, Office API, Azure API – all residing outside the domain from where the
application is served. A growing trend for JavaScript applications is to have no backend at all, relying 100% on
3rd party Web APIs to implement their business function.
Currently, the preferred method of protecting calls to a Web API is to use the OAuth2 bearer token approach,
where every call is accompanied by an OAuth2 access token. The Web API examines the incoming access token
and, if it finds in it the necessary scopes, it grants access to the requested operation. The implicit flow provides a
convenient mechanism for JavaScript applications to obtain access tokens for a Web API, offering numerous
advantages in respect to cookies:
Tokens can be reliably obtained without any need for cross origin calls – mandatory registration of the
redirect URI to which tokens are return guarantees that tokens are not displaced
JavaScript applications can obtain as many access tokens as they need, for as many Web APIs they target –
with no restriction on domains
HTML5 features like session or local storage grant full control over token caching and lifetime management,
whereas cookies management is opaque to the app
Access tokens aren’t susceptible to Cross-site request forgery (CSRF) attacks
The implicit grant flow does not issue refresh tokens, mostly for security reasons. A refresh token isn’t as
narrowly scoped as access tokens, granting far more power hence inflicting far more damage in case it is leaked
out. In the implicit flow, tokens are delivered in the URL, hence the risk of interception is higher than in the
authorization code grant.
However, note that a JavaScript application has another mechanism at its disposal for renewing access tokens
without repeatedly prompting the user for credentials. The application can use a hidden iframe to perform new
token requests against the authorization endpoint of Azure AD: as long as the browser still has an active session
(read: has a session cookie) against the Azure AD domain, the authentication request can successfully occur
without any need for user interaction.
This model grants the JavaScript application the ability to independently renew access tokens and even acquire
new ones for a new API (provided that the user previously consented for them. This avoids the added burden of
acquiring, maintaining, and protecting a high value artifact such as a refresh token. The artifact which makes the
silent renewal possible, the Azure AD session cookie, is managed outside of the application. Another advantage
of this approach is a user can sign out from Azure AD, using any of the applications signed into Azure AD,
running in any of the browser tabs. This results in the deletion of the Azure AD session cookie, and the JavaScript
application will automatically lose the ability to renew tokens for the signed out user.
Is the implicit grant suitable for my app?
The implicit grant presents more risks than other grants, and the areas you need to pay attention to are well
documented. For example, Misuse of Access Token to Impersonate Resource Owner in Implicit Flow and OAuth
2.0 Threat Model and Security Considerations). However, the higher risk profile is largely due to the fact that it is
meant to enable applications that execute active code, served by a remote resource to a browser. If you are
planning an SPA architecture, have no backend components or intend to invoke a Web API via JavaScript, use of
the implicit flow for token acquisition is recommended.
If your application is a native client, the implicit flow isn’t a great fit. The absence of the Azure AD session cookie
in the context of a native client deprives your application from the means of maintaining a long lived session.
Which means your application will repeatedly prompt the user when obtaining access tokens for new resources.
If you are developing a Web application which includes a backend, and consuming an API from its backend code,
the implicit flow is also not a good fit. Other grants give you far more power. For example, the OAuth2 client
credentials grant provides the ability to obtain tokens that reflect the permissions assigned to the application
itself, as opposed to user delegations. This means the client has the ability to maintain programmatic access to
resources even when a user is not actively engaged in a session, and so on. Not only that, but such grants give
higher security guarantees. For instance, access tokens never transit through the user browser, they don’t risk
being saved in the browser history, and so on. The client application can also perform strong authentication
when requesting a token.
Next steps
For a complete list of developer resources, including reference information for the protocols and OAuth2
authorization grant flows support by Azure AD, refer to the Azure AD Developer's Guide
See How to integrate an application with Azure AD for additional depth on the application integration process.
How Azure Active Directory uses the SAML protocol
4/12/2017 • 1 min to read • Edit Online
Azure Active Directory (Azure AD) uses the SAML 2.0 protocol to enable applications to provide a single sign-on
experience to their users. The Single Sign-On and Single Sign-Out SAML profiles of Azure AD explain how SAML
assertions, protocols and bindings are used in the identity provider service.
SAML Protocol requires the identity provider (Azure AD) and the service provider (the application) to exchange
information about themselves.
When an application is registered with Azure AD, the app developer registers federation-related information with
Azure AD. This includes the Redirect URI and Metadata URI of the application.
Azure AD uses the Metadata URI of the cloud service to retrieve the signing key and the logout URI of the cloud
service. If the application does not support a metadata URI, the developer must contact Microsoft support to
provide the logout URI and signing key.
Azure Active Directory exposes tenant-specific and common (tenant-independent) single sign-on and single signout endpoints. These URLs represent addressable locations -- they are not just an identifiers -- so you can go to the
endpoint to read the metadata.
The Tenant-specific endpoint is located at
https://login.microsoftonline.com/<TenantDomainName>/FederationMetadata/2007-06/FederationMetadata.xml
.
The placeholder represents a registered domain name or TenantID GUID of an Azure AD tenant. For
example, the federation metadata of the contoso.com tenant is at:
https://login.microsoftonline.com/contoso.com/FederationMetadata/2007-06/FederationMetadata.xml
The Tenant-independent endpoint is located at
https://login.microsoftonline.com/common/FederationMetadata/2007-06/FederationMetadata.xml
.In this
endpoint address, common appears, instead of a tenant domain name or ID.
For information about the Federation Metadata documents that Azure AD publishes, see Federation Metadata.
Customizing claims issued in the SAML token for preintegrated apps in Azure Active Directory
4/27/2017 • 3 min to read • Edit Online
Today Azure Active Directory supports thousands of pre-integrated applications in the Azure AD Application
Gallery, including over 150 that support single sign-on using the SAML 2.0 protocol. When a user authenticates to
an application through Azure AD using SAML, Azure AD sends a token to the application (via an HTTP 302 redirect).
And then, the application validates and uses the token to log the user in instead of prompting for a username and
password. These SAML tokens contain pieces of information about the user known as "claims".
In identity-speak, a “claim” is information that an identity provider states about a user inside the token they issue
for that user. In a SAML token, this data is typically contained in the SAML Attribute Statement, and the user’s
unique ID is typically represented in the SAML Subject.
By default, Azure AD issues a SAML token to your application that contains a NameIdentifier claim, with a value of
the user’s username in Azure AD. this value can uniquely identify the user. The SAML token also contains additional
claims containing the user’s email address, first name, and last name.
To view or edit the claims issued in the SAML token to the application, open the application record in Azure classic
portal and select the Attributes tab underneath the application.
There are two possible reasons why you might need to edit the claims issued in the SAML token:
The application has been written to require a different set of claim URIs or claim values
Your application has been deployed in a way that requires the NameIdentifier claim to be something other than
the username (AKA user principal name) stored in Azure Active Directory.
You can edit any of the default claim values. Select the pencil-shaped icon that appears on the right whenever you
mouse over one of the rows in the SAML token attributes table. You can also remove claims (other than
NameIdentifier) using the X icon, and add new claims using the Add user attribute button.
Editing the NameIdentifier claim
To solve the problem where the application has been deployed using a different username, click the pencil icon
next to the NameIdentifier claim. This action provides a dialog with several different options:
In the Attribute Value menu, select user.mail to set the NameIdentifier claim to be the user’s email address in the
directory. Or, select user.onpremisessamaccountname to set to the user’s SAM Account Name that has been
synced from on-premise Azure AD.
You can also use the special ExtractMailPrefix() function to remove the domain suffix from either the email address
or the user principal name. And then, only the first part of the user name being passed through (for example,
"joe_smith" instead of [email protected]).
Adding claims
When adding a claim, you can specify the attribute name (which doesn’t strictly need to follow a URI pattern as per
the SAML spec). Set the value to any user attribute that is stored in the directory.
For example, you need to send the department that the user belongs to in their organization as a claim (such as,
Sales). You can enter whatever claim value is expected by the application, and then select user.department as the
value.
If for a given user there is no value stored for a selected attribute, then that claim is not being issued in the token.
Note: The user.onpremisesecurityidentifier and user.onpremisesamaccountname are only supported when
synchronizing user data from on-premise Active Directory using the Azure AD Connect tool.
Next steps
Article Index for Application Management in Azure Active Directory
Configuring single sign-on to applications that are not in the Azure Active Directory application gallery
Troubleshooting SAML-Based Single Sign-On
How to debug SAML-based single sign-on to
applications in Azure Active Directory
4/12/2017 • 1 min to read • Edit Online
When debugging a SAML-based application integration, it is often helpful to use a tool like Fiddler to see the SAML
request, the SAML response, and the actual SAML token that is issued to the application. By examining the SAML
token, you can ensure that all of the required attributes, the username in the SAML subject, and the issuer URI are
coming through as expected.
The response from Azure AD that contains the SAML token is typically the one that occurs after an HTTP 302
redirect from https://login.windows.net, and is sent to the configured Reply URL of the application.
You can view the SAML token by selecting this line and then selecting the Inspectors > WebForms tab in the right
panel. From there, right-click the SAMLResponse value and select Send to TextWizard. Then select From Base64
from the Transform menu to decode the token and see its contents.
Note: To see the contents of this HTTP request, Fiddler may prompt you to configure decryption of HTTPS traffic,
which you will need to do.
Related Articles
Article Index for Application Management in Azure Active Directory
Configuring single sign-on to applications that are not in the Azure Active Directory application gallery
How to Customize Claims Issued in the SAML Token for Pre-Integrated Apps
Single Sign-On SAML protocol
2/8/2017 • 7 min to read • Edit Online
This article covers the SAML 2.0 authentication requests and responses that Azure Active Directory (Azure AD)
supports for Single Sign-On.
The protocol diagram below describes the single sign-on sequence. The cloud service (the service provider) uses an
HTTP Redirect binding to pass an AuthnRequest (authentication request) element to Azure AD (the identity
provider). Azure AD then uses an HTTP post binding to post a Response element to the cloud service.
AuthnRequest
To request a user authentication, cloud services send an
AuthnRequest could look like this:
AuthnRequest
element to Azure AD. A sample SAML 2.0
<samlp:AuthnRequest
xmlns="urn:oasis:names:tc:SAML:2.0:metadata"
ID="id6c1c178c166d486687be4aaf5e482730"
Version="2.0" IssueInstant="2013-03-18T03:28:54.1839884Z"
xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol">
<Issuer xmlns="urn:oasis:names:tc:SAML:2.0:assertion">https://www.contoso.com</Issuer>
</samlp:AuthnRequest>
PARAMETER
ID
DESCRIPTION
required
Azure AD uses this attribute to
populate the InResponseTo attribute of
the returned response. ID must not
begin with a number, so a common
strategy is to prepend a string like "id"
to the string representation of a GUID.
For example,
id6c1c178c166d486687be4aaf5e482730 is a
valid ID.
PARAMETER
DESCRIPTION
Version
required
This should be 2.0.
IssueInstant
required
This is a DateTime string with a UTC
value and round-trip format ("o"). Azure
AD expects a DateTime value of this
type, but does not evaluate or use the
value.
AssertionConsumerServiceUrl
optional
If provided, this must match the
RedirectUri of the cloud service in Azure
AD.
ForceAuthn
optional
This is a boolean value. If true, this
means that the user will be forced to reauthenticate, even if they have a valid
session with Azure AD.
IsPassive
optional
This is a boolean value that specifies
whether Azure AD should authenticate
the user silently, without user
interaction, using the session cookie if
one exists. If this is true, Azure AD will
attempt to authenticate the user using
the session cookie.
All other AuthnRequest attributes, such as Consent, Destination, AssertionConsumerServiceIndex,
AttributeConsumerServiceIndex and ProviderName are ignored.
Azure AD also ignores the
Conditions
element in
AuthnRequest
.
Issuer
The Issuer element in an AuthnRequest must exactly match one of the ServicePrincipalNames in the cloud
service in Azure AD. Typically, this is set to the App ID URI that is specified during application registration.
A sample SAML excerpt containing the
Issuer
element looks like this:
<Issuer xmlns="urn:oasis:names:tc:SAML:2.0:assertion">https://www.contoso.com</Issuer>
NameIDPolicy
This element requests a particular name ID format in the response and is optional in
to Azure AD.
A sample
NameIdPolicy
AuthnRequest
elements sent
element looks like this:
<NameIDPolicy Format="urn:oasis:names:tc:SAML:2.0:nameid-format:persistent"/>
If NameIDPolicy is provided, you can include its optional Format attribute. The
of the following values; any other value results in an error.
urn:oasis:names:tc:SAML:2.0:nameid-format:persistent
Format
attribute can have only one
: Azure Active Directory issues the NameID claim as a
pairwise identifier.
urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress
mail address format.
: Azure Active Directory issues the NameID claim in e-
: This value permits Azure Active Directory to select the
claim format. Azure Active Directory issues the NameID as a pairwise identifier.
urn:oasis:names:tc:SAML:2.0:nameid-format:transient : Azure Active Directory issues the NameID claim as a
randomly-generated value that is unique to the current SSO operation. This means that the value is temporary
and cannot be used to identify the authenticating user.
urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified
Azure AD ignores the
AllowCreate
attribute.
RequestAuthnContext
The RequestedAuthnContext element specifies the desired authentication methods. It is optional in
elements sent to Azure AD. Azure AD supports only one AuthnContextClassRef value:
urn:oasis:names:tc:SAML:2.0:ac:classes:Password .
Scoping
The Scoping element, which includes a list of identity providers, is optional in
Azure AD.
If provided, do not include the
supported.
ProxyCount
Signature
Do not include a Signature element in
authentication requests.
Subject
Azure AD ignores the
Subject
attribute,
AuthnRequest
element of
IDPListOption
or
AuthnRequest
RequesterID
AuthnRequest
elements sent to
element, as they are not
elements, as Azure AD does not support signed
AuthnRequest
elements.
Response
When a requested sign-on completes successfully, Azure AD posts a response to the cloud service. A sample
response to a successful sign-on attempt looks like this:
<samlp:Response ID="_a4958bfd-e107-4e67-b06d-0d85ade2e76a" Version="2.0" IssueInstant="2013-0318T07:38:15.144Z" Destination="https://contoso.com/identity/inboundsso.aspx"
InResponseTo="id758d0ef385634593a77bdf7e632984b6" xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol">
<Issuer xmlns="urn:oasis:names:tc:SAML:2.0:assertion"> https://login.microsoftonline.com/82869000-6ad1-48f08171-272ed18796e9/</Issuer>
<ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
...
</ds:Signature>
<samlp:Status>
<samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success" />
</samlp:Status>
<Assertion ID="_bf9c623d-cc20-407a-9a59-c2d0aee84d12" IssueInstant="2013-03-18T07:38:15.144Z" Version="2.0"
xmlns="urn:oasis:names:tc:SAML:2.0:assertion">
<Issuer>https://login.microsoftonline.com/82869000-6ad1-48f0-8171-272ed18796e9/</Issuer>
<ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
...
</ds:Signature>
<Subject>
<NameID>Uz2Pqz1X7pxe4XLWxV9KJQ+n59d573SepSAkuYKSde8=</NameID>
<SubjectConfirmation Method="urn:oasis:names:tc:SAML:2.0:cm:bearer">
<SubjectConfirmationData InResponseTo="id758d0ef385634593a77bdf7e632984b6" NotOnOrAfter="2013-0318T07:43:15.144Z" Recipient="https://contoso.com/identity/inboundsso.aspx" />
</SubjectConfirmation>
</Subject>
<Conditions NotBefore="2013-03-18T07:38:15.128Z" NotOnOrAfter="2013-03-18T08:48:15.128Z">
<AudienceRestriction>
<Audience>https://www.contoso.com</Audience>
</AudienceRestriction>
</Conditions>
<AttributeStatement>
<Attribute Name="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name">
<AttributeValue>[email protected]</AttributeValue>
</Attribute>
<Attribute Name="http://schemas.microsoft.com/identity/claims/objectidentifier">
<AttributeValue>3F2504E0-4F89-11D3-9A0C-0305E82C3301</AttributeValue>
</Attribute>
...
</AttributeStatement>
<AuthnStatement AuthnInstant="2013-03-18T07:33:56.000Z" SessionIndex="_bf9c623d-cc20-407a-9a59c2d0aee84d12">
<AuthnContext>
<AuthnContextClassRef> urn:oasis:names:tc:SAML:2.0:ac:classes:Password</AuthnContextClassRef>
</AuthnContext>
</AuthnStatement>
</Assertion>
</samlp:Response>
Response
The Response element includes the result of the authorization request. Azure AD sets the
IssueInstant values in the Response element. It also sets the following attributes:
Destination
: When sign-on completes successfully, this is set to the
RedirectUri
ID
,
Version
and
of the service provider (cloud
service).
InResponseTo
: This is set to the
ID
Issuer
Azure AD sets the Issuer element to
the Azure AD tenant.
attribute of the
AuthnRequest
element that initiated the response.
https://login.microsoftonline.com/<TenantIDGUID>/
For example, a sample response with Issuer element could look like this:
where is the tenant ID of
<Issuer xmlns="urn:oasis:names:tc:SAML:2.0:assertion"> https://login.microsoftonline.com/82869000-6ad1-48f08171-272ed18796e9/</Issuer>
Status
The Status element conveys the success or failure of sign-on. It includes the StatusCode element, which contains
a code or a set of nested codes that represent the status of the request. It also includes the StatusMessage element,
which contains custom error messages that are generated during the sign-on process.
The following is a SAML response to an unsuccessful sign-on attempt.
<samlp:Response ID="_f0961a83-d071-4be5-a18c-9ae7b22987a4" Version="2.0" IssueInstant="2013-0318T08:49:24.405Z" InResponseTo="iddce91f96e56747b5ace6d2e2aa9d4f8c"
xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol">
<Issuer xmlns="urn:oasis:names:tc:SAML:2.0:assertion">https://sts.windows.net/82869000-6ad1-48f0-8171272ed18796e9/</Issuer>
<samlp:Status>
<samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Requester">
<samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:RequestUnsupported" />
</samlp:StatusCode>
<samlp:StatusMessage>AADSTS75006: An error occurred while processing a SAML2 Authentication request.
AADSTS90011: The SAML authentication request property 'NameIdentifierPolicy/SPNameQualifier' is not supported.
Trace ID: 66febed4-e737-49ff-ac23-464ba090d57c
Timestamp: 2013-03-18 08:49:24Z</samlp:StatusMessage>
</samlp:Status>
Assertion
In addition to the
of the response.
ID
,
IssueInstant
and
Version
, Azure AD sets the following elements in the
Assertion
element
Issuer
This is set to
https://sts.windows.net/<TenantIDGUID>/
where is the Tenant ID of the Azure AD tenant.
<Issuer>https://login.microsoftonline.com/82869000-6ad1-48f0-8171-272ed18796e9/</Issuer>
Signature
Azure AD signs the assertion in response to a successful sign-on. The Signature element contains a digital
signature that the cloud service can use to authenticate the source to verify the integrity of the assertion.
To generate this digital signature, Azure AD uses the signing key in the
document.
IDPSSODescriptor
element of its metadata
<ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
digital_signature_here
</ds:Signature>
Subject
This specifies the principal that is the subject of the statements in the assertion. It contains a NameID element,
which represents the authenticated user. The NameID value is a targeted identifier that is directed only to the
service provider that is the audience for the token. It is persistent - it can be revoked, but is never reassigned. It is
also opaque, in that it does not reveal anything about the user and cannot be used as an identifier for attribute
queries.
The
Method
attribute of the
SubjectConfirmation
element is always set to
urn:oasis:names:tc:SAML:2.0:cm:bearer
.
<Subject>
<NameID>Uz2Pqz1X7pxe4XLWxV9KJQ+n59d573SepSAkuYKSde8=</NameID>
<SubjectConfirmation Method="urn:oasis:names:tc:SAML:2.0:cm:bearer">
<SubjectConfirmationData InResponseTo="id758d0ef385634593a77bdf7e632984b6" NotOnOrAfter="2013-0318T07:43:15.144Z" Recipient="https://contoso.com/identity/inboundsso.aspx" />
</SubjectConfirmation>
</Subject>
Conditions
This element specifies conditions that define the acceptable use of SAML assertions.
<Conditions NotBefore="2013-03-18T07:38:15.128Z" NotOnOrAfter="2013-03-18T08:48:15.128Z">
<AudienceRestriction>
<Audience>https://www.contoso.com</Audience>
</AudienceRestriction>
</Conditions>
The
NotBefore
and
NotOnOrAfter
attributes specify the interval during which the assertion is valid.
The value of the NotBefore attribute is equal to or slightly (less than a second) later than the value of
IssueInstant attribute of the Assertion element. Azure AD does not account for any time difference between
itself and the cloud service (service provider), and does not add any buffer to this time.
The value of the NotOnOrAfter attribute is 70 minutes later than the value of the NotBefore attribute.
Audience
This contains a URI that identifies an intended audience. Azure AD sets the value of this element to the value of
Issuer element of the AuthnRequest that initiated the sign-on. To evaluate the Audience value, use the value of
the App ID URI that was specified during application registration.
<AudienceRestriction>
<Audience>https://www.contoso.com</Audience>
</AudienceRestriction>
Like the Issuer value, the Audience value must exactly match one of the service principal names that represents
the cloud service in Azure AD. However, if the value of the Issuer element is not a URI value, the Audience value
in the response is the Issuer value prefixed with spn: .
AttributeStatement
This contains claims about the subject or user. The following excerpt contains a sample AttributeStatement
element. The ellipsis indicates that the element can include multiple attributes and attribute values.
<AttributeStatement>
<Attribute Name="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name">
<AttributeValue>[email protected]</AttributeValue>
</Attribute>
<Attribute Name="http://schemas.microsoft.com/identity/claims/objectidentifier">
<AttributeValue>3F2504E0-4F89-11D3-9A0C-0305E82C3301</AttributeValue>
</Attribute>
...
</AttributeStatement>
Name Claim : The value of the Name attribute ( http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name ) is
the user principal name of the authenticated user, such as [email protected] .
ObjectIdentifier Claim : The value of the ObjectIdentifier attribute (
http://schemas.microsoft.com/identity/claims/objectidentifier ) is the ObjectId of the directory object that
represents the authenticated user in Azure AD.
identifier of the authenticated user.
ObjectId
is an immutable, globally unique, and re-use safe
AuthnStatement
This element asserts that the assertion subject was authenticated by a particular means at a particular time.
The
The
AuthnInstant
AuthnContext
attribute specifies the time at which the user authenticated with Azure AD.
element specifies the authentication context used to authenticate the user.
<AuthnStatement AuthnInstant="2013-03-18T07:33:56.000Z" SessionIndex="_bf9c623d-cc20-407a-9a59-c2d0aee84d12">
<AuthnContext>
<AuthnContextClassRef> urn:oasis:names:tc:SAML:2.0:ac:classes:Password</AuthnContextClassRef>
</AuthnContext>
</AuthnStatement>
Single Sign-Out SAML Protocol
2/8/2017 • 1 min to read • Edit Online
Azure Active Directory (Azure AD) supports the SAML 2.0 web browser single sign-out profile. For single sign-out
to work correctly, the LogoutURL for the application must be explicitly registered with Azure AD during application
registration. Azure AD uses the LogoutURL to redirect users after they are signed out.
This diagram shows the workflow of the Azure AD single sign-out process.
LogoutRequest
The cloud service sends a LogoutRequest message to Azure AD to indicate that a session has been terminated. The
following excerpt shows a sample LogoutRequest element.
<samlp:LogoutRequest xmlns="urn:oasis:names:tc:SAML:2.0:metadata" ID="idaa6ebe6839094fe4abc4ebd5281ec780"
Version="2.0" IssueInstant="2013-03-28T07:10:49.6004822Z" xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol">
<Issuer xmlns="urn:oasis:names:tc:SAML:2.0:assertion">https://www.workaad.com</Issuer>
<NameID xmlns="urn:oasis:names:tc:SAML:2.0:assertion"> Uz2Pqz1X7pxe4XLWxV9KJQ+n59d573SepSAkuYKSde8=</NameID>
</samlp:LogoutRequest>
LogoutRequest
The LogoutRequest element sent to Azure AD requires the following attributes:
: This identifies the sign-out request. The value of ID should not begin with a number. The typical practice
is to append id to the string representation of a GUID.
Version : Set the value of this element to 2.0. This value is required.
IssueInstant : This is a DateTime string with a Coordinate Universal Time (UTC) value and round-trip format
("o"). Azure AD expects a value of this type, but does not enforce it.
ID
Issuer
The Issuer element in a LogoutRequest must exactly match one of the ServicePrincipalNames in the cloud
service in Azure AD. Typically, this is set to the App ID URI that is specified during application registration.
NameID
The value of the
NameID
element must exactly match the
NameID
of the user that is being signed out.
LogoutResponse
Azure AD sends a
LogoutResponse .
LogoutResponse
in response to a
LogoutRequest
element. The following excerpt shows a sample
<samlp:LogoutResponse ID="_f0961a83-d071-4be5-a18c-9ae7b22987a4" Version="2.0" IssueInstant="2013-0318T08:49:24.405Z" InResponseTo="iddce91f96e56747b5ace6d2e2aa9d4f8c"
xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol">
<Issuer xmlns="urn:oasis:names:tc:SAML:2.0:assertion">https://sts.windows.net/82869000-6ad1-48f0-8171272ed18796e9/</Issuer>
<samlp:Status>
<samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success" />
</samlp:Status>
</samlp:LogoutResponse>
LogoutResponse
Azure AD sets the ID , Version and IssueInstant values in the LogoutResponse element. It also sets the
InResponseTo element to the value of the ID attribute of the LogoutRequest that elicited the response.
Issuer
Azure AD sets this value to
AD tenant.
To evaluate the value of the
registration.
https://login.microsoftonline.com/<TenantIdGUID>/
Issuer
where is the tenant ID of the Azure
element, use the value of the App ID URI provided during application
Status
Azure AD uses the StatusCode element in the Status element to indicate the success or failure of sign-out. When
the sign-out attempt fails, the StatusCode element can also contain custom error messages.
How to get an Azure Active Directory tenant
4/13/2017 • 3 min to read • Edit Online
In Azure Active Directory (Azure AD), a tenant is representative of an organization. It is a dedicated instance of
the Azure AD service that an organization receives and owns when it signs up for a Microsoft cloud service such
as Azure, Microsoft Intune, or Office 365. Each Azure AD tenant is distinct and separate from other Azure AD
tenants.
A tenant houses the users in a company and the information about them - their passwords, user profile data,
permissions, and so on. It also contains groups, applications, and other information pertaining to an
organization and its security.
To allow Azure AD users to sign in to your application, you must register your application in a tenant of your
own. Publishing an application in an Azure AD tenant is absolutely free. In fact, most developers will create
several tenants and applications for experimentation, development, staging and testing purposes. Organizations
that sign up for and consume your application can optionally choose to purchase licenses if they wish to take
advantage of advanced directory features.
So, how do you go about getting an Azure AD tenant? The process might be a little different if you:
Have an existing Office 365 subscription
Have an existing Azure subscription associated with a Microsoft Account
Have an existing Azure subscription associated with an organizational account
Have none of the above & want to start from scratch
Use an existing Office 365 subscription
If you have an existing Office 365 subscription, you already have an Azure AD tenant! You can sign in to the
Azure portal with your O365 account and start using Azure AD.
Use an MSA Azure subscription
If you have previously signed up for an Azure subscription with your individual Microsoft Account, you already
have a tenant! When you log in to the Azure Portal, you will automatically be logged in to your default tenant.
You are free to use this tenant as you see fit - but you may want to create an Organizational administrator
account.
To do so, follow these steps. Alternatively, you may wish to create a new tenant and create an administrator in
that tenant following a similar process.
1. Log into the Azure Portal with your individual account
2. Navigate to the “Azure Active Directory” section of the portal (found in the left nav bar, under More
Services)
3. You should automatically be signed in to the "Default Directory", if not you can switch directories by clicking
on your account name in the top right corner.
4. From the Quick Tasks section, choose Add a user.
5. In the Add User Form, provide the following details:
Name: (choose an appropriate value)
User name: (choose a user name for this administrator)
Profile: (fill in the appropriate values for First name, Last name, Job title and Department)
Role: Global Administrator
6. When you have completed the Add User Form, and receive the temporary password for the new
administrative user, be sure to record this password as you will need to login with this new user in order to
change the password. You can also send the password directly to the user, using an alternative e-mail.
7. Click on Create to create the new user.
8. To change the temporary password, log into https://login.microsoftonline.com with this new user account
and change the password when requested.
Use an organizational Azure subscription
If you have previously signed up for an Azure subscription with your organizational account, you already have a
tenant! In the Azure Portal, you should find a tenant when you navigate to "More Services" and "Azure Active
Directory." You are free to use this tenant as you see fit.
Start from scratch
If all of the above is gibberish to you, don't worry. Simply visit https://account.windowsazure.com/organization
to sign up for Azure with a new organization. Once you've completed the process, you will have your very own
Azure AD tenant with the domain name you chose during sign up. In the Azure Portal, you can find your tenant
by navigating to "Azure Active Directory" in the left hand nav.
As part of the process of signing up for Azure, you will be required to provide credit card details. You can
proceed with confidence - you will not be charged for publishing applications in Azure AD or creating new
tenants.
Branding Guidelines for Applications
4/27/2017 • 4 min to read • Edit Online
This topic discusses the branding guidelines you should use when developing applications with Azure Active
Directory (Azure AD). These guidelines will help direct your customers when they want to use their work or school
account, managed in Azure AD, or their personal account for sign-up and sign-in to your application.
Personal accounts vs. work or school accounts from Microsoft
Microsoft manages two kinds of user accounts:
Personal accounts (formerly known as Windows Live ID). These accounts represent the relationship between
individual users and Microsoft, and are used to access consumer devices and services from Microsoft. These
accounts are intended for personal use.
Work or school accounts. These accounts are managed by Microsoft on behalf of organizations that use
Azure Active Directory. These accounts are used to sign in to Office 365 and other business services from
Microsoft.
Microsoft work or school accounts are typically assigned to end users (employees, students, federal employees)
by their organizations (company, school, government agency). These accounts are either mastered directly in the
cloud, in the Azure AD platform, or synced to Azure AD from an on-premises directory, such as Windows Server
Active Directory. Microsoft is the custodian of the work or school accounts, but the accounts are owned and
controlled by the organization.
Referring to Azure AD accounts in your application
Microsoft doesn’t expose end-users to the Azure or the Active Directory brand names, and neither should you.
Once users are signed in, you should use the organization’s name and logo as much as possible. This is better
than using generic terms like “your organization”.
When users are not signed in, you should refer to their accounts as “Work or school accounts” and use the
Microsoft logo to convey that these accounts are managed by Microsoft. Don’t use terms like “enterprise
account”, “business account” or “corporate account” which create user confusion.
User account pictogram
In an earlier version of these guidelines, we recommended using a “blue badge” pictogram. Based on user and
developer feedback, we now recommend the use of the Microsoft logo instead. This will help users understand
that they can reuse the account they use with Office 365 or other Microsoft business services to sign in to your
app.
Signing up and signing in with Azure AD
Your app may present separate paths for sign-up and sign-in and the following sections provide visual guidance
for both scenarios.
If your app supports end user sign up (e.g. free to trial or freemium model): You can show a sign-in button
that allows users to access your app with their work account or their personal account. Azure AD will show a
consent prompt the first time they access your app.
If your app requires permissions that only admins can consent to, or if your app requires organizational
licensing: You should separate admin acquisition from user sign in. The “get this app” button will redirect
admins to sign in then ask them to grant consent on behalf of users in their organization. This has the added
benefit of suppressing end users consent prompts to your app.
Visual guidance for app acquisition
Your “get the app” link must redirect the user to the Azure AD grant access (authorize) page, to allow an
organization’s administrator to authorize your app to have access to their organization’s data that is hosted by
Microsoft. Details on how to request access are discussed in the Integrating Applications with Azure Active
Directory article.
After admins consent to your app, they can choose to add it to their users’ Office 365 app launcher experience
(accessible from the waffle and from https://portal.office.com/myapps). If you want to advertise this capability, you
can use terms like “Add this app to your organization” and show a button like this:
However, we recommend that you write explanatory text instead of relying on buttons. For example:
If you already use Office 365 or other business service from Microsoft, you can simply grant access to your
organization’s data. This will allow your users to access with their existing work accounts.
Visual guidance for sign-in
Your app should display a sign in button that redirects users to the sign-in endpoint that corresponds to the
protocol you use to integrate with Azure AD. The following section provides details on what that button should
look like.
Pictogram and “Sign in with Microsoft”
It’s the association of the Microsoft logo and the “Sign in with Microsoft” terms that uniquely represents Azure AD
amongst other identity providers your app may support. If you don’t have enough space for “Sign in with
Microsoft,” it’s ok to shorten it to “Sign in”.
You can also use a dark color scheme for the buttons.
Branding Do’s and Don’ts
DO use “work or school account” in combination with the "Sign in with Microsoft" button to provide additional
explanation to help end-users recognize whether they can use it. DON’T use other terms such as “enterprise
account”, “business account” or “corporate account.”
DON’T use “Office 365 ID” or “Azure ID”. Office 365 is also the name of a consumer offering from Microsoft
which doesn’t use Azure AD for authentication.
DON’T alter the Microsoft logo.
DON’T expose end-users to the Azure or Active Directory brands. It’s ok however to use these terms with
developers, IT pros and admins.
Navigation Do’s and Don’ts
DO provide a way for users to sign out and switch to another user account. While most people have a single
personal account from Microsoft/Facebook/Google/Twitter, people are often associated with more than one
organization. Support for multiple signed-in users is coming soon.
How to enable cross-app SSO on Android using
ADAL
4/25/2017 • 12 min to read • Edit Online
Providing Single Sign-On (SSO) so that users only need to enter their credentials once and have those credentials
automatically work across applications is now expected by customers. The difficulty in entering their username and
password on a small screen, often times combined with an additional factor (2FA) like a phone call or a texted code,
results in quick dissatisfaction if a user has to do this more than one time for your product.
In addition, if you apply an identity platform that other applications may use such as Microsoft Accounts or a work
account from Office365, customers expect that those credentials to be available to use across all their applications
no matter the vendor.
The Microsoft Identity platform, along with our Microsoft Identity SDKs, does all this hard work for you and gives
you the ability to delight your customers with SSO either within your own suite of applications or, as with our
broker capability and Authenticator applications, across the entire device.
This walkthrough will tell you how to configure our SDK within your application to provide this benefit to your
customers.
This walkthrough applies to:
Azure Active Directory
Azure Active Directory B2C
Azure Active Directory B2B
Azure Active Directory Conditional Access
The document preceding assumes you know how to provision applications in the legacy portal for Azure Active
Directory and integrated your application with the Microsoft Identity Android SDK.
SSO Concepts in the Microsoft Identity Platform
Microsoft Identity Brokers
Microsoft provides applications for every mobile platform that allow for the bridging of credentials across
applications from different vendors and allows for special enhanced features that require a single secure place
from where to validate credentials. We call these brokers. On iOS and Android these are provided through
downloadable applications that customers either install independently or can be pushed to the device by a
company who manages some or all of the device for their employee. These brokers support managing security just
for some applications or the entire device based on what IT Administrators desire. In Windows, this functionality is
provided by an account chooser built in to the operating system, known technically as the Web Authentication
Broker.
For more information on how we use these brokers and how your customers might see them in their login flow for
the Microsoft Identity platform read on.
Patterns for logging in on mobile devices
Access to credentials on devices follow two basic patterns for the Microsoft Identity platform:
Non-broker assisted logins
Broker assisted logins
Non-broker assisted logins
Non-broker assisted logins are login experiences that happen inline with the application and use the local storage
on the device for that application. This storage may be shared across applications but the credentials are tightly
bound to the app or suite of apps using that credential. You've most likely experienced this in many mobile
applications when you enter a username and password within the application itself.
These logins have the following benefits:
User experience exists entirely within the application.
Credentials can be shared across applications that are signed by the same certificate, providing a single sign-on
experience to your suite of applications.
Control around the experience of logging in is provided to the application before and after sign-in.
These logins have the following drawbacks:
User cannot experience single-sign on across all apps that use a Microsoft Identity, only across those Microsoft
Identities that your application has configured.
Your application cannot be used with more advanced business features such as Conditional Access or use the
InTune suite of products.
Your application can't support certificate-based authentication for business users.
Here is a representation of how the Microsoft Identity SDKs work with the shared storage of your applications to
enable SSO:
+------------+ +------------+ +-------------+
|
| |
| |
|
| App 1
| | App 2
| | App 3
|
|
| |
| |
|
|
| |
| |
|
+------------+ +------------+ +-------------+
| Azure SDK | | Azure SDK | | Azure SDK |
+------------+-+------------+--+-------------+
|
|
|
App Shared Storage
|
+--------------------------------------------+
Broker assisted logins
Broker-assisted logins are login experiences that occur within the broker application and use the storage and
security of the broker to share credentials across all applications on the device that apply the Microsoft Identity
platform. This means that your applications rely on the broker to sign users in. On iOS and Android these brokers
are provided through downloadable applications that customers either install independently or can be pushed to
the device by a company who manages the device for their user. An example of this type of application is the
Microsoft Authenticator application on iOS. In Windows this functionality is provided by an account chooser built in
to the operating system, known technically as the Web Authentication Broker. The experience varies by platform
and can sometimes be disruptive to users if not managed correctly. You're probably most familiar with this pattern
if you have the Facebook application installed and use Facebook Connect from another application. The Microsoft
Identity platform uses the same pattern.
For iOS this leads to a "transition" animation where your application is sent to the background while the Microsoft
Authenticator applications comes to the foreground for the user to select which account they would like to sign in
with.
For Android and Windows the account chooser is displayed on top of your application which is less disruptive to
the user.
How the broker gets invoked
If a compatible broker is installed on the device, like the Microsoft Authenticator application, the Microsoft Identity
SDKs will automatically do the work of invoking the broker for you when a user indicates they wish to log in using
any account from the Microsoft Identity platform. This account could be a personal Microsoft Account, a work or
school account, or an account that you provide and host in Azure using our B2C and B2B products.
How we ensure the application is valid
The need to ensure the identity of an application call the broker is crucial to the security we provide in broker
assisted logins. Neither iOS nor Android enforces unique identifiers that are valid only for a given application, so
malicious applications may "spoof" a legitimate application's identifier and receive the tokens meant for the
legitimate application. To ensure we are always communicating with the right application at runtime, we ask the
developer to provide a custom redirectURI when registering their application with Microsoft. How developers
should craft this redirect URI is discussed in detail below. This custom redirectURI contains the certificate
thumbprint of the application and is ensured to be unique to the application by the Google Play Store. When an
application calls the broker, the broker asks the Android operating system to provide it with the certificate
thumbprint that called the broker. The broker provides this certificate thumbprint to Microsoft in the call to our
identity system. If the certificate thumbprint of the application does not match the certificate thumbprint provided
to us by the developer during registration, we will deny access to the tokens for the resource the application is
requesting. This check ensures that only the application registered by the developer receives tokens.
The developer has the choice of if the Microsoft Identity SDK calls the broker or uses the non-broker
assisted flow. However if the developer chooses not to use the broker-assisted flow they lose the benefit of using
SSO credentials that the user may have already added on the device and prevents their application from being
used with business features Microsoft provides its customers such as Conditional Access, Intune Management
capabilities, and certificate-based authentication.
These logins have the following benefits:
User experiences SSO across all their applications no matter the vendor.
Your application can use more advanced business features such as Conditional Access or use the InTune suite of
products.
Your application can support certificate-based authentication for business users.
Much more secure sign-in experience as the identity of the application and the user are verified by the broker
application with additional security algorithms and encryption.
These logins have the following drawbacks:
In iOS the user is transitioned out of your application's experience while credentials are chosen.
Loss of the ability to manage the login experience for your customers within your application.
Here is a representation of how the Microsoft Identity SDKs work with the broker applications to enable SSO:
+------------+ +------------+ +-------------+
|
| |
| |
|
| App 1
| | App 2
| | Someone |
|
| |
| |
Else's |
|
| |
| |
App
|
+------------+ +------------+ +-------------+
| ADAL SDK | | ADAL SDK | | ADAL SDK |
+-----+------+-+-----+------+- +-------+-----+
|
|
|
|
+------v------+
|
|
|
|
|
|
| Microsoft |
|
+-------> Broker
|^----------+
| Application
|
|
+-------------+
|
|
| Broker
|
| Storage |
|
|
+-------------+
Armed with this background information you should be able to better understand and implement SSO within your
application using the Microsoft Identity platform and SDKs.
Enabling cross-app SSO using ADAL
Here we use the ADAL Android SDK to:
Turn on non-broker assisted SSO for your suite of apps
Turn on support for broker-assisted SSO
Turning on SSO for non-broker assisted SSO
For non-broker assisted SSO across applications the Microsoft Identity SDKs manage much of the complexity of
SSO for you. This includes finding the right user in the cache and maintaining a list of logged in users for you to
query.
To enable SSO across applications you own you need to do the following:
1. Ensure all your applications user the same Client ID or Application ID.
2. Ensure all your applications have the same SharedUserID set.
3. Ensure that all of your applications share the same signing certificate from the Google Play store so that you can
share storage.
Step 1: Using the same Client ID / Application ID for all the applications in your suite of apps
In order for the Microsoft Identity platform to know that it's allowed to share tokens across your applications, each
of your applications will need to share the same Client ID or Application ID. This is the unique identifier that was
provided to you when you registered your first application in the portal.
You may be wondering how you will identify different apps to the Microsoft Identity service if it uses the same
Application ID. The answer is with the Redirect URIs. Each application can have multiple Redirect URIs registered
in the onboarding portal. Each app in your suite will have a different redirect URI. An example of how this looks is
below:
App1 Redirect URI:
msauth://com.example.userapp/IcB5PxIyvbLkbFVtBI%2FitkW%2Fejk%3D
App2 Redirect URI:
msauth://com.example.userapp1/KmB7PxIytyLkbGHuI%2UitkW%2Fejk%4E
App3 Redirect URI:
msauth://com.example.userapp2/Pt85PxIyvbLkbKUtBI%2SitkW%2Fejk%9F
....
These are nested under the same client ID / application ID and looked up based on the redirect URI you return to us
in your SDK configuration.
+-------------------+
|
|
| Client ID
|
+---------+---------+
|
|
+-----------------------------------+
|
| App 1 Redirect URI
|
+----------^+
|
|
+-----------------------------------+
|
|
+-----------------------------------+
+----------^+ App 2 Redirect URI
|
|
|
|
|
+-----------------------------------+
|
+----------^+-----------------------------------+
| App 3 Redirect URI
|
|
|
+-----------------------------------+
Note that the format of these Redirect URIs are explained below. You may use any Redirect URI unless you wish to
support the broker, in which case they must look something like the above
Step 2: Configuring shared storage in Android
Setting the SharedUserID is beyond the scope of this document but can be learned by reading the Google Android
documentation on the Manifest. What is important is that you decide what you want your sharedUserID will be
called and use that across all your applications.
Once you have the
SharedUserID
in all your applications you are ready to use SSO.
WARNING
When you share storage across your applications any application can delete users, or worse delete all the tokens across your
application. This is particularly disastrous if you have applications that rely on the tokens to do background work. Sharing
storage means that you must be very careful in any and all remove operations through the Microsoft Identity SDKs.
That's it! The Microsoft Identity SDK will now share credentials across all your applications. The user list will also be
shared across application instances.
Turning on SSO for broker assisted SSO
The ability for an application to use any broker that is installed on the device is turned off by default. In order to
use your application with the broker you must do some additional configuration and add some code to your
application.
The steps to follow are:
1. Enable broker mode in your application code's call to the MS SDK
2. Establish a new redirect URI and provide that to both the app and your app registration
3. Setting up the correct permissions in the Android manifest
Step 1: Enable broker mode in your application
The ability for your application to use the broker is turned on when you create the "settings" or initial setup of your
Authentication instance. You do this by setting your ApplicationSettings type in your code:
AuthenticationSettings.Instance.setUseBroker(true);
Step 2: Establish a new redirect URI with your URL Scheme
In order to ensure that we always return the credential tokens to the correct application, we need to make sure we
call back to your application in a way that the Android operating system can verify. The Android operating system
uses the hash of the certificate in the Google Play store. This cannot be spoofed by a rogue application. Therefore,
we leverage this along with the URI of our broker application to ensure that the tokens are returned to the correct
application. We require you to establish this unique redirect URI both in your application and set as a Redirect URI
in our developer portal.
Your redirect URI must be in the proper form of:
msauth://packagename/Base64UrlencodedSignature
ex: msauth://com.example.userapp/IcB5PxIyvbLkbFVtBI%2FitkW%2Fejk%3D
This Redirect URI needs to be specified in your app registration using the Azure portal. For more information on
Azure AD app registration, see Integrating with Azure Active Directory.
Step 3: Set up the correct permissions in your application
Our broker application in Android uses the Accounts Manager feature of the Android OS to manage credentials
across applications. In order to use the broker in Android your app manifest must have permissions to use
AccountManager accounts. This is discussed in detail in the Google documentation for Account Manager here
In particular, these permissions are:
GET_ACCOUNTS
USE_CREDENTIALS
MANAGE_ACCOUNTS
You've configured SSO!
Now the Microsoft Identity SDK will automatically both share credentials across your applications and invoke the
broker if it's present on their device.
How to enable cross-app SSO on iOS using ADAL
4/25/2017 • 13 min to read • Edit Online
Providing Single Sign-On (SSO) so that users only need to enter their credentials once and have those credentials
automatically work across applications is now expected by customers. The difficulty in entering their username and
password on a small screen, often times combined with an additional factor (2FA) like a phone call or a texted code,
results in quick dissatisfaction if a user has to do this more than one time for your product.
In addition, if you apply an identity platform that other applications may use such as Microsoft Accounts or a work
account from Office365, customers expect that those credentials to be available to use across all their applications
no matter the vendor.
The Microsoft Identity platform, along with our Microsoft Identity SDKs, does all this hard work for you and gives
you the ability to delight your customers with SSO either within your own suite of applications or, as with our
broker capability and Authenticator applications, across the entire device.
This walkthrough will tell you how to configure our SDK within your application to provide this benefit to your
customers.
This walkthrough applies to:
Azure Active Directory
Azure Active Directory B2C
Azure Active Directory B2B
Azure Active Directory Conditional Access
The document preceding assumes you know how to provision applications in the legacy portal for Azure Active
Directory and integrated your application with the Microsoft Identity iOS SDK.
SSO Concepts in the Microsoft Identity Platform
Microsoft Identity Brokers
Microsoft provides applications for every mobile platform that allow for the bridging of credentials across
applications from different vendors and allows for special enhanced features that require a single secure place
from where to validate credentials. We call these brokers. On iOS and Android these brokers are provided through
downloadable applications that customers either install independently or can be pushed to the device by a
company who manages some or all of the device for their employee. These brokers support managing security just
for some applications or the entire device based on what IT Administrators desire. In Windows, this functionality is
provided by an account chooser built in to the operating system, known technically as the Web Authentication
Broker.
For more information on how we use these brokers and how your customers might see them in their login flow for
the Microsoft Identity platform read on.
Patterns for logging in on mobile devices
Access to credentials on devices follow two basic patterns for the Microsoft Identity platform:
Non-broker assisted logins
Broker assisted logins
Non-broker assisted logins
Non-broker assisted logins are login experiences that happen inline with the application and use the local storage
on the device for that application. This storage may be shared across applications but the credentials are tightly
bound to the app or suite of apps using that credential. You've most likely experienced this in many mobile
applications when you enter a username and password within the application itself.
These logins have the following benefits:
User experience exists entirely within the application.
Credentials can be shared across applications that are signed by the same certificate, providing a single sign-on
experience to your suite of applications.
Control around the experience of logging in is provided to the application before and after sign-in.
These logins have the following drawbacks:
User cannot experience single-sign on across all apps that use a Microsoft Identity, only across those Microsoft
Identities that your application has configured.
Your application cannot be used with more advanced business features such as Conditional Access or use the
InTune suite of products.
Your application can't support certificate-based authentication for business users.
Here is a representation of how the Microsoft Identity SDKs work with the shared storage of your applications to
enable SSO:
+------------+ +------------+ +-------------+
|
| |
| |
|
| App 1
| | App 2
| | App 3
|
|
| |
| |
|
|
| |
| |
|
+------------+ +------------+ +-------------+
| ADAL SDK | | ADAL SDK | | ADAK SDK |
+------------+-+------------+--+-------------+
|
|
|
App Shared Storage
|
+--------------------------------------------+
Broker assisted logins
Broker-assisted logins are login experiences that occur within the broker application and use the storage and
security of the broker to share credentials across all applications on the device that apply the Microsoft Identity
platform. This means that your applications rely on the broker to sign users in. On iOS and Android these brokers
are provided through downloadable applications that customers either install independently or can be pushed to
the device by a company who manages the device for their user. An example of this type of application is the
Microsoft Authenticator application on iOS. In Windows this functionality is provided by an account chooser built in
to the operating system, known technically as the Web Authentication Broker. The experience varies by platform
and can sometimes be disruptive to users if not managed correctly. You're probably most familiar with this pattern
if you have the Facebook application installed and use Facebook Connect from another application. The Microsoft
Identity platform uses the same pattern.
For iOS this leads to a "transition" animation where your application is sent to the background while the Microsoft
Authenticator applications comes to the foreground for the user to select which account they would like to sign in
with.
For Android and Windows the account chooser is displayed on top of your application which is less disruptive to
the user.
How the broker gets invoked
If a compatible broker is installed on the device, like the Microsoft Authenticator application, the Microsoft Identity
SDKs will automatically do the work of invoking the broker for you when a user indicates they wish to log in using
any account from the Microsoft Identity platform. This account could be a personal Microsoft Account, a work or
school account, or an account that you provide and host in Azure using our B2C and B2B products.
How we ensure the application is valid
The need to ensure the identity of an application call the broker is crucial to the security we provide in broker
assisted logins. Neither iOS nor Android enforces unique identifiers that are valid only for a given application, so
malicious applications may "spoof" a legitimate application's identifier and receive the tokens meant for the
legitimate application. To ensure we are always communicating with the right application at runtime, we ask the
developer to provide a custom redirectURI when registering their application with Microsoft. How developers
should craft this redirect URI is discussed in detail below. This custom redirectURI contains the Bundle ID of
the application and is ensured to be unique to the application by the Apple App Store. When an application calls the
broker, the broker asks the iOS operating system to provide it with the Bundle ID that called the broker. The broker
provides this Bundle ID to Microsoft in the call to our identity system. If the Bundle ID of the application does not
match the Bundle ID provided to us by the developer during registration, we will deny access to the tokens for the
resource the application is requesting. This check ensures that only the application registered by the developer
receives tokens.
The developer has the choice of if the Microsoft Identity SDK calls the broker or uses the non-broker
assisted flow. However if the developer chooses not to use the broker-assisted flow they lose the benefit of using
SSO credentials that the user may have already added on the device and prevents their application from being
used with business features Microsoft provides its customers such as Conditional Access, Intune Management
capabilities, and certificate-based authentication.
These logins have the following benefits:
User experiences SSO across all their applications no matter the vendor.
Your application can use more advanced business features such as Conditional Access or use the InTune suite of
products.
Your application can support certificate-based authentication for business users.
Much more secure sign-in experience as the identity of the application and the user are verified by the broker
application with additional security algorithms and encryption.
These logins have the following drawbacks:
In iOS the user is transitioned out of your application's experience while credentials are chosen.
Loss of the ability to manage the login experience for your customers within your application.
Here is a representation of how the Microsoft Identity SDKs work with the broker applications to enable SSO:
+------------+ +------------+ +-------------+
|
| |
| |
|
| App 1
| | App 2
| | Someone |
|
| |
| |
Else's |
|
| |
| |
App
|
+------------+ +------------+ +-------------+
| Azure SDK | | Azure SDK | | Azure SDK |
+-----+------+-+-----+------+- +-------+-----+
|
|
|
|
+------v------+
|
|
|
|
|
|
| Microsoft |
|
+-------> Broker
|^----------+
| Application
|
|
+-------------+
|
|
| Broker
|
| Storage |
|
|
+-------------+
Armed with this background information you should be able to better understand and implement SSO within your
application using the Microsoft Identity platform and SDKs.
Enabling cross-app SSO using ADAL
Here we use the ADAL iOS SDK to:
Turn on non-broker assisted SSO for your suite of apps
Turn on support for broker-assisted SSO
Turning on SSO for non-broker assisted SSO
For non-broker assisted SSO across applications the Microsoft Identity SDKs manage much of the complexity of
SSO for you. This includes finding the right user in the cache and maintaining a list of logged in users for you to
query.
To enable SSO across applications you own you need to do the following:
1. Ensure all your applications user the same Client ID or Application ID.
2. Ensure that all of your applications share the same signing certificate from Apple so that you can share
keychains
3. Request the same keychain entitlement for each of your applications.
4. Tell the Microsoft Identity SDKs about the shared keychain you want us to use.
Using the same Client ID / Application ID for all the applications in your suite of apps
In order for the Microsoft Identity platform to know that it's allowed to share tokens across your applications, each
of your applications will need to share the same Client ID or Application ID. This is the unique identifier that was
provided to you when you registered your first application in the portal.
You may be wondering how you will identify different apps to the Microsoft Identity service if it uses the same
Application ID. The answer is with the Redirect URIs. Each application can have multiple Redirect URIs registered
in the onboarding portal. Each app in your suite will have a different redirect URI. An example of how this looks is
below:
App1 Redirect URI:
x-msauth-mytestiosapp://com.myapp.mytestapp
App2 Redirect URI:
x-msauth-mytestiosapp://com.myapp.mytestapp2
App3 Redirect URI:
x-msauth-mytestiosapp://com.myapp.mytestapp3
....
These are nested under the same client ID / application ID and looked up based on the redirect URI you return to us
in your SDK configuration.
+-------------------+
|
|
| Client ID
|
+---------+---------+
|
|
+-----------------------------------+
|
| App 1 Redirect URI
|
+----------^+
|
|
+-----------------------------------+
|
|
+-----------------------------------+
+----------^+ App 2 Redirect URI
|
|
|
|
|
+-----------------------------------+
|
+----------^+-----------------------------------+
| App 3 Redirect URI
|
|
|
+-----------------------------------+
Note that the format of these Redirect URIs are explained below. You may use any Redirect URI unless you wish to
support the broker, in which case they must look something like the above
Create keychain sharing between applications
Enabling keychain sharing is beyond the scope of this document and covered by Apple in their document Adding
Capabilities. What is important is that you decide what you want your keychain to be called and add that capability
across all your applications.
When you do have entitlements set up correctly you should see a file in your project directory entitled
entitlements.plist that contains something that looks like the following:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>keychain-access-groups</key>
<array>
<string>$(AppIdentifierPrefix)com.myapp.mytestapp</string>
<string>$(AppIdentifierPrefix)com.myapp.mycache</string>
</array>
</dict>
</plist>
Once you have the keychain entitlement enabled in each of your applications, and you are ready to use SSO, tell
the Microsoft Identity SDK about your keychain by using the following setting in your ADAuthenticationSettings
with the following setting:
defaultKeychainSharingGroup=@"com.myapp.mycache";
WARNING
When you share a keychain across your applications any application can delete users or worse delete all the tokens across
your application. This is particularly disastrous if you have applications that rely on the tokens to do background work.
Sharing a keychain means that you must be very careful in any and all remove operations through the Microsoft Identity
SDKs.
That's it! The Microsoft Identity SDK will now share credentials across all your applications. The user list will also be
shared across application instances.
Turning on SSO for broker assisted SSO
The ability for an application to use any broker that is installed on the device is turned off by default. In order to
use your application with the broker you must do some additional configuration and add some code to your
application.
The steps to follow are:
1.
2.
3.
4.
Enable broker mode in your application code's call to the MS SDK.
Establish a new redirect URI and provide that to both the app and your app registration.
Registering a URL Scheme.
iOS9 Support: Add a permission to your info.plist file.
Step 1: Enable broker mode in your application
The ability for your application to use the broker is turned on when you create the "context" or initial setup of your
Authentication object. You do this by setting your credentials type in your code:
/*! See the ADCredentialsType enumeration definition for details */
@propertyADCredentialsType credentialsType;
The
AD_CREDENTIALS_AUTO
AD_CREDENTIALS_EMBEDDED
setting will allow the Microsoft Identity SDK to try to call out to the broker,
will prevent the Microsoft Identity SDK from calling to the broker.
Step 2: Registering a URL Scheme
The Microsoft Identity platform uses URLs to invoke the broker and then return control back to your application. To
finish that round trip you need a URL scheme registered for your application that the Microsoft Identity platform
will know about. This can be in addition to any other app schemes you may have previously registered with your
application.
WARNING
We recommend making the URL scheme fairly unique to minimize the chances of another app using the same URL scheme.
Apple does not enforce the uniqueness of URL schemes that are registered in the app store.
Below is an example of how this appears in your project configuration. You may also do this in XCode as well:
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleTypeRole</key>
<string>Editor</string>
<key>CFBundleURLName</key>
<string>com.myapp.mytestapp</string>
<key>CFBundleURLSchemes</key>
<array>
<string>x-msauth-mytestiosapp</string>
</array>
</dict>
</array>
Step 3: Establish a new redirect URI with your URL Scheme
In order to ensure that we always return the credential tokens to the correct application, we need to make sure we
call back to your application in a way that the iOS operating system can verify. The iOS operating system reports to
the Microsoft broker applications the Bundle ID of the application calling it. This cannot be spoofed by a rogue
application. Therefore, we leverage this along with the URI of our broker application to ensure that the tokens are
returned to the correct application. We require you to establish this unique redirect URI both in your application
and set as a Redirect URI in our developer portal.
Your redirect URI must be in the proper form of:
<app-scheme>://<your.bundle.id>
ex: x-msauth-mytestiosapp://com.myapp.mytestapp
This Redirect URI needs to be specified in your app registration using the Azure portal. For more information on
Azure AD app registration, see Integrating with Azure Active Directory.
St e p 3 a : A d d a r e d i r e c t U R I i n y o u r a p p a n d d e v p o r t a l t o su p p o r t c e r t i fi c a t e b a se d a u t h e n t i c a t i o n
To support cert based authentication a second "msauth" needs to be registered in your application and the Azure
portal to handle certificate authentication if you wish to add that support in your application.
msauth://code/<broker-redirect-uri-in-url-encoded-form>
ex: msauth://code/x-msauth-mytestiosapp%3A%2F%2Fcom.myapp.mytestapp
Step 4: iOS9: Add a configuration parameter to your app
ADAL uses –canOpenURL: to check if the broker is installed on the device. In iOS 9 Apple locked down what
schemes an application can query for. You will need to add “msauth” to the LSApplicationQueriesSchemes section
of your info.plist file .
LSApplicationQueriesSchemes msauth
You've configured SSO!
Now the Microsoft Identity SDK will automatically both share credentials across your applications and invoke the
broker if it's present on their device.
What is Azure AD B2B collaboration?
4/12/2017 • 3 min to read • Edit Online
Azure AD business-to-business (B2B) collaboration capabilities enable any organization using Azure AD to work
safely and securely with users from any other organization – small or large; with Azure AD or without; in fact, with
an IT organization or without.
Organizations using Azure AD can provide access to documents, resources, and applications to their partners, all
while maintaining complete control over corporate data. Developers can use the Azure AD business-to-business
APIs to write applications that bring two organizations together in a secure way that is also seamless and intuitive
for end users to navigate.
A whopping 97% of our customers have told us Azure AD B2B collaboration is very important to them.
As of early April, 2017, we had about 3 million users already using Azure AD B2B collaboration capabilities. And
more than 23% of Azure AD organizations that have more than 10 users are already benefiting from these
capabilities.
The key benefits of Azure AD B2B collaboration to your organization
Work with any user from any partner
Partners use their own credentials
No requirement for partners to use Azure AD
No external directories or complex set-up required
Simple and secure collaboration
Provide access to any corporate app or data, while applying sophisticated, Azure AD-powered authorization
policies
Seamless user experiences
Enterprise-grade security for apps and data
No management overhead
No external account or password management
No sync or manual account lifecycle management
No external administrative overhead
You can easily add B2B collaboration users to your organization
Admins can add B2B collaboration (guest) users in the Azure portal.
Enable your collaborators to bring their own identity
B2B collaborators can sign in with an identity of their choice. If the user doesn’t have an Microsoft account or and
Azure AD account – one is created for them seamlessly at the time for offer redemption.
Delegate to application and group owners
Application and group owners can add B2B users directly to any application that you care about, whether it is a
Microsoft application or not. Admins can delegate permission to add B2B users to non-admins. Non-admins can
use the Azure AD Application Access Panel to add B2B collaboration users to applications or groups.
Authorization policies protect your corporate content
Admins can establish conditional access policies, like Multi-factor Authentication, can be enforced at the tenant
level, the application level, or for specific users to protect corporate apps and data.
Use our APIs and sample code to easily build applications to onboard
Bring your external partners on board in ways customized to your organization’s needs.
Using the Azure AD B2B invitation APIs, organizations can deeply customize their onboarding experiences,
including creating self-service sign-up portals, sample code for which we provide on Github:
https://github.com/Azure/active-directory-dotnet-graphapi-b2bportal-web
With Azure AD B2B collaboration, you can get the full power of Azure AD to protect your partner relationships in a
way that end users find easy and intuitive. So go ahead, join the thousands of organizations that are already using
Azure AD B2B for their external collaboration!
Next steps
Administrator experiences are found in the Azure portal.
Information worker experiences are available in the Access Panel.
And, as always, connect with the product team for any feedback, discussions and suggestions through our
Microsoft Tech Community.
Browse our other articles on Azure AD B2B collaboration:
How do Azure Active Directory admins add B2B collaboration users?
How do information workers add B2B collaboration users?
The elements of the B2B collaboration invitation email
B2B collaboration invitation redemption
Azure AD B2B collaboration licensing
Troubleshooting Azure Active Directory B2B collaboration
Azure Active Directory B2B collaboration frequently asked questions (FAQ)
Azure Active Directory B2B collaboration API and customization
Multi-factor authentication for B2B collaboration users
Add B2B collaboration users without an invitation
B2B collaboration user auditing and reporting
Article Index for Application Management in Azure Active Directory
Using SCIM to enable automatic provisioning of users
and groups from Azure Active Directory to
applications
1/17/2017 • 21 min to read • Edit Online
Overview
Azure Active Directory can automatically provision users and groups to any application or identity store that is
fronted by a Web service with the interface defined in the SCIM 2.0 protocol specification. Azure Active Directory
can send requests to create, modify and delete assigned users and groups to this Web service, which can then
translate those requests into operations upon the target identity store.
Figure: Provisioning from Azure Active Directory to an identity store via a Web service
This capability can be used in conjunction with the “bring your own app” capability in Azure AD to enable single
sign-on and automatic user provisioning for applications that provide or are fronted by a SCIM web service.
There are two use cases for SCIM in Azure Active Directory:
Provisioning users and groups to applications that support SCIM - Applications that support SCIM 2.0 and
use OAuth bearer tokens for authentication will work with Azure AD of the box.
Build your own provisioning solution for applications that support other API-based provisioning - For
non-SCIM applications, you can create a SCIM endpoint to translate between Azure AD’s SCIM endpoint and
whatever API the application supports for user provisioning. To aid in the development of a SCIM endpoint, we
provide CLI libraries along with code samples that show you how to do provide a SCIM endpoint and translate
SCIM messages.
Provisioning Users and Groups To Applications That Support SCIM
Azure Active Directory can be configured to automatically provision assigned users and groups to applications that
implement a System for Cross-domain Identity Management 2 (SCIM) Web service and accept OAuth bearer
tokens for authentication. Within the SCIM 2.0 specification, applications must meet these requirements:
Supports creating users and/or groups, as per section 3.3 of the SCIM protocol.
Supports modifying users and/or groups with patch requests as per section 3.5.2 of the SCIM protocol.
Supports retrieving a known resource as per section 3.4.1 of the SCIM protocol.
Supports querying users and/or groups, as per section 3.4.2 of the SCIM protocol. By default, users are queried
by externalId and groups are queried by displayName.
Supports querying user by ID and by manager as per section 3.4.2 of the SCIM protocol.
Supports querying groups by ID and by member as per section 3.4.2 of the SCIM protocol.
Accepts OAuth bearer tokens for authorization as per section 2.1 of the SCIM protocol.
You should check with your application provider, or your application provider's documentation for statements of
compatibility with these requirements.
Getting Started
Applications that support the SCIM profile described above can be connected to Azure Active Directory using the
"custom" app feature in the Azure AD application gallery. Once connected, Azure AD runs a synchronization process
every 5 minutes where it queries the application's SCIM endpoint for assigned users and groups, and creates or
modifies them according to the assignment details.
To connect an application that supports SCIM:
1. In a web browser, launch the Azure management portal at https://manage.windowsazure.com.
2. Browse to Active Directory > Directory > [Your Directory] > Applications, and select Add > Add an
application from the gallery.
3. Select the Custom tab on the left, enter a name for your application, and click the checkmark icon to create an
app object.
1. In the resulting screen, select the second Configure account provisioning button.
2. In the Provisioning Endpoint URL field, enter the URL of the application's SCIM endpoint.
3. If the SCIM endpoint requires an OAuth bearer token from an issuer other than Azure AD, then copy the
required OAuth bearer token into the Authentication Token (optional) field. Is this field is left blank, then
Azure AD will include an OAuth bearer token issued from Azure AD with each request. Apps that use Azure AD
as an idenity provider can validate this Azure AD -issued token.
4. Click Next, and click on the Start Test button to have Azure Active Directory attempt to connect to the SCIM
endpoint. If the attempts fail, diagnostic information will be displayed.
5. If the attempts to connect to the application succeed, then click Next on the remaining screens, and click
Complete to exit the dialog.
6. In the resulting screen, select the third Assign Accounts button. In the resulting Users and Groups section,
assign the users or groups you want to provision to the application.
7. Once users and groups are assigned, click the Configure tab near the top of the screen.
8. Under Account Provisioning, confirm that the Status is set to On.
9. Under Tools, click Restart account provisioning to kick-start the provisioning process.
Note that 5-10 minutes may elapse before the provisioning process will begin to send requests to the SCIM
endpoint. A summary of connection attempts is provided on the application’s Dashboard tab, and both a report of
provisioning activity and any provisioning errors can be downloaded from the directory’s Reports tab.
Building Your Own Provisioning Solution For Any Application
By creating a SCIM web service that interfaces with Azure Active Directory, you can enable single sign-on and
automatic user provisioning for virtually any application that provides a REST or SOAP user provisioning API.
Here’s how it works:
1. Azure AD provides a common language infrastructure library named
Microsoft.SystemForCrossDomainIdentityManagement. System integrators and developers can use this library
to create and deploy a SCIM-based web service endpoint capable of connecting Azure AD to any application’s
identity store.
2. Mappings are implemented in the web service to map the standardized user schema to the user schema and
protocol required by the application.
3. The endpoint URL is registered in Azure AD as part of a custom application in the application gallery.
4. Users and groups are assigned to this application in Azure AD. Upon assignment, they are put into a queue to be
synchronized to the target application. The synchronization process handling the queue runs every 5 minutes.
Code Samples
To make this process easier, a set of code samples are provided that create a SCIM web service endpoint and
demonstrate automatic provisioning. One sample is of a provider that maintains a file with rows of commaseparated values representing users and groups. The other is of a provider that operates on the Amazon Web
Services Identity and Access Management service.
Prerequisites
Visual Studio 2013 or later
Azure SDK for .NET
Windows machine that supports the ASP.NET framework 4.5 to be used as the SCIM endpoint. This machine
must be accessible from the cloud
An Azure subscription with a trial or licensed version of Azure AD Premium
The Amazon AWS sample requires libraries from the AWS Toolkit for Visual Studio. See the README file
included with the sample for additional details
Getting Started
The easiest way to implement a SCIM endpoint that can accept provisioning requests from Azure AD is to build and
deploy the code sample that outputs the provisioned users to a comma-separated value (CSV) file.
To create a sample SCIM endpoint:
1. Download the code sample package at https://github.com/Azure/AzureAD-BYOA-ProvisioningSamples/tree/master
2. Unzip the package and place it on your Windows machine at a location such as C:\AzureAD-BYOA-Provisioning-
Samples.
3. In this folder, launch the FileProvisioningAgent solution in Visual Studio.
4. Select Tools > Library Package Manager > Package Manager Console, and execute the commands
below for the FileProvisioningAgent project to resolve the solution references:
Install-Package Microsoft.SystemForCrossDomainIdentityManagement Install-Package
Microsoft.IdentityModel.Clients.ActiveDirectory Install-Package Microsoft.Owin.Diagnostics Install-Package
Microsoft.Owin.Host.SystemWeb
5. Build the FileProvisioningAgent project.
6. Launch the Command Prompt application in Windows (as an Administrator), and use the cd command to
change the directory to your \AzureAD-BYOA-Provisioning-Samples\ProvisioningAgent\bin\Debug
folder.
7. Run the command below, replacing with the IP or domain name of the Windows Machine.
FileAgnt.exe http://:9000 TargetFile.csv
8. In Windows under Windows Settings > Network & Internet Settings, select the Windows Firewall >
Advanced Settings, and create an Inbound Rule that allows inbound access to port 9000.
9. If the Windows machine is behind a router, the router will need to be configured to perform Network Access
Translation between its port 9000 that is exposed to the internet, and port 9000 on the Windows machine. This
is required for Azure AD to be able to access this endpoint in the cloud.
To register the sample SCIM endpoint in Azure AD:
1. In a web browser, launch the Azure management portal at https://manage.windowsazure.com.
2. Browse to Active Directory > Directory > [Your Directory] > Applications, and select Add > Add an
application from the gallery.
3. Select the Custom tab on the left, enter a name such as “SCIM Test App”, and click the checkmark icon to create
an app object. Note that the application object created is intend to represent the target app you would be
provisioning to and implementing single sign-on for, and not just the SCIM endpoint.
1. In the resulting screen, select the second Configure account provisioning button.
2. In the dialog, enter the internet-exposed URL and port of your SCIM endpoint. This would be something like
http://testmachine.contoso.com:9000 or http://:9000/, where is the internet exposed IP address.
3. Click Next, and click on the Start Test button to have Azure Active Directory attempt to connect to the SCIM
endpoint. If the attempts fail, diagnostic information will be displayed.
4. If the attempts to connect to your Web service succeed, then click Next on the remaining screens, and click
Complete to exit the dialog.
5. In the resulting screen, select the third Assign Accounts button. In the resulting Users and Groups section,
assign the users or groups you want to provision to the application.
6. Once users and groups are assigned, click the Configure tab near the top of the screen.
7. Under Account Provisioning, confirm that the Status is set to On.
8. Under Tools, click Restart account provisioning to kick-start the provisioning process.
Note that 5-10 minutes may elapse before the provisioning process will begin to send requests to the SCIM
endpoint. A summary of connection attempts is provided on the application’s Dashboard tab, and both a report of
provisioning activity and any provisioning errors can be downloaded from the directory’s Reports tab.
The final step in verifying the sample is to open the TargetFile.csv file in the \AzureAD-BYOA-ProvisioningSamples\ProvisioningAgent\bin\Debug folder on your Windows machine. Once the provisioning process is run,
this file shows the details of all assigned and provisioned users and groups.
Development Libraries
To develop your own Web service that conforms to the SCIM specification, first familiarize yourself with the
following libraries provided by Microsoft to help accelerate the development process:
1: Common Language Infrastructure libraries are offered for use with languages based on that infrastructure, such
as C#. One of those libraries, Microsoft.SystemForCrossDomainIdentityManagement.Service, declares an interface,
Microsoft.SystemForCrossDomainIdentityManagement.IProvider, shown in the figure below. A developer using the
libraries would implement that interface with a class that may be referred to, generically, as a provider. The libraries
enable the developer to easily deploy a Web service that conforms to the SCIM specification, either hosted within
Internet Information Services, or any executable Common Language Infrastructure assembly. Requests to that Web
service will be translated into calls to the provider’s methods, which would be programmed by the developer to
operate on some identity store.
2: Express route handlers are available for parsing node.js request objects representing calls (as defined by the
SCIM specification), made to a node.js Web service.
Building a Custom SCIM Endpoint
Using the libraries described above, developers using those libraries can host their services within any executable
Common Language Infrastructure assembly, or within Internet Information Services. Here is sample code for
hosting a service within an executable assembly, at the address http://localhost:9000:
private static void Main(string[] arguments)
private static void Main(string[] arguments)
{
// Microsoft.SystemForCrossDomainIdentityManagement.IMonitor,
// Microsoft.SystemForCrossDomainIdentityManagement.IProvider and
// Microsoft.SystemForCrossDomainIdentityManagement.Service are all defined in
// Microsoft.SystemForCrossDomainIdentityManagement.Service.dll.
Microsoft.SystemForCrossDomainIdentityManagement.IMonitor monitor =
new DevelopersMonitor();
Microsoft.SystemForCrossDomainIdentityManagement.IProvider provider =
new DevelopersProvider(arguments[1]);
Microsoft.SystemForCrossDomainIdentityManagement.Service webService = null;
try
{
webService = new WebService(monitor, provider);
webService.Start("http://localhost:9000");
Console.ReadKey(true);
}
finally
{
if (webService != null)
{
webService.Dispose();
webService = null;
}
}
}
public class WebService : Microsoft.SystemForCrossDomainIdentityManagement.Service
{
private Microsoft.SystemForCrossDomainIdentityManagement.IMonitor monitor;
private Microsoft.SystemForCrossDomainIdentityManagement.IProvider provider;
public WebService(
Microsoft.SystemForCrossDomainIdentityManagement.IMonitor monitoringBehavior,
Microsoft.SystemForCrossDomainIdentityManagement.IProvider providerBehavior)
{
this.monitor = monitoringBehavior;
this.provider = providerBehavior;
}
public override IMonitor MonitoringBehavior
{
get
{
return this.monitor;
}
set
{
this.monitor = value;
}
}
public override IProvider ProviderBehavior
{
get
{
return this.provider;
}
set
{
this.provider = value;
}
}
}
It is important to note that this service must have an HTTP address and server authentication certificate of which the
root certification authority is one of the following:
CNNIC
Comodo
CyberTrust
DigiCert
GeoTrust
GlobalSign
Go Daddy
Verisign
WoSign
A server authentication certificate can be bound to a port on a Windows host using the network shell utility, like so:
netsh http add sslcert ipport=0.0.0.0:443 certhash=0000000000003ed9cd0c315bbb6dc1c08da5e6 appid={00112233-44556677-8899-AABBCCDDEEFF}
Here, the value provided for the certhash argument is the thumbprint of the certificate, while the value provided for
the appid argument is an arbitrary globally-unique identifier.
To host the service within Internet Information Services, a developer would build a Common Language
Infrastructure code library assembly with a class named Startup in the default namespace of the assembly. Here is a
sample of such a class:
public class Startup
{
// Microsoft.SystemForCrossDomainIdentityManagement.IWebApplicationStarter,
// Microsoft.SystemForCrossDomainIdentityManagement.IMonitor and
// Microsoft.SystemForCrossDomainIdentityManagement.Service are all defined in
// Microsoft.SystemForCrossDomainIdentityManagement.Service.dll.
Microsoft.SystemForCrossDomainIdentityManagement.IWebApplicationStarter starter;
public Startup()
{
Microsoft.SystemForCrossDomainIdentityManagement.IMonitor monitor =
new DevelopersMonitor();
Microsoft.SystemForCrossDomainIdentityManagement.IProvider provider =
new DevelopersProvider();
this.starter =
new Microsoft.SystemForCrossDomainIdentityManagement.WebApplicationStarter(
provider,
monitor);
}
public void Configuration(
Owin.IAppBuilder builder) // Defined in in Owin.dll.
{
this.starter.ConfigureApplication(builder);
}
}
Handling Endpoint Authentication
Requests from Azure Active Directory include an OAuth 2.0 bearer token. Any service receiving the request should
authenticate the issuer as being Azure Active Directory on behalf of the expected Azure Active Directory tenant, for
access to Azure Active Directory’s Graph Web service. In the token, the issuer is identified by an iss claim, like,
"iss":"https://sts.windows.net/cbb1a5ac-f33b-45fa-9bf5-f37db0fed422/". In this example, the base address of the
claim value, https://sts.windows.net, identifies Azure Active Directory as the issuer, while the relative address
segment, cbb1a5ac-f33b-45fa-9bf5-f37db0fed422, is a unique identifier of the Azure Active Directory tenant on
behalf of which the token was issued. If the token was issued for accessing the Azure Active Directory’s Graph Web
service, then the identifier of that service, 00000002-0000-0000-c000-000000000000, should be in the value of
the token’s aud claim.
Developers using the Common Language Infrastructure libraries provided by Microsoft for building a SCIM service
can authenticate requests from Azure Active Directory using the Microsoft.Owin.Security.ActiveDirectory package
by following these steps:
1: In a provider, implement the Microsoft.SystemForCrossDomainIdentityManagement.IProvider.StartupBehavior
property by having it return a method to be called whenever the service is started:
public override Action\<Owin.IAppBuilder, System.Web.Http.HttpConfiguration.HttpConfiguration\> StartupBehavior
{
get
{
return this.OnServiceStartup;
}
}
private void OnServiceStartup(
Owin.IAppBuilder applicationBuilder, // Defined in Owin.dll.
System.Web.Http.HttpConfiguration configuration) // Defined in System.Web.Http.dll.
{
}
2: Add the following code to that method to have any request to any of the service’s endpoints authenticated as
bearing a token issued by Azure Active Directory on behalf of a specified tenant, for access to Azure Active
Directory’s Graph Web service:
private void OnServiceStartup(
Owin.IAppBuilder applicationBuilder IAppBuilder applicationBuilder,
System.Web.Http.HttpConfiguration HttpConfiguration configuration)
{
// IFilter is defined in System.Web.Http.dll.
System.Web.Http.Filters.IFilter authorizationFilter =
new System.Web.Http.AuthorizeAttribute(); // Defined in
System.Web.Http.dll.configuration.Filters.Add(authorizationFilter);
// SystemIdentityModel.Tokens.TokenValidationParameters is defined in
// System.IdentityModel.Token.Jwt.dll.
SystemIdentityModel.Tokens.TokenValidationParameters tokenValidationParameters =
new TokenValidationParameters()
{
ValidAudience = "00000002-0000-0000-c000-000000000000"
};
// WindowsAzureActiveDirectoryBearerAuthenticationOptions is defined in
// Microsoft.Owin.Security.ActiveDirectory.dll
Microsoft.Owin.Security.ActiveDirectory.
WindowsAzureActiveDirectoryBearerAuthenticationOptions authenticationOptions =
new WindowsAzureActiveDirectoryBearerAuthenticationOptions()
{
TokenValidationParameters = tokenValidationParameters,
Tenant = "03F9FCBC-EA7B-46C2-8466-F81917F3C15E" // Substitute the appropriate tenant’s
// identifier for this one.
};
applicationBuilder.UseWindowsAzureActiveDirectoryBearerAuthentication(authenticationOptions);
}
User and Group Schema
Azure Active Directory can provision two types of resources to SCIM Web Services. Those types of resources are
users and groups.
User resources are identified by the schema identifier, urn:ietf:params:scim:schemas:extension:enterprise:2.0:User,
which is included in this protocol specification: http://tools.ietf.org/html/draft-ietf-scim-core-schema. The default
mapping of the attributes of users in Azure Active Directory to the attributes of
urn:ietf:params:scim:schemas:extension:enterprise:2.0:User resources is provided in table 1, below.
Group resources are identified by the schema identifier,
http://schemas.microsoft.com/2006/11/ResourceManagement/ADSCIM/Group. Table 2, below, shows the default
mapping of the attributes of groups in Azure Active Directory to the attributes of
http://schemas.microsoft.com/2006/11/ResourceManagement/ADSCIM/Group resources.
Table 1: Default user attribute mapping
AZURE ACTIVE DIRECTORY USER
URN:IETF:PARAMS:SCIM:SCHEMAS:EXTENSION:ENTERPRISE:2.0:USE
R
IsSoftDeleted
active
displayName
displayName
Facsimile-TelephoneNumber
phoneNumbers[type eq "fax"].value
givenName
name.givenName
jobTitle
title
mail
emails[type eq "work"].value
mailNickname
externalId
manager
manager
mobile
phoneNumbers[type eq "mobile"].value
objectId
id
postalCode
addresses[type eq "work"].postalCode
proxy-Addresses
emails[type eq "other"].Value
physical-Delivery-OfficeName
addresses[type eq "other"].Formatted
streetAddress
addresses[type eq "work"].streetAddress
surname
name.familyName
telephone-Number
phoneNumbers[type eq "work"].value
user-PrincipalName
userName
Table 2: Default group attribute mapping
AZURE ACTIVE DIRECTORY GROUP
HTTP://SCHEMAS.MICROSOFT.COM/2006/11/RESOURCEMANAGEM
ENT/ADSCIM/GROUP
displayName
externalId
mail
emails[type eq "work"].value
mailNickname
displayName
members
members
objectId
id
proxyAddresses
emails[type eq "other"].Value
User Provisioning and De-Provisioning
The figure below shows the messages that Azure Active Directory will send to a SCIM service to manage the
lifecycle of a user in another identity store. The diagram also shows how a SCIM service implemented using the
Common Language Infrastructure libraries provided by Microsoft for building such services will translate those
requests into calls to the methods of a provider.
Figure: User provisioning and de-provisioning sequence
1: Azure Active Directory will query the service for a user with an externalId attribute value matching the
mailNickname attribute value of a user in Azure Active Directory. The query will be expressed as a Hypertext
Transfer Protocol request like this one, wherein jyoung is a sample of a mailNickname of a user in Azure Active
Directory:
GET https://.../scim/Users?filter=externalId eq jyoung HTTP/1.1
Authorization: Bearer ...
If the service was built using the Common Language Infrastructure libraries provided by Microsoft for
implementing SCIM services, then the request will be translated into a call to the Query method of the service’s
provider. Here is the signature of that method:
//
//
//
//
//
System.Threading.Tasks.Tasks is defined in mscorlib.dll.
Microsoft.SystemForCrossDomainIdentityManagement.Resource is defined in
Microsoft.SystemForCrossDomainIdentityManagement.Schemas.
Microsoft.SystemForCrossDomainIdentityManagement.IQueryParameters is defined in
Microsoft.SystemForCrossDomainIdentityManagement.Protocol.
System.Threading.Tasks.Task<Microsoft.SystemForCrossDomainIdentityManagement.Resource[]> Query(
Microsoft.SystemForCrossDomainIdentityManagement.IQueryParameters parameters,
string correlationIdentifier);
Here is the definition of the Microsoft.SystemForCrossDomainIdentityManagement.IQueryParameters interface:
public interface IQueryParameters:
Microsoft.SystemForCrossDomainIdentityManagement.IRetrievalParameters
{
System.Collections.Generic.IReadOnlyCollection <Microsoft.SystemForCrossDomainIdentityManagement.IFilter>
AlternateFilters
{ get; }
}
public interface Microsoft.SystemForCrossDomainIdentityManagement.IRetrievalParameters
{
system.Collections.Generic.IReadOnlyCollection<string> ExcludedAttributePaths
{ get; }
System.Collections.Generic.IReadOnlyCollection<string> RequestedAttributePaths
{ get; }
string SchemaIdentifier
{ get; }
}
public interface Microsoft.SystemForCrossDomainIdentityManagement.IFilter
{
Microsoft.SystemForCrossDomainIdentityManagement.IFilter AdditionalFilter
{ get; set; }
string AttributePath
{ get; }
Microsoft.SystemForCrossDomainIdentityManagement.ComparisonOperator FilterOperator
{ get; }
string ComparisonValue
{ get; }
}
public enum Microsoft.SystemForCrossDomainIdentityManagement.ComparisonOperator
{
Equals
}
In the case of the foregoing sample of a query for a user with a given value for the externalId attribute, values of the
arguments passed to the Query method will be as follows:
parameters.AlternateFilters.Count: 1
parameters.AlternateFilters.ElementAt(0).AttributePath: "externalId"
parameters.AlternateFilters.ElementAt(0).ComparisonOperator: ComparisonOperator.Equals
parameters.AlternateFilter.ElementAt(0).ComparisonValue: "jyoung"
correlationIdentifier: System.Net.Http.HttpRequestMessage.GetOwinEnvironment["owin.RequestId"]
2: If the response to a query to the service for a user with an externalId attribute value matching the mailNickname
attribute value of a user in Azure Active Directory does not return any users, then Azure Active Directory will
request that the service provision a user corresponding to the one in Azure Active Directory. Here is an example of
such a request:
POST https://.../scim/Users HTTP/1.1
Authorization: Bearer ...
Content-type: application/json
{
"schemas":
[
"urn:ietf:params:scim:schemas:core:2.0:User",
"urn:ietf:params:scim:schemas:extension:enterprise:2.0User"],
"externalId":"jyoung",
"userName":"jyoung",
"active":true,
"addresses":null,
"displayName":"Joy Young",
"emails": [
{
"type":"work",
"value":"[email protected]",
"primary":true}],
"meta": {
"resourceType":"User"},
"name":{
"familyName":"Young",
"givenName":"Joy"},
"phoneNumbers":null,
"preferredLanguage":null,
"title":null,
"department":null,
"manager":null}
The Common Language Infrastructure libraries provided by Microsoft for implementing SCIM services would
translate that request into a call to the Create method of the service’s provider. The Create method has this
signature:
// System.Threading.Tasks.Tasks is defined in mscorlib.dll.
// Microsoft.SystemForCrossDomainIdentityManagement.Resource is defined in
// Microsoft.SystemForCrossDomainIdentityManagement.Schemas.
System.Threading.Tasks.Task<Microsoft.SystemForCrossDomainIdentityManagement.Resource> Create(
Microsoft.SystemForCrossDomainIdentityManagement.Resource resource,
string correlationIdentifier);
In the case of a request to provision a user, the value of the resource argument will be an instance of the
Microsoft.SystemForCrossDomainIdentityManagement. Core2EnterpriseUser class, defined in the
Microsoft.SystemForCrossDomainIdentityManagement.Schemas library. If the request to provision the user
succeeds, then the implementation of the method is expected to return an instance of the the
Microsoft.SystemForCrossDomainIdentityManagement. Core2EnterpriseUser class, with the value of the Identifier
property set to the unique identifier of the newly-provisioned user.
3: To update a user known to exist in an identity store fronted by an SCIM, Azure Active Directory will proceed by
requesting the current state of that user from the service with a request like this one:
GET ~/scim/Users/54D382A4-2050-4C03-94D1-E769F1D15682 HTTP/1.1
Authorization: Bearer ...
In a service built using the Common Language Infrastructure libraries provided by Microsoft for implementing
SCIM services, the request will be translated into a call to the Retrieve method of the service’s provider. Here is the
signature of the Retrieve method:
// System.Threading.Tasks.Tasks is defined in mscorlib.dll.
// Microsoft.SystemForCrossDomainIdentityManagement.Resource and
// Microsoft.SystemForCrossDomainIdentityManagement.IResourceRetrievalParameters
// are defined in Microsoft.SystemForCrossDomainIdentityManagement.Schemas.
System.Threading.Tasks.Task<Microsoft.SystemForCrossDomainIdentityManagement.Resource>
Retrieve(
Microsoft.SystemForCrossDomainIdentityManagement.IResourceRetrievalParameters
parameters,
string correlationIdentifier);
public interface
Microsoft.SystemForCrossDomainIdentityManagement.IResourceRetrievalParameters:
IRetrievalParameters
{
Microsoft.SystemForCrossDomainIdentityManagement.IResourceIdentifier
ResourceIdentifier
{ get; }
}
public interface Microsoft.SystemForCrossDomainIdentityManagement.IResourceIdentifier
{
string Identifier
{ get; set; }
string Microsoft.SystemForCrossDomainIdentityManagement.SchemaIdentifier
{ get; set; }
}
In the case of the foregoing example of a request to retrieve the current state of a user, the values of the properties
of the object provided as the value of the parameters argument will be as follows:
Identifier: "54D382A4-2050-4C03-94D1-E769F1D15682"
SchemaIdentifier: "urn:ietf:params:scim:schemas:extension:enterprise:2.0:User"
4: If a reference attribute is to be updated, then Azure Active Directory will query the service to determine whether
or not the current value of the reference attribute in the identity store fronted by the service already matches the
value of that attribute in Azure Active Directory. In the case of users, the only attribute of which the current value
will be queried in this way is the manager attribute. Here is an example of a request to determine whether the
manager attribute of a particular user object currently has a certain value:
GET ~/scim/Users?filter=id eq 54D382A4-2050-4C03-94D1-E769F1D15682 and manager eq 2819c223-7f76-453a-919d413861904646&attributes=id HTTP/1.1
Authorization: Bearer ...
The value of the attributes query parameter, id, signifies that if a user object exists that satisfies the expression
provided as the value of the filter query parameter, then the service is expected to respond with a
urn:ietf:params:scim:schemas:core:2.0:User or urn:ietf:params:scim:schemas:extension:enterprise:2.0:User resource,
including only the value of that resource’s id attribute. Of course, the value of the id attribute is known to the
requestor—it is included in the value of the filter query parameter; the purpose of asking for it is actually to request
a minimal representation of a resource that satisfying the filter expression as an indication of whether or not any
such object exists.
If the service was built using the Common Language Infrastructure libraries provided by Microsoft for
implementing SCIM services, then the request will be translated into a call to the Query method of the service’s
provider. The value of the properties of the object provided as the value of the parameters argument will be as
follows:
parameters.AlternateFilters.Count: 2
parameters.AlternateFilters.ElementAt(x).AttributePath: "id"
parameters.AlternateFilters.ElementAt(x).ComparisonOperator: ComparisonOperator.Equals
parameters.AlternateFilter.ElementAt(x).ComparisonValue: "54D382A4-2050-4C03-94D1-E769F1D15682"
parameters.AlternateFilters.ElementAt(y).AttributePath: "manager"
parameters.AlternateFilters.ElementAt(y).ComparisonOperator: ComparisonOperator.Equals
parameters.AlternateFilter.ElementAt(y).ComparisonValue: "2819c223-7f76-453a-919d-413861904646"
parameters.RequestedAttributePaths.ElementAt(0): "id"
parameters.SchemaIdentifier: "urn:ietf:params:scim:schemas:extension:enterprise:2.0:User"
Here, the value of the index x may be 0 and the value of the index y may be 1, or the value of x may be 1 and the
value of y may be 0, depending on the order of the expressions of the filter query parameter.
5: Here is an example of a request from Azure Active Directory to an SCIM service to update a user:
PATCH ~/scim/Users/54D382A4-2050-4C03-94D1-E769F1D15682 HTTP/1.1
Authorization: Bearer ...
Content-type: application/json
{
"schemas":
[
"urn:ietf:params:scim:api:messages:2.0:PatchOp"],
"Operations":
[
{
"op":"Add",
"path":"manager",
"value":
[
{
"$ref":"http://.../scim/Users/2819c223-7f76-453a-919d-413861904646",
"value":"2819c223-7f76-453a-919d-413861904646"}]}]}
The Microsoft Common Language Infrastructure libraries for implementing SCIM services would translate the
request into a call to the Update method of the service’s provider. Here is the signature of that method:
//
//
//
//
//
//
//
//
//
//
//
System.Threading.Tasks.Tasks and
System.Collections.Generic.IReadOnlyCollection<T>
are defined in mscorlib.dll.
Microsoft.SystemForCrossDomainIdentityManagement.IPatch,
Microsoft.SystemForCrossDomainIdentityManagement.PatchRequestBase,
Microsoft.SystemForCrossDomainIdentityManagement.IResourceIdentifier,
Microsoft.SystemForCrossDomainIdentityManagement.PatchOperation,
Microsoft.SystemForCrossDomainIdentityManagement.OperationName,
Microsoft.SystemForCrossDomainIdentityManagement.IPath and
Microsoft.SystemForCrossDomainIdentityManagement.OperationValue
are all defined in Microsoft.SystemForCrossDomainIdentityManagement.Protocol.
System.Threading.Tasks.Task Update(
Microsoft.SystemForCrossDomainIdentityManagement.IPatch patch,
string correlationIdentifier);
public interface Microsoft.SystemForCrossDomainIdentityManagement.IPatch
{
Microsoft.SystemForCrossDomainIdentityManagement.PatchRequestBase
PatchRequest
{ get; set; }
{ get; set; }
Microsoft.SystemForCrossDomainIdentityManagement.IResourceIdentifier
ResourceIdentifier
{ get; set; }
}
public class PatchRequest2:
Microsoft.SystemForCrossDomainIdentityManagement.PatchRequestBase
{
public System.Collections.Generic.IReadOnlyCollection
<Microsoft.SystemForCrossDomainIdentityManagement.PatchOperation>
Operations
{ get;}
public void AddOperation(
Microsoft.SystemForCrossDomainIdentityManagement.PatchOperation operation);
}
public class PatchOperation
{
public Microsoft.SystemForCrossDomainIdentityManagement.OperationName
Name
{ get; set; }
public Microsoft.SystemForCrossDomainIdentityManagement.IPath
Path
{ get; set; }
public System.Collections.Generic.IReadOnlyCollection
<Microsoft.SystemForCrossDomainIdentityManagement.OperationValue> Value
{ get; }
public void AddValue(
Microsoft.SystemForCrossDomainIdentityManagement.OperationValue value);
}
public enum OperationName
{
Add,
Remove,
Replace
}
public interface IPath
{
string AttributePath { get; }
System.Collections.Generic.IReadOnlyCollection<IFilter> SubAttributes { get; }
Microsoft.SystemForCrossDomainIdentityManagement.IPath ValuePath { get; }
}
public class OperationValue
{
public string Reference
{ get; set; }
public string Value
{ get; set; }
}
In the case of the foregoing example of a request to update a user, the object provided as the value of the patch
argument will have these property values:
ResourceIdentifier.Identifier: "54D382A4-2050-4C03-94D1-E769F1D15682"
ResourceIdentifier.SchemaIdentifier: "urn:ietf:params:scim:schemas:extension:enterprise:2.0:User"
(PatchRequest as PatchRequest2).Operations.Count: 1
(PatchRequest as PatchRequest2).Operations.ElementAt(0).OperationName: OperationName.Add
(PatchRequest as PatchRequest2).Operations.ElementAt(0).Path.AttributePath: "manager"
(PatchRequest as PatchRequest2).Operations.ElementAt(0).Value.Count: 1
(PatchRequest as PatchRequest2).Operations.ElementAt(0).Value.ElementAt(0).Reference:
http://.../scim/Users/2819c223-7f76-453a-919d-413861904646
(PatchRequest as PatchRequest2).Operations.ElementAt(0).Value.ElementAt(0).Value: 2819c223-7f76-453a919d-413861904646
6: To de-provision a user from an identity store fronted by an SCIM service, Azure Active Directory will send a
request like this one:
DELETE ~/scim/Users/54D382A4-2050-4C03-94D1-E769F1D15682 HTTP/1.1
Authorization: Bearer ...
If the service was built using the Common Language Infrastructure libraries provided by Microsoft for
implementing SCIM services, then the request will be translated into a call to the Delete method of the service’s
provider. That method has this signature:
// System.Threading.Tasks.Tasks is defined in mscorlib.dll.
// Microsoft.SystemForCrossDomainIdentityManagement.IResourceIdentifier,
// is defined in Microsoft.SystemForCrossDomainIdentityManagement.Protocol.
System.Threading.Tasks.Task Delete(
Microsoft.SystemForCrossDomainIdentityManagement.IResourceIdentifier
resourceIdentifier,
string correlationIdentifier);
The object provided as the value of the resourceIdentifier argument will have these property values in the case of
the foregoing example of a request to de-provision a user:
ResourceIdentifier.Identifier: "54D382A4-2050-4C03-94D1-E769F1D15682"
ResourceIdentifier.SchemaIdentifier: "urn:ietf:params:scim:schemas:extension:enterprise:2.0:User"
Group Provisioning and De-Provisioning
The figure below shows the messages that Azure Active Directory will send to a SCIM service to manage the
lifecycle of a group in another identity store. Those messages differ from the messages pertaining to users in three
ways:
The schema of a group resource will be identified as
http://schemas.microsoft.com/2006/11/ResourceManagement/ADSCIM/Group.
Requests to retrieve groups will stipulate that the members attribute is to be excluded from any resource
provided in response to the request.
Requests to determine whether a reference attribute has a certain value will be requests about the members
attribute.
Figure: Group provisioning and de-provisioning sequence
Related Articles
Article Index for Application Management in Azure Active Directory
Automate User Provisioning/Deprovisioning to SaaS Apps
Customizing Attribute Mappings for User Provisioning
Writing Expressions for Attribute Mappings
Scoping Filters for User Provisioning
Account Provisioning Notifications
List of Tutorials on How to Integrate SaaS Apps
Azure Active Directory Graph API
4/27/2017 • 4 min to read • Edit Online
IMPORTANT
We strongly recommend that you use Microsoft Graph instead of Azure AD Graph API to access Azure Active Directory
resources. Our development efforts are now concentrated on Microsoft Graph and no further enhancements are planned for
Azure AD Graph API. There are a very limited number of scenarios for which Azure AD Graph API might still be appropriate;
for more information, see the Microsoft Graph or the Azure AD Graph blog post in the Office Dev Center.
The Azure Active Directory Graph API provides programmatic access to Azure AD through REST API endpoints.
Applications can use the Graph API to perform create, read, update, and delete (CRUD) operations on directory data
and objects. For example, the Graph API supports the following common operations for a user object:
Create a new user in a directory
Get a user’s detailed properties, such as their groups
Update a user’s properties, such as their location and phone number, or change their password
Check a user’s group membership for role-based access
Disable a user’s account or delete it entirely
In addition to user objects, you can perform similar operations on other objects such as groups and applications. To
call the Graph API on a directory, the application must be registered with Azure AD and be configured to allow
access to the directory. This is normally achieved through a user or admin consent flow.
To begin using the Azure Active Directory Graph API, see the Graph API Quickstart Guide, or view the interactive
Graph API reference documentation.
Features
The Graph API provides the following features:
REST API Endpoints: The Graph API is a RESTful service comprised of endpoints that are accessed using
standard HTTP requests. The Graph API supports XML or Javascript Object Notation (JSON) content types for
requests and responses. For more information, see Azure AD Graph REST API Reference.
Authentication with Azure AD: Every request to the Graph API must be authenticated by appending a JSON
Web Token (JWT) in the Authorization header of the request. This token is acquired by making a request to
Azure AD’s token endpoint and providing valid credentials. You can use the OAuth 2.0 client credentials flow or
the authorization code grant flow to acquire a token to call the Graph. For more information, OAuth 2.0 in Azure
AD.
Role-Based Authorization (RBAC): Security groups are used to perform RBAC in the Graph API. For example,
if you want to determine whether a user has access to a specific resource, the application can call the Check
Group Membership (transitive) operation, which returns true or false.
Differential Query: If you want to check for changes in a directory between two time periods without having to
make frequent queries to the Graph API, you can make a differential query request. This type of request will
return only the changes made between the previous differential query request and the current request. For
more information, see Azure AD Graph API Differential Query.
Directory Extensions: If you are developing an application that needs to read or write unique properties for
directory objects, you can register and use extension values by using the Graph API. For example, if your
application requires a Skype ID property for each user, you can register the new property in the directory and it
will be available on every user object. For more information, see Azure AD Graph API Directory Schema
Extensions.
Secured by permission scopes: AAD Graph API exposes permission scopes that enable secure/consented
access to AAD data, and support a variety of client app types, including:
those with a user interface which are given delegated access to data via authorization from the signed-in
user (delegated)
those that use application-define role-based access control such as service/daemon clients (app roles)
Both delegated and app role permission scopes represent a privilege exposed by the Graph API and
can be requested by client applications through application registration permissions features in the
Azure portal. Clients can verify the permission scopes granted to them by inspecting the scope (“scp”)
claim received in the access token for delegated permissions and the roles (“roles”) claim for app role
permissions. Learn more about Azure AD Graph API Permission Scopes.
Scenarios
The Graph API enables many application scenarios. The following scenarios are the most common:
Line of Business (Single Tenant) Application: In this scenario, an enterprise developer works for an
organization that has an Office 365 subscription. The developer is building a web application that interacts with
Azure AD to perform tasks such assigning a license to a user. This task requires access to the Graph API, so the
developer registers the single tenant application in Azure AD and configures read and write permissions for the
Graph API. Then the application is configured to use either its own credentials or those of the currently sign-in
user to acquire a token to call the Graph API.
Software as a Service Application (Multi-Tenant): In this scenario, an independent software vendor (ISV) is
developing hosted multi-tenant web application that provides user management features for other
organizations that use Azure AD. These features require access to directory objects, and so the application needs
to call the Graph API. The developer registers the application in Azure AD, configures it to require read and write
permissions for the Graph API, and then enables external access so that other organizations can consent to use
the application in their directory. When a user in another organization authenticates to the application for the
first time, they are shown a consent dialog with the permissions the application is requesting. Granting consent
will then give the application those requested permissions to the Graph API in the user’s directory. For more
information on the consent framework, see Overview of the Consent Framework.
See Also
Azure AD Graph API Quickstart Guide
AD Graph REST documentation
Azure Active Directory developer's guide
Quickstart for the Azure AD Graph API
5/4/2017 • 6 min to read • Edit Online
The Azure Active Directory (AD) Graph API provides programmatic access to Azure AD through OData REST API
endpoints. Applications can use the Graph API to perform create, read, update, and delete (CRUD) operations on
directory data and objects. For example, you can use the Graph API to create a new user, view or update user’s
properties, change user’s password, check group membership for role-based access, disable, or delete the user. For
more information on the Graph API features and application scenarios, see Azure AD Graph API and Azure AD
Graph API Prerequisites.
IMPORTANT
We strongly recommend that you use Microsoft Graph instead of Azure AD Graph API to access Azure Active Directory
resources. Our development efforts are now concentrated on Microsoft Graph and no further enhancements are planned for
Azure AD Graph API. There are a very limited number of scenarios for which Azure AD Graph API might still be appropriate;
for more information, see the Microsoft Graph or the Azure AD Graph blog post in the Office Dev Center.
How to construct a Graph API URL
In Graph API, to access directory data and objects (in other words, resources or entities) against which you want to
perform CRUD operations, you can use URLs based on the Open Data (OData) Protocol. The URLs used in Graph
API consist of four main parts: service root, tenant identifier, resource path, and query string options:
https://graph.windows.net/{tenant-identifier}/{resource-path}?[query-parameters] . Take the example of the
following URL: https://graph.windows.net/contoso.com/groups?api-version=1.6 .
Service Root: In Azure AD Graph API, the service root is always https://graph.windows.net.
Tenant identifier: This section can be a verified (registered) domain name, in the preceding example,
contoso.com. It can also be a tenant object ID or the “myorganization” or “me” alias. For more information, see
Addressing Entities and Operations in the Graph API).
Resource path: This section of a URL identifies the resource to be interacted with (users, groups, a particular
user, or a particular group, etc.) In the example above, it is the top level “groups” to address that resource set.
You can also address a specific entity, for example “users/{objectId}” or “users/userPrincipalName”.
Query parameters: A question mark (?) separates the resource path section from the query parameters
section. The “api-version” query parameter is required on all requests in the Graph API. The Graph API also
supports the following OData query options: $filter, $orderby, $expand, $top, and $format. The following
query options are not currently supported: $count, $inlinecount, and $skip. For more information, see
Supported Queries, Filters, and Paging Options in Azure AD Graph API.
Graph API versions
You specify the version for a Graph API request in the “api-version” query parameter. For version 1.5 and later, you
use a numerical version value; api-version=1.6. For earlier versions, you use a date string that adheres to the
format YYYY-MM-DD; for example, api-version=2013-11-08. For preview features, use the string “beta”; for
example, api-version=beta. For more information about differences between Graph API versions, see Azure AD
Graph API Versioning.
Graph API metadata
To return the Graph API metadata file, add the “$metadata” segment after the tenant-identifier in the URL For
example, the following URL returns metadata for a demo company:
. You can enter this URL in the
address bar of a web browser to see the metadata. The CSDL metadata document returned describes the entities
and complex types, their properties, and the functions and actions exposed by the version of Graph API you
requested. Omitting the api-version parameter returns metadata for the most recent version.
https://graph.windows.net/GraphDir1.OnMicrosoft.com/$metadata?api-version=1.6
Common queries
Azure AD Graph API Common Queries lists common queries that can be used with the Azure AD Graph, including
queries that can be used to access top-level resources in your directory and queries to perform operations in your
directory.
For example, https://graph.windows.net/contoso.com/tenantDetails?api-version=1.6 returns company information
for directory contoso.com.
Or
https://graph.windows.net/contoso.com/users?api-version=1.6
lists all user objects in the directory contoso.com.
Using the Graph Explorer
You can use the Graph Explorer for the Azure AD Graph API to query the directory data as you build your
application.
The following is the output you would see if you were to navigate to the Graph Explorer, sign in, and enter
https://graph.windows.net/GraphDir1.OnMicrosoft.com/users?api-version=1.6 to display all the users in the signed-in
user's directory:
Load the Graph Explorer: To load the tool, navigate to https://graphexplorer.azurewebsites.net/. Click Login and
sign-in with your Azure AD account credentials to run the Graph Explorer against your tenant. If you run Graph
Explorer against your own tenant, either you or your administrator needs to consent during sign-in. If you have an
Office 365 subscription, you automatically have an Azure AD tenant. The credentials you use to sign in to Office
365 are, in fact, Azure AD accounts, and you can use these credentials with Graph Explorer.
Run a query: To run a query, type your query in the request text box and click GET or click the enter key. The
results are displayed in the response box. For example,
https://graph.windows.net/myorganization/groups?api-version=1.6 lists all group objects in the signed-in user's
directory.
Note the following features and limitations of the Graph Explorer:
Autocomplete capability on resource sets. To see this functionality, click on the request text box (where the
company URL appears). You can select a resource set from the dropdown list.
Supports the “me” and “myorganization” addressing aliases. For example, you can use
https://graph.windows.net/me?api-version=1.6 to return the user object of the signed-in user or
https://graph.windows.net/myorganization/users?api-version=1.6 to return all users in the current directory.
A response headers section. This section can be used to help troubleshoot issues that occur when running
queries.
A JSON viewer for the response with expand and collapse capabilities.
No support for displaying a thumbnail photo.
Using Fiddler to write to the directory
For the purposes of this Quickstart guide, you can use the Fiddler Web Debugger to practice performing ‘write’
operations against your Azure AD directory. For more information and to install Fiddler, see
http://www.telerik.com/fiddler.
In the example below, you use Fiddler Web Debugger to create a new security group ‘MyTestGroup’ in your Azure
AD directory.
Obtain an access token: To access Azure AD Graph, clients are required to successfully authenticate to Azure AD
first. For more information, see Authentication Scenarios for Azure AD.
Compose and run a query: Complete the following steps:
1. Open Fiddler Web Debugger and switch to the Composer tab.
2. Since you want to create a new security group, select Post as the HTTP method from the pull-down menu. For
more information about operations and permissions on a group object, see Group within the Azure AD Graph
REST API Reference.
3. In the field next to Post, type in the following as the request URL:
https://graph.windows.net/mytenantdomain/groups?api-version=1.6 .
NOTE
You must substitute mytenantdomain with the domain name of your own Azure AD directory.
4. In the field directly below Post pull-down, type the following:
Host: graph.windows.net
Authorization: Bearer <your access token>
Content-Type: application/json
NOTE
Substitute your <your access token> with the access token for your Azure AD directory.
5. In the Request body field, type the following:
{
"displayName":"MyTestGroup",
"mailNickname":"MyTestGroup",
"mailEnabled":"false",
"securityEnabled": true
}
For more information about creating groups, see Create Group.
For more information on Azure AD entities and types that are exposed by Graph and information about the
operations that can be performed on them with Graph, see Azure AD Graph REST API Reference.
Next steps
Learn more about the Azure AD Graph API
Learn more about Azure AD Graph API Permission Scopes
How to get AppSource Certified for Azure Active
Directory (AD)
5/3/2017 • 1 min to read • Edit Online
To receive AppSource certification for Azure AD, your application must implement the multi-tenant sign in pattern
with Azure AD using the OpenID Connect or OAuth 2.0 protocols.
If you’re not familiar with Azure AD sign-in or multi-tenant application development:
1. Start by reading about the Browser to Web App scenarios in Authentication Scenarios for Azure AD.
2. Next, check out the Azure AD web application quick-start guides, which demonstrate how to implement
sign-in, and include companion code samples.
TIP
Try the preview of our new developer portal that will help you get up and running with Azure Active Directory in just
a few minutes! The developer portal will walk you through the process of registering an app and integrating Azure AD
into your code. When you’re finished, you will have a simple application that can authenticate users in your tenant
and a back-end that can accept tokens and perform validation.
3. To learn how to implement the multi-tenant sign-in pattern with Azure AD, check out How to sign in any Azure
Active Directory (AD) user using the multi-tenant application pattern
Related content
For more information on building applications that support Azure AD sign-in, or to get help and support, refer to
the Azure AD Developer's Guide.
Please use the Disqus comments section following this article to provide feedback and help us refine and shape our
content.
Listing your application in the Azure Active Directory
application gallery
4/27/2017 • 2 min to read • Edit Online
To list an application that supports single sign-on with Azure Active Directory in the Azure AD gallery, the
application first needs to implement one of the following integration modes:
OpenID Connect - Direct integration with Azure AD using OpenID Connect for authentication and the Azure AD
consent API for configuration. If you are just starting an integration and your application does not support
SAML, then this is the recommend mode.
SAML – Your application already has the ability to configure third-party identity providers using the SAML
protocol.
Listing requirements for each mode are below.
OpenID Connect Integration
To integrate your application with Azure AD, following the developer instructions. Then complete the questions
below and send to [email protected].
Provide credentials for a test tenant or account with your application that can be used by the Azure AD team to
test the integration.
Provide instructions on how the Azure AD team can sign in and connect an instance of Azure AD to your
application using the Azure AD consent framework.
Provide any further instructions required for the Azure AD team to test single sign-on with your application.
Provide the info below:
Company Name:
Company Website:
Application Name:
Application Description (256 character limit):
Application Website (informational):
Application Technical Support Website or Contact Info:
Application ID of the application, as shown in the application details at https://portal.azure.com:
Application Sign-Up URL where customers go to sign up for and /or purchase the application:
Choose up to three categories for your application to be listed under (for available categories see the Azure
Active Directory Marketplace):
Attach Application Small Icon (PNG file, 45px by 45px, solid background color):
Attach Application Large Icon (PNG file, 215px by 215px, solid background color):
Attach Application Logo (PNG file, 150px by 122px, transparent background color):
SAML Integration
Any app that supports SAML 2.0 can be integrated directly with an Azure AD tenant using these instructions to add
a custom application. Once you have tested that your application integration works with Azure AD, send the
following information to [email protected].
Provide credentials for a test tenant or account with your application that can be used by the Azure AD team to
test the integration.
Provide the SAML Sign-On URL, Issuer URL (entity ID), and Reply URL (assertion consumer service) values for
your application, as described here. If you typically provide these values as part of a SAML metadata file, then
please send that as well.
Provide a brief description of how to configure Azure AD as an identity provider in your application using SAML
2.0. If your application supports configuring Azure AD as an identity provider through a self-service
administrative portal, then please ensure the credentials provided above include the ability to set this up.
Provide the info below:
Company Name:
Company Website:
Application Name:
Application Description (256 character limit):
Application Website (informational):
Application Technical Support Website or Contact Info:
Application Sign-Up URL where customers go to sign up for and /or purchase the application:
Choose up to three categories for your application to be listed under (for available categories see the Azure
Active Directory Marketplace)):
Attach Application Small Icon (PNG file, 45px by 45px, solid background color):
Attach Application Large Icon (PNG file, 215px by 215px, solid background color):
Attach Application Logo (PNG file, 150px by 122px, transparent background color):
Getting Started with Azure Active Directory and
Visual Studio connected services (MVC Projects)
3/20/2017 • 1 min to read • Edit Online
Requiring authentication to access controllers
All controllers in your project were adorned with the Authorize attribute. This attribute requires the user to be
authenticated before accessing these controllers. To allow the controller to be accessed anonymously, remove this
attribute from the controller. If you want to set the permissions at a more granular level, apply the attribute to each
method that requires authorization instead of applying it to the controller class.
Adding SignIn / SignOut Controls
To add the SignIn/SignOut controls to your view, you can use the _LoginPartial.cshtml partial view to add the
functionality to one of your views. Here is an example of the functionality added to the standard _Layout.cshtml
view. (Note the last element in the div with class navbar-collapse):
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>@ViewBag.Title - My ASP.NET Application</title>
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" datatarget=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
@Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new {
@class = "navbar-brand" })
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>@Html.ActionLink("Home", "Index", "Home")</li>
<li>@Html.ActionLink("About", "About", "Home")</li>
<li>@Html.ActionLink("Contact", "Contact", "Home")</li>
</ul>
@Html.Partial("_LoginPartial")
</div>
</div>
</div>
<div class="container body-content">
@RenderBody()
<hr />
<footer>
<p>&copy; @DateTime.Now.Year - My ASP.NET Application</p>
</footer>
</div>
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
@RenderSection("scripts", required: false)
</body>
</html>
Next steps
Learn more about Azure Active Directory
Diagnosing errors with the Azure Active Directory
Connection Wizard
3/20/2017 • 2 min to read • Edit Online
While detecting previous authentication code, the wizard detected an incompatible authentication type.
What is being checked?
Note: To correctly detect previous authentication code in a project, the project must be built. If you encountered
this error and you don't have a previous authentication code in your project, rebuild and try again.
Project Types
The wizard checks the type of project you’re developing so it can inject the right authentication logic into the
project. If there is any controller that derives from ApiController in the project, the project is considered a WebAPI
project. If there are only controllers that derive from MVC.Controller in the project, the project is considered an
MVC project. Anything else is not supported by the wizard.
Compatible Authentication Code
The wizard also checks for authentication settings that have been previously configured with the wizard or are
compatible with the wizard. If all settings are present, it is considered a re-entrant case, and the wizard opens
display the settings. If only some of the settings are present, it is considered an error case.
In an MVC project, the wizard checks for any of the following settings, which result from previous use of the wizard:
<add
<add
<add
<add
key="ida:ClientId" value="" />
key="ida:Tenant" value="" />
key="ida:AADInstance" value="" />
key="ida:PostLogoutRedirectUri" value="" />
In addition, the wizard checks for any of the following settings in a Web API project, which result from previous use
of the wizard:
<add key="ida:ClientId" value="" />
<add key="ida:Tenant" value="" />
<add key="ida:Audience" value="" />
Incompatible Authentication Code
Finally, the wizard attempts to detect versions of authentication code that have been configured with previous
versions of Visual Studio. If you received this error, it means your project contains an incompatible authentication
type. The wizard detects the following types of authentication from previous versions of Visual Studio:
Windows Authentication
Individual User Accounts
Organizational Accounts
To detect Windows Authentication in an MVC project, the wizard looks for the
web.config file.
authentication
element from your
<configuration>
<system.web>
<authentication mode="Windows" />
</system.web>
</configuration>
To detect Windows Authentication in a Web API project, the wizard looks for the
element from your project's .csproj file:
IISExpressWindowsAuthentication
<Project>
<PropertyGroup>
<IISExpressWindowsAuthentication>enabled</IISExpressWindowsAuthentication>
</PropertyGroup>
</Project>
To detect Individual User Accounts authentication, the wizard looks for the package element from your
Packages.config file.
<packages>
<package id="Microsoft.AspNet.Identity.EntityFramework" version="2.1.0"
targetFramework="net45" />
</packages>
To detect an old form of Organizational Account authentication, the wizard looks for the following element from
web.config:
<configuration>
<appSettings>
<add key="ida:Realm" value="***" />
</appSettings>
</configuration>
To change the authentication type, remove the incompatible authentication type and run the wizard again.
For more information, see Authentication Scenarios for Azure AD.
Next steps
Authentication Scenarios for Azure AD
Get Started with Azure Active Directory and Visual
Studio connected services (WebApi projects)
3/20/2017 • 1 min to read • Edit Online
Requiring authentication to access controllers
All controllers in your project were adorned with the Authorize attribute. This attribute requires the user to be
authenticated before accessing the APIs defined by these controllers. To allow the controller to be accessed
anonymously, remove this attribute from the controller. If you want to set the permissions at a more granular level,
apply the attribute to each method that requires authorization instead of applying it to the controller class.
Next steps
Learn more about Azure Active Directory
What happened to my WebApi project (Visual Studio
Azure Active Directory connected service)
3/20/2017 • 1 min to read • Edit Online
References have been added
NuGet package references
Microsoft.Owin
Microsoft.Owin.Host.SystemWeb
Microsoft.Owin.Security
Microsoft.Owin.Security.ActiveDirectory
Microsoft.Owin.Security.Jwt
Microsoft.Owin.Security.OAuth
Owin
System.IdentityModel.Tokens.Jwt
.NET references
Microsoft.Owin
Microsoft.Owin.Host.SystemWeb
Microsoft.Owin.Security
Microsoft.Owin.Security.ActiveDirectory
Microsoft.Owin.Security.Jwt
Microsoft.Owin.Security.OAuth
Owin
System.IdentityModel.Tokens.Jwt
Code changes
Code files were added to your project
An authentication startup class, App_Start/Startup.Auth.cs was added to your project containing startup logic for
Azure AD authentication.
Startup code was added to your project
If you already had a Startup class in your project, the Configuration method was updated to include a call to
ConfigureAuth(app) . Otherwise, a Startup class was added to your project.
Your app.config or web.config file has new configuration values.
The following configuration entries have been added.
<appSettings>
<add key="ida:ClientId" value="ClientId from the new Azure AD App" />
<add key="ida:Tenant" value="Your selected Azure AD Tenant" />
<add key="ida:Audience" value="The App ID Uri from the wizard" />
</appSettings>`
An Azure AD App was created
An Azure AD Application was created in the directory that you selected in the wizard.
Learn more about Azure Active Directory
If I checked disable Individual User Accounts authentication, what
additional changes were made to my project?
NuGet package references were removed, and files were removed and backed up. Depending on the state of your
project, you may have to manually remove additional references or files, or modify code as appropriate.
NuGet package references removed (for those present)
Microsoft.AspNet.Identity.Core
Microsoft.AspNet.Identity.EntityFramework
Microsoft.AspNet.Identity.Owin
Code files backed up and removed (for those present)
Each of following files was backed up and removed from the project. Backup files are located in a 'Backup' folder at
the root of the project's directory.
App_Start\IdentityConfig.cs
Controllers\AccountController.cs
Controllers\ManageController.cs
Models\IdentityModels.cs
Providers\ApplicationOAuthProvider.cs
Code files backed up (for those present)
Each of following files was backed up before being replaced. Backup files are located in a 'Backup' folder at the root
of the project's directory.
Startup.cs
App_Start\Startup.Auth.cs
If I checked Read directory data, what additional changes were made to
my project?
Additional changes were made to your app.config or web.config
The following additional configuration entries have been added.
<appSettings>
<add key="ida:Password" value="Your Azure AD App's new password" />
</appSettings>`
Your Azure Active Directory App was updated
Your Azure Active Directory App was updated to include the Read directory data permission and an additional key
was created which was then used as the ida:Password in the web.config file.
Next steps
Learn more about Azure Active Directory
Azure Active Directory Authentication Libraries
4/27/2017 • 3 min to read • Edit Online
The Azure AD authentication Library (ADAL) enables client application developers to easily authenticate users
to cloud or on-premises Active Directory (AD), and then obtain access tokens for securing API calls. ADAL has
many features that make authentication easier for developers, such as asynchronous support, a configurable
token cache that stores access tokens and refresh tokens, automatic token refresh when an access token
expires and a refresh token is available, and more. By handling most of the complexity, ADAL can help a
developer focus on business logic in their application and easily secure resources without being an expert on
security.
ADAL is available on a variety of platforms.
Client Libraries
PLATFORM
LIBRARY
DOWNLOAD
SOURCE CODE
SAMPLE
REFERENCE
.NET Client,
Windows Store,
UWP, Xamarin
iOS and Android
ADAL .NET v3
NuGet
GitHub
Desktop App
Reference
.NET Client,
Windows Store,
Windows Phone
8.1
ADAL .NET v2
NuGet
GitHub
Desktop App
Reference
JavaScript
ADAL.js
GitHub
GitHub
Single Page App
iOS, macOS
ADAL
CocoaPods
GitHub
iOS App
Reference
Android
ADAL
The Central
Repository
GitHub
Android App
JavaDocs
Node.js
ADAL
npm
GitHub
Java
ADAL4J
GitHub
GitHub
Java Web App
PLATFORM
LIBRARY
DOWNLOAD
SOURCE CODE
SAMPLE
.NET
OWIN for
AzureAD
NuGet
CodePlex
MVC App
.NET
OWIN for
OpenIDConnect
NuGet
CodePlex
Web App
Node.js
Azure AD
Passport
npm
GitHub
Web API
Server Libraries
REFERENCE
PLATFORM
LIBRARY
DOWNLOAD
SOURCE CODE
SAMPLE
.NET
OWIN for WSFederation
NuGet
CodePlex
MVC Web App
.NET
Identity Protocol
Extensions for
.NET 4.5
NuGet
GitHub
.NET
JWT Handler for
.NET 4.5
NuGet
GitHub
REFERENCE
Scenarios
Here are three common scenarios in which ADAL can be used for authentication.
Authenticating Users of a Client Application to a Remote Resource
In this scenario, a developer has a client, such as a WPF application, that needs to access a remote resource
secured by Azure AD, such as a web API. He has an Azure subscription, knows how to invoke the downstream
web API, and knows the Azure AD tenant that the web API uses. As a result, he can use ADAL to facilitate
authentication with Azure AD, either by fully delegating the authentication experience to ADAL or by explicitly
handling user credentials. ADAL makes it easy to authenticate the user, obtain an access token and refresh
token from Azure AD, and then use the access token to make requests to the web API.
For a code sample that demonstrates this scenario using authentication to Azure AD, see Native Client WPF
Application to Web API.
Authenticating a Server Application to a Remote Resource
In this scenario, a developer has an application running on a server that needs to access a remote resource
secured by Azure AD, such as a web API. He has an Azure subscription, knows how to invoke the downstream
service, and knows the Azure AD tenant the web API uses. As a result, he can use ADAL to facilitate
authentication with Azure AD by explicitly handling the application’s credentials. ADAL makes it easy to
retrieve a token from Azure AD by using the application’s client credential and then use that token to make
requests to the web API. ADAL also handles managing the lifetime of the access token by caching it and
renewing it as necessary. For a code sample that demonstrates this scenario, see Console Application to Web
API.
Authenticating a Server Application on Behalf of a User to Access a Remote Resource
In this scenario, a developer has an application running on a server that needs to access a remote resource
secured by Azure AD, such as a web API. The request also needs to be made on behalf of a user in Azure AD.
He has an Azure subscription, knows how to invoke the downstream web API, and knows the Azure AD tenant
the service uses. Once the user is authenticated to the web application, the application can get an authorization
code for the user from Azure AD. The web application can then use ADAL to obtain an access token and
refresh token on behalf of a user using the authorization code and client credentials associated with the
application from Azure AD. Once the web application is in possession of the access token, it can call the web
API until the token expires. When the token expires, the web application can use ADAL to get a new access
token by using the refresh token that was previously received.
See Also
The Azure Active Directory developer's guide
Authentication scenarios for Azure Active directory
Azure Active Directory code samples
Azure Active Directory Code Samples
2/13/2017 • 6 min to read • Edit Online
NOTE
This article is part of the Azure Active Directory developer's guide.
You can use Microsoft Azure Active Directory (Azure AD) to add authentication and authorization to your web
applications and web APIs. This section links you to samples that show you how it's done and code snippets
that you can use in your applications. On the code sample page, 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.
To understand the basic scenario for each sample type, see Authentication Scenarios for Azure AD.
Contribute to our samples on GitHub: Microsoft Azure Active Directory Samples and Documentation.
Web Browser to Web Application
These samples show how to write a web application that directs the user’s browser to sign them in to Azure
AD.
LANGUAGE/PLATFORM
SAMPLE
DESCRIPTION
C#/.NET
WebApp-OpenIDConnect-DotNet
Use OpenID Connect (ASP.Net
OpenID Connect OWIN middleware)
to authenticate users from an Azure
AD tenant.
C#/.NET
WebApp-MultiTenantOpenIdConnect-DotNet
A multi-tenant .NET MVC web
application that uses OpenID Connect
(ASP.Net OpenID Connect OWIN
middleware) to authenticate users
from multiple Azure AD tenants.
C#/.NET
WebApp-WSFederation-DotNet
Use WS-Federation (ASP.Net WSFederation OWIN middleware) to
authenticate users from an Azure AD
tenant.
Single Page Application (SPA)
This sample shows how to write a single page application secured with Azure AD.
LANGUAGE/PLATFORM
SAMPLE
DESCRIPTION
JavaScript, C#/.NET
SinglePageApp-DotNet
Use ADAL for JavaScript and Azure AD
to secure an AngularJS-based single
page app implemented with an
ASP.NET web API back end.
Native Application to Web API
These code samples show how to build native client applications that call web APIs that are secured by Azure
AD. They use Azure AD Authentication Library (ADAL) and OAuth 2.0 in Azure AD.
LANGUAGE/PLATFORM
SAMPLE
DESCRIPTION
Javascript
NativeClient-MultiTarget-Cordova
Use the ADAL plugin for Apache
Cordova to build an Apache Cordova
app that calls a web API and uses
Azure AD for authentication.
C#/.NET
NativeClient-DotNet
A .NET WPF application that calls a
web API that is secured by using
Azure AD.
C#/.NET
NativeClient-WindowsStore
A Windows Store application that calls
a web API that is secured with Azure
AD.
C#/.NET
NativeClient-WebAPI-MultiTenantWindowsStore
A Windows Store application calling a
multi-tenant web API that is secured
with Azure AD.
C#/.NET
WebAPI-OnBehalfOf-DotNet
A native client application that calls a
web API, which gets a token to act on
behalf of the original user, and then
uses the token to call another web
API.
C#/.NET
NativeClient-WindowsPhone8.1
A Windows Store application for
Windows Phone 8.1 that calls a web
API that is secured by Azure AD.
ObjC
NativeClient-iOS
An iOS application that calls a web API
that requires Azure AD for
authentication.
C#/.NET
WebAPI-ManuallyValidateJwt-DotNet
A native client application that
includes logic to process a JWT token
in a web API, instead of using OWIN
middleware.
C#/Xamarin
NativeClient-Xamarin-Android
A Xamarin binding to the native Azure
AD Authentication Library (ADAL) for
the Android library.
C#/Xamarin
NativeClient-Xamarin-iOS
A Xamarin binding to the native Azure
AD Authentication Library (ADAL) for
iOS.
C#/Xamarin
NativeClient-MultiTarget-DotNet
A Xamarin project that targets five
platforms and calls a web API that is
secured by Azure AD.
LANGUAGE/PLATFORM
SAMPLE
DESCRIPTION
C#/.NET
NativeClient-Headless-DotNet
A native application that performs
non-interactive authentication and
calls a web API that is secured by
Azure AD.
Web Application to Web API
These code samples show how use OAuth 2.0 in Azure AD to build web applications that call web APIs that are
secured by Azure AD.
LANGUAGE/PLATFORM
SAMPLE
DESCRIPTION
C#/.NET
WebApp-WebAPI-OpenIDConnectDotNet
Call a web API with the signed-in
user's permissions.
C#/.NET
WebApp-WebAPI-OAuth2AppIdentity-DotNet
Call a web API with the application's
permissions.
C#/.NET
WebApp-WebAPI-OAuth2UserIdentity-Dotnet
Add authorization with OAuth 2.0 in
Azure AD to an existing web
application so it can call a web API.
JavaScript
WebAPI-Nodejs
Set up a REST API service that's
integrated with Azure AD for API
protection. Includes a Node.js server
with a Web API.
C#/.NET
WebApp-WebAPI-MultiTenantOpenIdConnect-DotNet
A multi-tenant MVC web application
that uses OpenID Connect (ASP.Net
OpenID Connect OWIN middleware)
to authenticate users from an Azure
AD tenant. Uses an authorization code
to invoke the Graph API.
Server or Daemon Application to Web API
These code samples show how to build a daemon or server application that gets resources from a web API by
using Azure AD Authentication Library (ADAL) and OAuth 2.0 in Azure AD.
LANGUAGE/PLATFORM
SAMPLE
DESCRIPTION
C#/.NET
Daemon-DotNet
A console application calls a web API.
The client credential is a password.
C#/.NET
Daemon-CertificateCredential-DotNet
A console application that calls a web
API. The client credential is a
certificate.
Calling Azure AD Graph API
These code sample show how to build applications that call the Azure AD Graph API to read and write directory
data.
LANGUAGE/PLATFORM
SAMPLE
DESCRIPTION
Java
WebApp-GraphAPI-Java
A web application that uses the Graph
API to access Azure AD directory data.
PHP
WebApp-GraphAPI-PHP
A web application that uses the Graph
API to access Azure AD directory data.
C#/.NET
WebApp-GraphAPI-DotNet
A web application that uses the Graph
API to access Azure AD directory data.
C#/.NET
ConsoleApp-GraphAPI-DotNet
This console app demonstrates
common Read and Write calls to the
Graph API, and shows how to execute
user license assignment and update a
user's thumbnail photo and links.
C#/.NET
ConsoleApp-GraphAPI-DiffQueryDotNet
A console application that uses the
differential query in the Graph API to
get periodic changes to user objects in
an Azure AD tenant.
C#/.NET
WebApp-GraphAPIDirectoryExtensions-DotNet
An MVC application uses Graph API
queries to generate a simple company
organizational chart.
PHP
WebApp-GraphAPIDirectoryExtensions-PHP
A PHP application that calls the Graph
API to register an extension and then
read, update, and delete values in the
extension attribute.
Authorization
These code samples show how to use Azure AD for authorization.
LANGUAGE/PLATFORM
SAMPLE
DESCRIPTION
C#/.NET
WebApp-GroupClaims-DotNet
Perform role based access control
(RBAC) using Azure Active Directory
group claims in an application that is
integrated with Azure AD.
C#/.NET
WebApp-RoleClaims-DotNet
Perform role based access control
(RBAC) using Azure Active Directory
application roles in an application that
is integrated with Azure AD.
Legacy Walkthroughs
These walkthroughs use slightly older technology, but still might be of interest.
LANGUAGE/PLATFORM
SAMPLE
DESCRIPTION
LANGUAGE/PLATFORM
SAMPLE
DESCRIPTION
C#/.NET
Role-Based and ACL-Based
Authorization in a Microsoft Azure AD
Application
Perform role-based authorization
(RBAC) and ACL-based authorization
in an application that is integrated
with Azure AD.
C#/.NET
AAL - Windows Store app to REST
service - Authentication
Use Azure AD Authentication Library
(ADAL) (formerly AAL) for Windows
Store Beta to add user authentication
capabilities to a Windows Store app.
C#/.NET
ADAL - Native App to REST service Authentication with AAD via Browser
Dialog
Use Azure AD Authentication Library
(ADAL) to add user authentication
capabilities to a WPF client.
C#/.NET
ADAL - Native App to REST service Authentication with ACS via Browser
Dialog
Use Azure AD Authentication Library
(ADAL) and Access Control Service 2.0
(ACS) to add user authentication
capabilities to a WPF client.
C#/.NET
ADAL - Server to Server
Authentication
Use Azure AD Authentication Library
(ADAL) to secure service calls from a
server side process to an MVC4 Web
API REST service.
C#/.NET
Adding Sign-On to Your Web
Application Using Azure AD
Configure a .NET application to
perform web single sign-on against
your Azure AD enterprise directory.
C#/.NET
Developing Multi-Tenant Web
Applications with Azure AD
Use Azure AD to add to the single
sign-on and directory access
capabilities of one .NET application to
work across multiple organizations.
JAVA
Java Sample App for Azure AD Graph
API
Use the Graph API to access directory
data from Azure AD.
PHP
PHP Sample App for Azure AD Graph
API
Use the Graph API to access directory
data from Azure AD.
C#/.NET
Sample App for Azure AD Graph API
Use the Graph API to access directory
data from Azure AD.
C#/.NET
Sample App for Azure AD Graph
Differential Query
Use the differential query in the Graph
API to get periodic changes to user
objects in an Azure AD tenant.
C#/.NET
Sample App for Integrating MultiTenant Cloud Application for Azure
AD
Integrate a multi-tenant application
into Azure AD.
C#/.NET
Securing a Windows Store Application
and REST Web Service Using Azure AD
Create a simple web API resource and
a Windows Store client application
using Azure AD and the Azure AD
Authentication Library (ADAL).
LANGUAGE/PLATFORM
SAMPLE
DESCRIPTION
C#/.NET
Using the Graph API to Query Azure
AD
Configure a Microsoft .NET application
to use the Azure AD Graph API to
access data from an Azure AD tenant
directory.
See also
O t h e r R e so u r c e s
Azure Active Directory Developer's Guide
Azure AD Graph API Conceptual and Reference
Azure AD Graph API Helper Library
Azure Active Directory developer glossary
3/21/2017 • 13 min to read • Edit Online
This article contains definitions for some of the core Azure Active Directory (AD) developer concepts, which are
helpful when learning about application development for Azure AD.
access token
A type of security token issued by an authorization server, and used by a client application in order to access a
protected resource server. Typically in the form of a JSON Web Token (JWT), the token embodies the authorization
granted to the client by the resource owner, for a requested level of access. The token contains all applicable claims
about the subject, enabling the client application to use it as a form of credential when accessing a given resource.
This also eliminates the need for the resource owner to expose credentials to the client.
Access tokens are sometimes referred to as "User+App" or "App-Only", depending on the credentials being
represented. For example, when a client application uses the:
"Authorization code" authorization grant, the end user authenticates first as the resource owner, delegating
authorization to the client to access the resource. The client authenticates afterward when obtaining the access
token. The token can sometimes be referred to more specifically as a "User+App" token, as it represents both
the user that authorized the client application, and the application.
"Client credentials" authorization grant, the client provides the sole authentication, functioning without the
resource-owner's authentication/authorization, so the token can sometimes be referred to as an "App-Only"
token.
See Azure AD Token Reference for more details.
application manifest
A feature provided by the Azure portal, which produces a JSON representation of the application's identity
configuration, used as a mechanism for updating its associated Application and ServicePrincipal entities. See
Understanding the Azure Active Directory application manifest for more details.
application object
When you register/update an application in the Azure portal, the portal creates/updates both an application object
and a corresponding service principal object for that tenant. The application object defines the application's identity
configuration globally (across all tenants where it has access), providing a template from which its corresponding
service principal object(s) are derived for use locally at run-time (in a specific tenant).
See Application and Service Principal Objects for more information.
application registration
In order to allow an application to integrate with and delegate Identity and Access Management functions to Azure
AD, it must be registered with an Azure AD tenant. When you register your application with Azure AD, you are
providing an identity configuration for your application, allowing it to integrate with Azure AD and use features
such as:
Robust management of Single Sign-On using Azure AD Identity Management and OpenID Connect protocol
implementation
Brokered access to protected resources by client applications, via Azure AD's OAuth 2.0 authorization server
implementation
Consent framework for managing client access to protected resources, based on resource owner authorization.
See Integrating applications with Azure Active Directory for more details.
authentication
The act of challenging a party for legitimate credentials, providing the basis for creation of a security principal to
be used for identity and access control. During an OAuth2 authorization grant for example, the party
authenticating is filling the role of either resource owner or client application, depending on the grant used.
authorization
The act of granting an authenticated security principal permission to do something. There are two primary use
cases in the Azure AD programming model:
During an OAuth2 authorization grant flow: when the resource owner grants authorization to the client
application, allowing the client to access the resource owner's resources.
During resource access by the client: as implemented by the resource server, using the claim values present in
the access token to make access control decisions based upon them.
authorization code
A short lived "token" provided to a client application by the authorization endpoint, as part of the "authorization
code" flow, one of the four OAuth2 authorization grants. The code is returned to the client application in response
to authentication of a resource owner, indicating the resource owner has delegated authorization to access the
requested resources. As part of the flow, the code is later redeemed for an access token.
authorization endpoint
One of the endpoints implemented by the authorization server, used to interact with the resource owner in order
to provide an authorization grant during an OAuth2 authorization grant flow. Depending on the authorization
grant flow used, the actual grant provided can vary, including an authorization code or security token.
See the OAuth2 specification's authorization grant types and authorization endpoint sections, and the
OpenIDConnect specification for more details.
authorization grant
A credential representing the resource owner's authorization to access its protected resources, granted to a client
application. A client application can use one of the four grant types defined by the OAuth2 Authorization
Framework to obtain a grant, depending on client type/requirements: "authorization code grant", "client
credentials grant", "implicit grant", and "resource owner password credentials grant". The credential returned to
the client is either an access token, or an authorization code (exchanged later for an access token), depending on
the type of authorization grant used.
authorization server
As defined by the OAuth2 Authorization Framework, the server responsible for issuing access tokens to the client
after successfully authenticating the resource owner and obtaining its authorization. A client application interacts
with the authorization server at runtime via its authorization and token endpoints, in accordance with the OAuth2
defined authorization grants.
In the case of Azure AD application integration, Azure AD implements the authorization server role for Azure AD
applications and Microsoft service APIs, for example Microsoft Graph APIs.
claim
A security token contains claims, which provide assertions about one entity (such as a client application or
resource owner) to another entity (such as the resource server). Claims are name/value pairs that relay facts about
the token subject (for example, the security principal that was authenticated by the authorization server). The
claims present in a given token are dependent upon several variables, including the type of token, the type of
credential used to authenticate the subject, the application configuration, etc.
See Azure AD token reference for more details.
client application
As defined by the OAuth2 Authorization Framework, an application that makes protected resource requests on
behalf of the resource owner. The term "client" does not imply any particular hardware implementation
characteristics (for instance, whether the application executes on a server, a desktop, or other devices).
A client application requests authorization from a resource owner to participate in an OAuth2 authorization grant
flow, and may access APIs/data on the resource owner's behalf. The OAuth2 Authorization Framework defines two
types of clients, "confidential" and "public", based on the client's ability to maintain the confidentiality of its
credentials. Applications can implement a web client (confidential) which runs on a web server, a native client
(public) installed on a device, or a user-agent-based client (public) which runs in a device's browser.
consent
The process of a resource owner granting authorization to a client application, to access protected resources under
specific permissions, on behalf of the resource owner. Depending on the permissions requested by the client, an
administrator or user will be asked for consent to allow access to their organization/individual data respectively.
Note, in a multi-tenant scenario, the application's service principal is also recorded in the tenant of the consenting
user.
ID token
An OpenID Connect security token provided by an authorization server's authorization endpoint, which contains
claims pertaining to the authentication of an end user resource owner. Like an access token, ID tokens are also
represented as a digitally signed JSON Web Token (JWT). Unlike an access token though, an ID token's claims are
not used for purposes related to resource access and specifically access control.
See Azure AD token reference for more details.
multi-tenant application
A class of application that enables sign in and consent by users provisioned in any Azure AD tenant, including
tenants other than the one where the client is registered. Native client applications are multi-tenant by default,
whereas web client and web resource/API applications have the ability to select between single or multi-tenant. By
contrast, a web application registered as single-tenant, would only allow sign-ins from user accounts provisioned
in the same tenant as the one where the application is registered.
See How to sign in any Azure AD user using the multi-tenant application pattern for more details.
native client
A type of client application that is installed natively on a device. Since all code is executed on a device, it is
considered a "public" client due to its inability to store credentials privately/confidentially. See OAuth2 client types
and profiles for more details.
permissions
A client application gains access to a resource server by declaring permission requests. Two types are available:
"Delegated" permissions, which specify scope-based access using delegated authorization from the signed-in
resource owner, are presented to the resource at run-time as "scp" claims in the client's access token.
"Application" permissions, which specify role-based access using the client application's credentials/identity, are
presented to the resource at run-time as "roles" claims in the client's access token.
They also surface during the consent process, giving the administrator or resource owner the opportunity to
grant/deny the client access to resources in their tenant.
Permission requests are configured on the "Applications" / "Settings" tab in the Azure portal, under "Required
Permissions", by selecting the desired "Delegated Permissions" and "Application Permissions" (the latter requires
membership in the Global Admin role). Because a public client can't securely maintain credentials, it can only
request delegated permissions, while a confidential client has the ability to request both delegated and application
permissions. The client's application object stores the declared permissions in its requiredResourceAccess
property.
resource owner
As defined by the OAuth2 Authorization Framework, an entity capable of granting access to a protected resource.
When the resource owner is a person, it is referred to as an end user. For example, when a client application wants
to access a user's mailbox through the Microsoft Graph API, it requires permission from the resource owner of the
mailbox.
resource server
As defined by the OAuth2 Authorization Framework, a server that hosts protected resources, capable of accepting
and responding to protected resource requests by client applications that present an access token. Also known as a
protected resource server, or resource application.
A resource server exposes APIs and enforces access to its protected resources through scopes and roles, using the
OAuth 2.0 Authorization Framework. Examples include the Azure AD Graph API which provides access to Azure AD
tenant data, and the Office 365 APIs that provide access to data such as mail and calendar. Both of these are also
accessible via the Microsoft Graph API.
Just like a client application, resource application's identity configuration is established via registration in an Azure
AD tenant, providing both the application and service principal object. Some Microsoft-provided APIs, such as the
Azure AD Graph API, have pre-registered service principals made available in all tenants during provisioning.
roles
Like scopes, roles provide a way for a resource server to govern access to its protected resources. There are two
types: a "user" role implements role-based access control for users/groups that require access to the resource,
while an "application" role implements the same for client applications that require access.
Roles are resource-defined strings (for example "Expense approver", "Read-only", "Directory.ReadWrite.All"),
managed in the Azure portal via the resource's application manifest, and stored in the resource's appRoles
property. The Azure portal is also used to assign users to "user" roles, and configure client application permissions
to access an "application" role.
For a detailed discussion of the application roles exposed by Azure AD's Graph API, see Graph API Permission
Scopes. For a step-by-step implementation example, see Role based access control in cloud applications using
Azure AD.
scopes
Like roles, scopes provide a way for a resource server to govern access to its protected resources. Scopes are used
to implement scope-based access control, for a client application that has been given delegated access to the
resource by its owner.
Scopes are resource-defined strings (for example "Mail.Read", "Directory.ReadWrite.All"), managed in the Azure
portal via the resource's application manifest, and stored in the resource's oauth2Permissions property. The Azure
portal is also used to configure client application delegated permissions to access a scope.
A best practice naming convention, is to use a "resource.operation.constraint" format. For a detailed discussion of
the scopes exposed by Azure AD's Graph API, see Graph API Permission Scopes. For scopes exposed by Office 365
services, see Office 365 API permissions reference.
security token
A signed document containing claims, such as an OAuth2 token or SAML 2.0 assertion. For an OAuth2
authorization grant, an access token (OAuth2) and an ID Token are types of security tokens, both of which are
implemented as a JSON Web Token (JWT).
service principal object
When you register/update an application in the Azure portal, the portal creates/updates both an application object
and a corresponding service principal object for that tenant. The application object defines the application's identity
configuration globally (across all tenants where the associated application has been granted access), and is the
template from which its corresponding service principal object(s) are derived for use locally at run-time (in a
specific tenant).
See Application and Service Principal Objects for more information.
sign-in
The process of a client application initiating end user authentication and capturing related state, for the purpose of
acquiring a security token and scoping the application session to that state. State can include artifacts such as user
profile information, and information derived from token claims.
The sign-in function of an application is typically used to implement single-sign-on (SSO). It may also be preceded
by a "sign-up" function, as the entry point for an end user to gain access to an application (upon first sign-in). The
sign-up function is used to gather and persist additional state specific to the user, and may require user consent.
sign-out
The process of un-authenticating an end user, detaching the user state associated with the client application
session during sign-in
tenant
An instance of an Azure AD directory is referred to as an Azure AD tenant. It provides a variety of features,
including:
a registry service for integrated applications
authentication of user accounts and registered applications
REST endpoints required to support various protocols including OAuth2 and SAML, including the authorization
endpoint, token endpoint and the "common" endpoint used by multi-tenant applications.
A tenant is also associated with an Azure AD or Office 365 subscription during provisioning of the subscription,
providing Identity & Access Management features for the subscription. See How to get an Azure Active Directory
tenant for details on the various ways you can get access to a tenant. See How Azure subscriptions are associated
with Azure Active Directory for details on the relationship between subscriptions and an Azure AD tenant.
token endpoint
One of the endpoints implemented by the authorization server to support OAuth2 authorization grants.
Depending on the grant, it can be used to acquire an access token (and related "refresh" token) to a client, or ID
token when used with the OpenID Connect protocol.
User-agent-based client
A type of client application that downloads code from a web server and executes within a user-agent (for instance,
a web browser), such as a Single Page Application (SPA). Since all code is executed on a device, it is considered a
"public" client due to its inability to store credentials privately/confidentially. See OAuth2 client types and profiles
for more details.
user principal
Similar to the way a service principal object is used to represent an application instance, a user principal object is
another type of security principal, which represents a user. The Azure AD Graph User entity defines the schema for
a user object, including user-related properties such as first and last name, user principal name, directory role
membership, etc. This provides the user identity configuration for Azure AD to establish a user principal at runtime. The user principal is used to represent an authenticated user for Single Sign-On, recording consent
delegation, making access control decisions, etc.
web client
A type of client application that executes all code on a web server, and able to function as a "confidential" client by
securely storing its credentials on the server. See OAuth2 client types and profiles for more details.
Next steps
The Azure AD Developer's Guide is the portal to use for all Azure AD development related topics, including an
overview of application integration and the basics of Azure AD authentication and supported authentication
scenarios.
Please use the following comments section to provide feedback and help us refine and shape our content,
including requests for new definitions or updating existing ones!
Azure Active Directory Authentication Protocols
4/27/2017 • 1 min to read • Edit Online
Azure Active Directory (Azure AD) supports several of the most widely used authentication and authorization
protocols. The topics in this section describe the supported protocols and their implementation in Azure AD. The
topics included a review of supported claim types, an introduction to the use of federation metadata, detailed
OAuth 2.0. and SAML 2.0 protocol reference documentation, and a troubleshooting section.
Authentication Protocols Articles and Reference
Important Information About Signing Key Rollover in Azure AD – Learn about Azure AD’s signing key rollover
cadence, changes you can make to update the key automatically, and discussion for how to update the most
common application scenarios.
Supported Token and Claim Types - Learn about the claims in the tokens that Azure AD issues.
Federation Metadata - Learn how to find and interpret the metadata documents that Azure AD generates.
OAuth 2.0 in Azure AD - Learn about the implementation of OAuth 2.0 in Azure AD.
OpenID Connect 1.0 - Learn how to use OAuth 2.0, an authorization protocol, for authentication.
Service to Service Calls - Learn how to use OAuth 2.0 client credentials grant flow for service to service calls.
SAML Protocol Reference - Learn about the Single Sign-On and Single Sign-out SAML profiles of Azure AD.
See Also
Azure Active Directory Developer's Guide
Using Azure AD for Authentication
Active Directory Code Samples
Authorize access to web applications using OpenID
Connect and Azure Active Directory
2/23/2017 • 11 min to read • Edit Online
OpenID Connect is a simple identity layer built on top of the OAuth 2.0 protocol. OAuth 2.0 defines mechanisms
to obtain and use access tokens to access protected resources, but they do not define standard methods to
provide identity information. OpenID Connect implements authentication as an extension to the OAuth 2.0
authorization process. It provides information about the end user in the form of an id_token that verifies the
identity of the user and provides basic profile information about the user.
OpenID Connect is our recommendation if you are building a web application that is hosted on a server and
accessed via a browser.
Register your application with your AD tenant
First, you will need to register your application with your Azure Active Directory (Azure AD) tenant. This will give
you an Application ID for your application, as well as enable it to receive tokens.
Sign in to the Azure Portal.
Choose your Azure AD tenant by clicking on your account in the top right corner of the page.
In the left hand navigation pane, click on Azure Active Directory.
Click on App Registrations and click on Add.
Follow the prompts and create a new application. It doesn't matter if it is a web application or a native
application for this tutorial, but if you'd like specific examples for web applications or native applications, check
out our quickstarts.
For Web Applications, provide the Sign-On URL which is the base URL of your app, where users can
sign in e.g http://localhost:12345 .
For Native Applications, provide a Redirect URI, which Azure AD will use to return token responses.
Enter a value specific to your application, .e.g http://MyFirstAADApp
Once you've completed registration, Azure AD will assign your application a unique client identifier, the
Application ID. You will need this value in the next sections, so copy it from the application page.
Authentication flow using OpenID Connect
The most basic sign-in flow contains the following steps - each of them is described in detail below.
OpenID Connect metadata document
OpenID Connect describes a metadata document that contains most of the information required for an app to
perform sign-in. This includes information such as the URLs to use and the location of the service's public signing
keys. The OpenID Connect metadata document can be found at:
https://login.microsoftonline.com/{tenant}/.well-known/openid-configuration
The metadata is a simple JavaScript Object Notation (JSON) document. See the following snippet for an example.
The snippet's contents are fully described in the OpenID Connect specification.
{
"authorization_endpoint": "https://login.microsoftonline.com/common/oauth2/authorize",
"token_endpoint": "https://login.microsoftonline.com/common/oauth2/token",
"token_endpoint_auth_methods_supported":
[
"client_secret_post",
"private_key_jwt"
],
"jwks_uri": "https://login.microsoftonline.com/common/discovery/keys"
...
}
Send the sign-in request
When your web application needs to authenticate the user, it must direct the user to the /authorize endpoint.
This request is similar to the first leg of the OAuth 2.0 Authorization Code Flow, with a few important distinctions:
The request must include the scope openid in the scope parameter.
The response_type parameter must include id_token .
The request must include the nonce parameter.
So a sample request would look like this:
// Line breaks for legibility only
GET https://login.microsoftonline.com/{tenant}/oauth2/authorize?
client_id=6731de76-14a6-49ae-97bc-6eba6914391e
&response_type=id_token
&redirect_uri=http%3A%2F%2Flocalhost%2Fmyapp%2F
&response_mode=form_post
&scope=openid
&state=12345
&nonce=7362CAEA-9CA5-4B43-9BA3-34D7C303EBA7
PARAMETER
DESCRIPTION
tenant
required
The {tenant} value in the path of the
request can be used to control who can
sign into the application. The allowed
values are tenant identifiers, for
example,
8eaef023-2b34-4da1-9baa-8bc8c9d6a490 or
contoso.onmicrosoft.com or common for
tenant-independent tokens
client_id
required
The Application Id assigned to your app
when you registered it with Azure AD.
You can find this in the Azure Portal.
Click Azure Active Directory, click
App Registrations, choose the
application and locate the Application
Id on the application page.
response_type
required
Must include id_token for OpenID
Connect sign-in. It may also include
other response_types, such as code .
PARAMETER
DESCRIPTION
scope
required
A space-separated list of scopes. For
OpenID Connect, it must include the
scope openid , which translates to the
"Sign you in" permission in the consent
UI. You may also include other scopes
in this request for requesting consent.
nonce
required
A value included in the request,
generated by the app, that is included
in the resulting id_token as a claim. The
app can then verify this value to
mitigate token replay attacks. The value
is typically a randomized, unique string
or GUID that can be used to identify
the origin of the request.
redirect_uri
recommended
The redirect_uri of your app, where
authentication responses can be sent
and received by your app. It must
exactly match one of the redirect_uris
you registered in the portal, except it
must be url encoded.
response_mode
recommended
Specifies the method that should be
used to send the resulting
authorization_code back to your app.
Supported values are form_post for
HTTP form post or fragment for URL
fragment. For web applications, we
recommend using
response_mode=form_post to ensure the
most secure transfer of tokens to your
application.
state
recommended
A value included in the request that is
returned in the token response. It can
be a string of any content that you
wish. A randomly generated unique
value is typically used for preventing
cross-site request forgery attacks. The
state is also used to encode
information about the user's state in
the app before the authentication
request occurred, such as the page or
view they were on.
PARAMETER
DESCRIPTION
prompt
optional
Indicates the type of user interaction
that is required. Currently, the only
valid values are 'login', 'none', and
'consent'. prompt=login forces the user
to enter their credentials on that
request, negating single-sign on.
prompt=none is the opposite - it
ensures that the user is not presented
with any interactive prompt
whatsoever. If the request cannot be
completed silently via single-sign on,
the endpoint returns an error.
prompt=consent triggers the OAuth
consent dialog after the user signs in,
asking the user to grant permissions to
the app.
login_hint
optional
Can be used to pre-fill the
username/email address field of the
sign-in page for the user, if you know
their username ahead of time. Often
apps use this parameter during
reauthentication, having already
extracted the username from a
previous sign-in using the
preferred_username claim.
At this point, the user is asked to enter their credentials and complete the authentication.
Sample response
A sample response, after the user has authenticated, could look like this:
POST /myapp/ HTTP/1.1
Host: localhost
Content-Type: application/x-www-form-urlencoded
id_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik1uQ19WWmNB...&state=12345
PARAMETER
DESCRIPTION
id_token
The
id_token that the app requested. You can use the
id_token to verify the user's identity and begin a session with
the user.
state
Error response
Error responses may also be sent to the
A value included in the request that is also returned in the
token response. A randomly generated unique value is
typically used for preventing cross-site request forgery
attacks. The state is also used to encode information about
the user's state in the app before the authentication request
occurred, such as the page or view they were on.
redirect_uri
so the app can handle them appropriately:
POST /myapp/ HTTP/1.1
Host: localhost
Content-Type: application/x-www-form-urlencoded
error=access_denied&error_description=the+user+canceled+the+authentication
PARAMETER
DESCRIPTION
error
An error code string that can be used to classify types of
errors that occur, and can be used to react to errors.
error_description
A specific error message that can help a developer identify
the root cause of an authentication error.
Error codes for authorization endpoint errors
The following table describes the various error codes that can be returned in the
response.
error
parameter of the error
ERROR CODE
DESCRIPTION
CLIENT ACTION
invalid_request
Protocol error, such as a missing
required parameter.
Fix and resubmit the request. This is a
development error, and is typically
caught during initial testing.
unauthorized_client
The client application is not permitted
to request an authorization code.
This usually occurs when the client
application is not registered in Azure
AD or is not added to the user's Azure
AD tenant. The application can prompt
the user with instruction for installing
the application and adding it to Azure
AD.
access_denied
Resource owner denied consent
The client application can notify the
user that it cannot proceed unless the
user consents.
unsupported_response_type
The authorization server does not
support the response type in the
request.
Fix and resubmit the request. This is a
development error, and is typically
caught during initial testing.
server_error
The server encountered an unexpected
error.
Retry the request. These errors can
result from temporary conditions. The
client application might explain to the
user that its response is delayed due to
a temporary error.
temporarily_unavailable
The server is temporarily too busy to
handle the request.
Retry the request. The client application
might explain to the user that its
response is delayed due to a temporary
condition.
invalid_resource
The target resource is invalid because it
does not exist, Azure AD cannot find it,
or it is not correctly configured.
This indicates the resource, if it exists,
has not been configured in the tenant.
The application can prompt the user
with instruction for installing the
application and adding it to Azure AD.
Validate the id_token
Just receiving an id_token is not sufficient to authenticate the user; you must validate the signature and verify
the claims in the id_token per your app's requirements. The Azure AD endpoint uses JSON Web Tokens (JWTs)
and public key cryptography to sign tokens and verify that they are valid.
You can choose to validate the id_token in client code, but a common practice is to send the id_token to a
backend server and perform the validation there. Once you've validated the signature of the id_token , there are a
few claims you are required to verify.
You may also wish to validate additional claims depending on your scenario. Some common validations include:
Ensuring the user/organization has signed up for the app.
Ensuring the user has proper authorization/privileges
Ensuring a certain strength of authentication has occurred, such as multi-factor authentication.
Once you have validated the id_token , you can begin a session with the user and use the claims in the id_token
to obtain information about the user in your app. This information can be used for display, records,
authorizations, etc. For more information about the token types and claims, read Supported Token and Claim
Types.
Send a sign-out request
When you wish to sign the user out of the app, it is not sufficient to clear your app's cookies or otherwise end the
session with the user. You must also redirect the user to the end_session_endpoint for sign-out. If you fail to do
so, the user will be able to reauthenticate to your app without entering their credentials again, because they will
have a valid single sign-on session with the Azure AD endpoint.
You can simply redirect the user to the
end_session_endpoint
listed in the OpenID Connect metadata document:
GET https://login.microsoftonline.com/common/oauth2/logout?
post_logout_redirect_uri=http%3A%2F%2Flocalhost%2Fmyapp%2F
PARAMETER
post_logout_redirect_uri
DESCRIPTION
recommended
The URL that the user should be
redirected to after successful logout. If
not included, the user is shown a
generic message.
Single sign-out
When you redirect the user to the end_session_endpoint , Azure AD clears the user's session from the browser.
However, the user may still be signed in to other applications that use Azure AD for authentication. To enable
those applications to sign the user out simultaneously, Azure AD sends an HTTP GET request to the registered
LogoutUrl of all the applications that the user is currently signed in to. Applications must respond to this request
by clearing any session that identifies the user and returning a 200 response. If you wish to support single sign
out in your application, you must implement such a LogoutUrl in your application's code. You can set the
LogoutUrl from the Azure portal:
1. Navigate to the Azure Portal.
2. Choose your Active Directory by clicking on your account in the top right corner of the page.
3. From the left hand navigation panel, choose Azure Active Directory, then choose App registrations and
select your application.
4. Click on Properties and find the Logout URL text box.
Token Acquisition
Many web apps need to not only sign the user in, but also access a web service on behalf of that user using
OAuth. This scenario combines OpenID Connect for user authentication while simultaneously acquiring an
authorization_code that can be used to get access_tokens using the OAuth Authorization Code Flow.
Get Access Tokens
To acquire access tokens, you need to modify the sign-in request from above:
// Line breaks for legibility only
GET https://login.microsoftonline.com/{tenant}/oauth2/authorize?
client_id=6731de76-14a6-49ae-97bc-6eba6914391e
// Your registered Application Id
&response_type=id_token+code
&redirect_uri=http%3A%2F%2Flocalhost%2Fmyapp%2F
// Your registered Redirect Uri, url encoded
&response_mode=form_post
// form_post', or 'fragment'
&scope=openid
&resource=https%3A%2F%2Fservice.contoso.com%2F
&state=12345
// Any value, provided by your app
&nonce=678910
// Any value, provided by your app
By including permission scopes in the request and using response_type=code+id_token , the authorize endpoint
ensures that the user has consented to the permissions indicated in the scope query parameter, and return your
app an authorization code to exchange for an access token.
Successful Response
A successful response using
response_mode=form_post
looks like:
POST /myapp/ HTTP/1.1
Host: localhost
Content-Type: application/x-www-form-urlencoded
id_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik1uQ19WWmNB...&code=AwABAAAAvPM1KaPlrEqdFSBzjqfTGBCmLdg
fSTLEMPGYuNHSUYBrq...&state=12345
PARAMETER
DESCRIPTION
id_token
The
id_token that the app requested. You can use the
id_token to verify the user's identity and begin a session with
the user.
code
The authorization_code that the app requested. The app can
use the authorization code to request an access token for the
target resource. Authorization_codes are short lived, and
typically expire after about 10 minutes.
state
If a state parameter is included in the request, the same value
should appear in the response. The app should verify that the
state values in the request and response are identical.
Error response
Error responses may also be sent to the
redirect_uri
so the app can handle them appropriately:
POST /myapp/ HTTP/1.1
Host: localhost
Content-Type: application/x-www-form-urlencoded
error=access_denied&error_description=the+user+canceled+the+authentication
PARAMETER
DESCRIPTION
error
An error code string that can be used to classify types of
errors that occur, and can be used to react to errors.
error_description
A specific error message that can help a developer identify
the root cause of an authentication error.
For a description of the possible error codes and their recommended client action, see Error codes for
authorization endpoint errors.
Once you've gotten an authorization code and an id_token , you can sign the user in and get access tokens on
their behalf. To sign the user in, you must validate the id_token exactly as described above. To get access tokens,
you can follow the steps described in the "Use the authorization code to request an access token" section of our
OAuth protocol documentation.
Authorize access to web applications using OAuth
2.0 and Azure Active Directory
2/13/2017 • 20 min to read • Edit Online
Azure Active Directory (Azure AD) uses OAuth 2.0 to enable you to authorize access to web applications and
web APIs in your Azure AD tenant. This guide is language independent, and describes how to send and receive
HTTP messages without using any of our open-source libraries.
The OAuth 2.0 authorization code flow is described in section 4.1 of the OAuth 2.0 specification. It is used to
perform authentication and authorization in most application types, including web apps and natively installed
apps.
Register your application with your AD tenant
First, you will need to register your application with your Azure Active Directory (Azure AD) tenant. This will give
you an Application ID for your application, as well as enable it to receive tokens.
Sign in to the Azure Portal.
Choose your Azure AD tenant by clicking on your account in the top right corner of the page.
In the left hand navigation pane, click on Azure Active Directory.
Click on App Registrations and click on Add.
Follow the prompts and create a new application. It doesn't matter if it is a web application or a native
application for this tutorial, but if you'd like specific examples for web applications or native applications,
check out our quickstarts.
For Web Applications, provide the Sign-On URL which is the base URL of your app, where users can
sign in e.g http://localhost:12345 .
For Native Applications, provide a Redirect URI, which Azure AD will use to return token responses.
Enter a value specific to your application, .e.g http://MyFirstAADApp
Once you've completed registration, Azure AD will assign your application a unique client identifier, the
Application ID. You will need this value in the next sections, so copy it from the application page.
OAuth 2.0 authorization flow
At a high level, the entire authorization flow for an application looks a bit like this:
Request an authorization code
The authorization code flow begins with the client directing the user to the /authorize endpoint. In this request,
the client indicates the permissions it needs to acquire from the user. You can get the OAuth 2.0 endpoints from
your application's page in Azure Classic Portal, in the View Endpoints button in the bottom drawer.
// Line breaks for legibility only
https://login.microsoftonline.com/{tenant}/oauth2/authorize?
client_id=6731de76-14a6-49ae-97bc-6eba6914391e
&response_type=code
&redirect_uri=http%3A%2F%2Flocalhost%2Fmyapp%2F
&response_mode=query
&resource=https%3A%2F%2Fservice.contoso.com%2F
&state=12345
PARAMETER
DESCRIPTION
PARAMETER
DESCRIPTION
tenant
required
The {tenant} value in the path of the
request can be used to control who
can sign into the application. The
allowed values are tenant identifiers,
for example,
8eaef023-2b34-4da1-9baa-8bc8c9d6a490 or
contoso.onmicrosoft.com or common for
tenant-independent tokens
client_id
required
The Application Id assigned to your
app when you registered it with Azure
AD. You can find this in the Azure
Portal. Click Active Directory, click
the directory, choose the application,
and click Configure
response_type
required
Must include code for the
authorization code flow.
redirect_uri
recommended
The redirect_uri of your app, where
authentication responses can be sent
and received by your app. It must
exactly match one of the redirect_uris
you registered in the portal, except it
must be url encoded. For native &
mobile apps, you should use the
default value of urn:ietf:wg:oauth:2.0:oob .
response_mode
recommended
Specifies the method that should be
used to send the resulting token back
to your app. Can be query or
form_post .
state
recommended
A value included in the request that is
also returned in the token response. A
randomly generated unique value is
typically used for preventing cross-site
request forgery attacks. The state is
also used to encode information about
the user's state in the app before the
authentication request occurred, such
as the page or view they were on.
resource
optional
The App ID URI of the web API
(secured resource). To find the App ID
URI of the web API, in the Azure
Portal, click Active Directory, click the
directory, click the application and
then click Configure.
PARAMETER
prompt
DESCRIPTION
optional
Indicate the type of user interaction
that is required.
Valid values are:
login: The user should be
prompted to reauthenticate.
consent: User consent has been
granted, but needs to be updated.
The user should be prompted to
consent.
admin_consent: An administrator
should be prompted to consent
on behalf of all users in their
organization
login_hint
optional
Can be used to pre-fill the
username/email address field of the
sign-in page for the user, if you know
their username ahead of time. Often
apps use this parameter during
reauthentication, having already
extracted the username from a
previous sign-in using the
preferred_username claim.
domain_hint
optional
Provides a hint about the tenant or
domain that the user should use to
sign in. The value of the domain_hint is
a registered domain for the tenant. If
the tenant is federated to an onpremises directory, AAD redirects to
the specified tenant federation server.
NOTE
If the user is part of an organization, an administrator of the organization can consent or decline on the user's behalf, or
permit the user to consent. The user is given the option to consent only when the administrator permits it.
At this point, the user is asked to enter their credentials and consent to the permissions indicated in the scope
query parameter. Once the user authenticates and grants consent, Azure AD sends a response to your app at the
redirect_uri address in your request.
Successful response
A successful response could look like this:
GET HTTP/1.1 302 Found
Location: http://localhost/myapp/?code=
AwABAAAAvPM1KaPlrEqdFSBzjqfTGBCmLdgfSTLEMPGYuNHSUYBrqqf_ZT_p5uEAEJJ_nZ3UmphWygRNy2C3jJ239gV_DBnZ2syeg95Ki374WHUP-i3yIhv5i-7KU2CEoPXwURQp6IVYMwDjAOzn7C3JCu5wpngXmbZKtJdWmiBzHpcO2aICJPu1KvJrDLDP20chJBXzVYJtkfjviLNNW7l7Y3ydcHDsBRKZc3GuMQanmcghXPyoDg41g
8XbwPudVh7uCmUponBQpIhbuffFP_tbV8SNzsPoFz9CLpBCZagJVXeqWoYMPe2dSsPiLO9Alf_YIe5zpizY4C3aLw5g9at35eZTfNd0gBRpR5ojkMIcZZ6IgAA&session_state=7B29111D-C220-4263-99AB6F6E135D75EF&state=D79E5777-702E-4260-9A62-37F75FF22CCE
PARAMETER
DESCRIPTION
admin_consent
The value is True if an administrator consented to a consent
request prompt.
code
The authorization code that the application requested. The
application can use the authorization code to request an
access token for the target resource.
session_state
A unique value that identifies the current user session. This
value is a GUID, but should be treated as an opaque value
that is passed without examination.
state
If a state parameter is included in the request, the same
value should appear in the response. It's a good practice for
the application to verify that the state values in the request
and response are identical before using the response. This
helps to detect Cross-Site Request Forgery (CSRF) attacks
against the client.
Error response
Error responses may also be sent to the
redirect_uri
so that the application can handle them appropriately.
GET http://localhost:12345/?
error=access_denied
&error_description=the+user+canceled+the+authentication
PARAMETER
DESCRIPTION
error
An error code value defined in Section 5.2 of the OAuth 2.0
Authorization Framework. The next table describes the error
codes that Azure AD returns.
error_description
A more detailed description of the error. This message is not
intended to be end-user friendly.
state
The state value is a randomly generated non-reused value
that is sent in the request and returned in the response to
prevent cross-site request forgery (CSRF) attacks.
Error codes for authorization endpoint errors
The following table describes the various error codes that can be returned in the
response.
error
parameter of the error
ERROR CODE
DESCRIPTION
CLIENT ACTION
invalid_request
Protocol error, such as a missing
required parameter.
Fix and resubmit the request. This is a
development error, and is typically
caught during initial testing.
ERROR CODE
DESCRIPTION
CLIENT ACTION
unauthorized_client
The client application is not permitted
to request an authorization code.
This usually occurs when the client
application is not registered in Azure
AD or is not added to the user's Azure
AD tenant. The application can prompt
the user with instruction for installing
the application and adding it to Azure
AD.
access_denied
Resource owner denied consent
The client application can notify the
user that it cannot proceed unless the
user consents.
unsupported_response_type
The authorization server does not
support the response type in the
request.
Fix and resubmit the request. This is a
development error, and is typically
caught during initial testing.
server_error
The server encountered an unexpected
error.
Retry the request. These errors can
result from temporary conditions. The
client application might explain to the
user that its response is delayed due
to a temporary error.
temporarily_unavailable
The server is temporarily too busy to
handle the request.
Retry the request. The client
application might explain to the user
that its response is delayed due to a
temporary condition.
invalid_resource
The target resource is invalid because
it does not exist, Azure AD cannot find
it, or it is not correctly configured.
This indicates the resource, if it exists,
has not been configured in the tenant.
The application can prompt the user
with instruction for installing the
application and adding it to Azure AD.
Use the authorization code to request an access token
Now that you've acquired an authorization code and have been granted permission by the user, you can
redeem the code for an access token to the desired resource, by sending a POST request to the /token
endpoint:
// Line breaks for legibility only
POST /{tenant}/oauth2/token HTTP/1.1
Host: https://login.microsoftonline.com
Content-Type: application/x-www-form-urlencoded
grant_type=authorization_code
&client_id=2d4d11a2-f814-46a7-890a-274a72a7309e
&code=AwABAAAAvPM1KaPlrEqdFSBzjqfTGBCmLdgfSTLEMPGYuNHSUYBrqqf_ZT_p5uEAEJJ_nZ3UmphWygRNy2C3jJ239gV_DBnZ2syeg
95Ki-374WHUP-i3yIhv5i-7KU2CEoPXwURQp6IVYMwDjAOzn7C3JCu5wpngXmbZKtJdWmiBzHpcO2aICJPu1KvJrDLDP20chJBXzVYJtkfjviLNNW7l7Y3ydcHDsBRKZc3GuMQanmcghXPyoDg41g
8XbwPudVh7uCmUponBQpIhbuffFP_tbV8SNzsPoFz9CLpBCZagJVXeqWoYMPe2dSsPiLO9Alf_YIe5zpizY4C3aLw5g9at35eZTfNd0gBRpR5ojkMIcZZ6IgAA
&redirect_uri=https%3A%2F%2Flocalhost%2Fmyapp%2F
&resource=https%3A%2F%2Fservice.contoso.com%2F
&client_secret=p@ssw0rd
//NOTE: client_secret only required for web apps
PARAMETER
DESCRIPTION
tenant
required
The {tenant} value in the path of the
request can be used to control who
can sign into the application. The
allowed values are tenant identifiers,
for example,
8eaef023-2b34-4da1-9baa-8bc8c9d6a490 or
contoso.onmicrosoft.com or common for
tenant-independent tokens
client_id
required
The Application Id assigned to your
app when you registered it with Azure
AD. You can find this in the Azure
Classic Portal. Click Active Directory,
click the directory, choose the
application, and click Configure
grant_type
required
Must be authorization_code for the
authorization code flow.
code
required
The authorization_code that you
acquired in the previous section
redirect_uri
required
The same redirect_uri value that was
used to acquire the authorization_code .
client_secret
required for web apps
The application secret that you created
in the app registration portal for your
app. It should not be used in a native
app, because client_secrets cannot be
reliably stored on devices. It is required
for web apps and web APIs, which
have the ability to store the
client_secret securely on the server
side.
resource
required if specified in authorization
code request, else optional
The App ID URI of the web API
(secured resource).
To find the App ID URI, in the Azure Management Portal, click Active Directory, click the directory, click the
application, and then click Configure.
Successful response
Azure AD returns an access token upon a successful response. To minimize network calls from the client
application and their associated latency, the client application should cache access tokens for the token lifetime
that is specified in the OAuth 2.0 response. To determine the token lifetime, use either the expires_in or
expires_on parameter values.
If a web API resource returns an invalid_token error code, this might indicate that the resource has determined
that the token is expired. If the client and resource clock times are different (known as a "time skew"), the
resource might consider the token to be expired before the token is cleared from the client cache. If this occurs,
clear the token from the cache, even if it is still within its calculated lifetime.
A successful response could look like this:
{
"access_token": "
eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik5HVEZ2ZEstZnl0aEV1THdqcHdBSk9NOW4tQSJ9.eyJhdWQiOiJodHRwczovL3
NlcnZpY2UuY29udG9zby5jb20vIiwiaXNzIjoiaHR0cHM6Ly9zdHMud2luZG93cy5uZXQvN2ZlODE0NDctZGE1Ny00Mzg1LWJlY2ItNmRlN
TdmMjE0NzdlLyIsImlhdCI6MTM4ODQ0MDg2MywibmJmIjoxMzg4NDQwODYzLCJleHAiOjEzODg0NDQ3NjMsInZlciI6IjEuMCIsInRpZCI6
IjdmZTgxNDQ3LWRhNTctNDM4NS1iZWNiLTZkZTU3ZjIxNDc3ZSIsIm9pZCI6IjY4Mzg5YWUyLTYyZmEtNGIxOC05MWZlLTUzZGQxMDlkNzR
mNSIsInVwbiI6ImZyYW5rbUBjb250b3NvLmNvbSIsInVuaXF1ZV9uYW1lIjoiZnJhbmttQGNvbnRvc28uY29tIiwic3ViIjoiZGVOcUlqOU
lPRTlQV0pXYkhzZnRYdDJFYWJQVmwwQ2o4UUFtZWZSTFY5OCIsImZhbWlseV9uYW1lIjoiTWlsbGVyIiwiZ2l2ZW5fbmFtZSI6IkZyYW5rI
iwiYXBwaWQiOiIyZDRkMTFhMi1mODE0LTQ2YTctODkwYS0yNzRhNzJhNzMwOWUiLCJhcHBpZGFjciI6IjAiLCJzY3AiOiJ1c2VyX2ltcGVy
c29uYXRpb24iLCJhY3IiOiIxIn0.JZw8jC0gptZxVC7l5sFkdnJgP3_tRjeQEPgUn28XctVe3QqmheLZw7QVZDPCyGycDWBaqy7FLpSekET_BftDkewRhyHk9FW_KeEz0ch2c3i08NGNDbr6XYGVa
yNuSesYk5Aw_p3ICRlUV1bqEwkJkzs9EEkQg4hbefqJS6yS1HoV_2EsEhpd_wCQpxK89WPs3hLYZETRJtG5kvCCEOvSHXmDE6eTHGTnEgsIk-UlPe275Dvou4gEAwLofhLDQbMSjnlV5VLsjimNBVcSRFShoxmQwBJR_b2011Y5IuD6St5zPnzruBbZYkGNurQK63TJPWmRd3mbJsGM0mf3C
UQ",
"token_type": "Bearer",
"expires_in": "3600",
"expires_on": "1388444763",
"resource": "https://service.contoso.com/",
"refresh_token": "AwABAAAAvPM1KaPlrEqdFSBzjqfTGAMxZGUTdM0t4B4rTfgV29ghDOHRc2BC_hHeJaJICqjZ3mY2b_YNqmf9SoAylD1PycGCB90xzZeEDg6oBzOIPfYsbDWNf621pKo2Q3GGTHYlmNfwocOlrxK69hkha2CF12azM_NYhgO668yfcUl4VBbiSHZyd1NVZG5QTIOcbObu3qnLutbpadZGAxqjIbMkQ2bQS09fTrjMBtDE3D6kSMIodpCec
oANon9b0LATkpitimVCrl-NyfN3oyG4ZCWu18M9-vEou4Sq-1oMDzExgAf61noxzkNiaTecM-Ve5cq6wHqYQjfV9DOz4lbceuYCAA",
"scope": "https%3A%2F%2Fgraph.microsoft.com%2Fmail.read",
"id_token": "
eyJ0eXAiOiJKV1QiLCJhbGciOiJub25lIn0.eyJhdWQiOiIyZDRkMTFhMi1mODE0LTQ2YTctODkwYS0yNzRhNzJhNzMwOWUiLCJpc3MiOiJ
odHRwczovL3N0cy53aW5kb3dzLm5ldC83ZmU4MTQ0Ny1kYTU3LTQzODUtYmVjYi02ZGU1N2YyMTQ3N2UvIiwiaWF0IjoxMzg4NDQwODYzLC
JuYmYiOjEzODg0NDA4NjMsImV4cCI6MTM4ODQ0NDc2MywidmVyIjoiMS4wIiwidGlkIjoiN2ZlODE0NDctZGE1Ny00Mzg1LWJlY2ItNmRlN
TdmMjE0NzdlIiwib2lkIjoiNjgzODlhZTItNjJmYS00YjE4LTkxZmUtNTNkZDEwOWQ3NGY1IiwidXBuIjoiZnJhbmttQGNvbnRvc28uY29t
IiwidW5pcXVlX25hbWUiOiJmcmFua21AY29udG9zby5jb20iLCJzdWIiOiJKV3ZZZENXUGhobHBTMVpzZjd5WVV4U2hVd3RVbTV5elBtd18
talgzZkhZIiwiZmFtaWx5X25hbWUiOiJNaWxsZXIiLCJnaXZlbl9uYW1lIjoiRnJhbmsifQ.”
}
PARAMETER
DESCRIPTION
access_token
The requested access token. The app can use this token to
authenticate to the secured resource, such as a web API.
token_type
Indicates the token type value. The only type that Azure AD
supports is Bearer. For more information about Bearer
tokens, see OAuth2.0 Authorization Framework: Bearer
Token Usage (RFC 6750)
expires_in
How long the access token is valid (in seconds).
expires_on
The time when the access token expires. The date is
represented as the number of seconds from 1970-0101T0:0:0Z UTC until the expiration time. This value is used to
determine the lifetime of cached tokens.
resource
The App ID URI of the web API (secured resource).
scope
Impersonation permissions granted to the client application.
The default permission is user_impersonation . The owner of
the secured resource can register additional values in Azure
AD.
PARAMETER
DESCRIPTION
refresh_token
An OAuth 2.0 refresh token. The app can use this token to
acquire additional access tokens after the current access
token expires. Refresh tokens are long-lived, and can be
used to retain access to resources for extended periods of
time.
id_token
An unsigned JSON Web Token (JWT). The app can base64Url
decode the segments of this token to request information
about the user who signed in. The app can cache the values
and display them, but it should not rely on them for any
authorization or security boundaries.
JWT Token Claims
The JWT token in the value of the
id_token
parameter can be decoded into the following claims:
{
"typ": "JWT",
"alg": "none"
}.
{
"aud": "2d4d11a2-f814-46a7-890a-274a72a7309e",
"iss": "https://sts.windows.net/7fe81447-da57-4385-becb-6de57f21477e/",
"iat": 1388440863,
"nbf": 1388440863,
"exp": 1388444763,
"ver": "1.0",
"tid": "7fe81447-da57-4385-becb-6de57f21477e",
"oid": "68389ae2-62fa-4b18-91fe-53dd109d74f5",
"upn": "[email protected]",
"unique_name": "[email protected]",
"sub": "JWvYdCWPhhlpS1Zsf7yYUxShUwtUm5yzPmw_-jX3fHY",
"family_name": "Miller",
"given_name": "Frank"
}.
For more information about JSON web tokens, see the JWT IETF draft specification. For more information about
the token types and claims, read Supported Token and Claim Types
The
id_token
parameter includes the following claim types:
CLAIM TYPE
DESCRIPTION
aud
Audience of the token. When the token is issued to a client
application, the audience is the client_id of the client.
exp
Expiration time. The time when the token expires. For the
token to be valid, the current date/time must be less than or
equal to the exp value. The time is represented as the
number of seconds from January 1, 1970 (1970-0101T0:0:0Z) UTC until the time the token was issued.
family_name
User’s last name or surname. The application can display this
value.
given_name
User’s first name. The application can display this value.
CLAIM TYPE
DESCRIPTION
iat
Issued at time. The time when the JWT was issued. The time
is represented as the number of seconds from January 1,
1970 (1970-01-01T0:0:0Z) UTC until the time the token was
issued.
iss
Identifies the token issuer
nbf
Not before time. The time when the token becomes
effective. For the token to be valid, the current date/time
must be greater than or equal to the Nbf value. The time is
represented as the number of seconds from January 1, 1970
(1970-01-01T0:0:0Z) UTC until the time the token was
issued.
oid
Object identifier (ID) of the user object in Azure AD.
sub
Token subject identifier. This is a persistent and immutable
identifier for the user that the token describes. Use this
value in caching logic.
tid
Tenant identifier (ID) of the Azure AD tenant that issued the
token.
unique_name
A unique identifier for that can be displayed to the user. This
is usually a user principal name (UPN).
upn
User principal name of the user.
ver
Version. The version of the JWT token, typically 1.0.
Error response
The token issuance endpoint errors are HTTP error codes, because the client calls the token issuance endpoint
directly. In addition to the HTTP status code, the Azure AD token issuance endpoint also returns a JSON
document with objects that describe the error.
A sample error response could look like this:
{
"error": "invalid_grant",
"error_description": "AADSTS70002: Error validating credentials. AADSTS70008: The provided authorization
code or refresh token is expired. Send a new interactive authorization request for this user and
resource.\r\nTrace ID: 3939d04c-d7ba-42bf-9cb7-1e5854cdce9e\r\nCorrelation ID: a8125194-2dc8-4078-90ba7b6592a7f231\r\nTimestamp: 2016-04-11 18:00:12Z",
"error_codes": [
70002,
70008
],
"timestamp": "2016-04-11 18:00:12Z",
"trace_id": "3939d04c-d7ba-42bf-9cb7-1e5854cdce9e",
"correlation_id": "a8125194-2dc8-4078-90ba-7b6592a7f231"
}
PARAMETER
DESCRIPTION
PARAMETER
DESCRIPTION
error
An error code string that can be used to classify types of
errors that occur, and can be used to react to errors.
error_description
A specific error message that can help a developer identify
the root cause of an authentication error.
error_codes
A list of STS-specific error codes that can help in diagnostics.
timestamp
The time at which the error occurred.
trace_id
A unique identifier for the request that can help in
diagnostics.
correlation_id
A unique identifier for the request that can help in
diagnostics across components.
HTTP status codes
The following table lists the HTTP status codes that the token issuance endpoint returns. In some cases, the error
code is sufficient to describe the response, but if there are errors, you need to parse the accompanying JSON
document and examine its error code.
HTTP CODE
DESCRIPTION
400
Default HTTP code. Used in most cases and is typically due
to a malformed request. Fix and resubmit the request.
401
Authentication failed. For example, the request is missing the
client_secret parameter.
403
Authorization failed. For example, the user does not have
permission to access the resource.
500
An internal error has occurred at the service. Retry the
request.
Error codes for token endpoint errors
ERROR CODE
DESCRIPTION
CLIENT ACTION
invalid_request
Protocol error, such as a missing
required parameter.
Fix and resubmit the request
invalid_grant
The authorization code is invalid or has
expired.
Try a new request to the
endpoint
unauthorized_client
The authenticated client is not
authorized to use this authorization
grant type.
This usually occurs when the client
application is not registered in Azure
AD or is not added to the user's Azure
AD tenant. The application can prompt
the user with instruction for installing
the application and adding it to Azure
AD.
/authorize
ERROR CODE
DESCRIPTION
CLIENT ACTION
invalid_client
Client authentication failed.
The client credentials are not valid. To
fix, the application administrator
updates the credentials.
unsupported_grant_type
The authorization server does not
support the authorization grant type.
Change the grant type in the request.
This type of error should occur only
during development and be detected
during initial testing.
invalid_resource
The target resource is invalid because
it does not exist, Azure AD cannot find
it, or it is not correctly configured.
This indicates the resource, if it exists,
has not been configured in the tenant.
The application can prompt the user
with instruction for installing the
application and adding it to Azure AD.
interaction_required
The request requires user interaction.
For example, an additional
authentication step is required.
Retry the request with the same
resource.
temporarily_unavailable
The server is temporarily too busy to
handle the request.
Retry the request. The client
application might explain to the user
that its response is delayed due to a
temporary condition.
Use the access token to access the resource
Now that you've successfully acquired an access_token , you can use the token in requests to Web APIs, by
including it in the Authorization header. The RFC 6750 specification explains how to use bearer tokens in HTTP
requests to access protected resources.
Sample request
GET /data HTTP/1.1
Host: service.contoso.com
Authorization: Bearer
eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik5HVEZ2ZEstZnl0aEV1THdqcHdBSk9NOW4tQSJ9.eyJhdWQiOiJodHRwczovL3
NlcnZpY2UuY29udG9zby5jb20vIiwiaXNzIjoiaHR0cHM6Ly9zdHMud2luZG93cy5uZXQvN2ZlODE0NDctZGE1Ny00Mzg1LWJlY2ItNmRlN
TdmMjE0NzdlLyIsImlhdCI6MTM4ODQ0MDg2MywibmJmIjoxMzg4NDQwODYzLCJleHAiOjEzODg0NDQ3NjMsInZlciI6IjEuMCIsInRpZCI6
IjdmZTgxNDQ3LWRhNTctNDM4NS1iZWNiLTZkZTU3ZjIxNDc3ZSIsIm9pZCI6IjY4Mzg5YWUyLTYyZmEtNGIxOC05MWZlLTUzZGQxMDlkNzR
mNSIsInVwbiI6ImZyYW5rbUBjb250b3NvLmNvbSIsInVuaXF1ZV9uYW1lIjoiZnJhbmttQGNvbnRvc28uY29tIiwic3ViIjoiZGVOcUlqOU
lPRTlQV0pXYkhzZnRYdDJFYWJQVmwwQ2o4UUFtZWZSTFY5OCIsImZhbWlseV9uYW1lIjoiTWlsbGVyIiwiZ2l2ZW5fbmFtZSI6IkZyYW5rI
iwiYXBwaWQiOiIyZDRkMTFhMi1mODE0LTQ2YTctODkwYS0yNzRhNzJhNzMwOWUiLCJhcHBpZGFjciI6IjAiLCJzY3AiOiJ1c2VyX2ltcGVy
c29uYXRpb24iLCJhY3IiOiIxIn0.JZw8jC0gptZxVC7l5sFkdnJgP3_tRjeQEPgUn28XctVe3QqmheLZw7QVZDPCyGycDWBaqy7FLpSekET_BftDkewRhyHk9FW_KeEz0ch2c3i08NGNDbr6XYGVa
yNuSesYk5Aw_p3ICRlUV1bqEwkJkzs9EEkQg4hbefqJS6yS1HoV_2EsEhpd_wCQpxK89WPs3hLYZETRJtG5kvCCEOvSHXmDE6eTHGTnEgsIk-UlPe275Dvou4gEAwLofhLDQbMSjnlV5VLsjimNBVcSRFShoxmQwBJR_b2011Y5IuD6St5zPnzruBbZYkGNurQK63TJPWmRd3mbJsGM0mf3C
UQ
Error Response
Secured resources that implement RFC 6750 issue HTTP status codes. If the request does not include
authentication credentials or is missing the token, the response includes an WWW-Authenticate header. When a
request fails, the resource server responds with the HTTP status code and an error code.
The following is an example of an unsuccessful response when the client request does not include the bearer
token:
HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer authorization_uri="https://login.window.net/contoso.com/oauth2/authorize",
error="invalid_token", error_description="The access token is missing.",
Error parameters
PARAMETER
DESCRIPTION
authorization_uri
The URI (physical endpoint) of the authorization server. This
value is also used as a lookup key to get more information
about the server from a discovery endpoint.
The client must validate that the authorization server is
trusted. When the resource is protected by Azure AD, it
is sufficient to verify that the URL begins with
https://login.windows.net or another hostname that
Azure AD supports. A tenant-specific resource should
always return a tenant-specific authorization URI.
error
An error code value defined in Section 5.2 of the OAuth 2.0
Authorization Framework.
error_description
A more detailed description of the error. This message is not
intended to be end-user friendly.
resource_id
Returns the unique identifier of the resource. The client
application can use this identifier as the value of the
resource parameter when it requests a token for the
resource.
It is important for the client application to verify this
value, otherwise a malicious service might be able to
induce an elevation-of-privileges attack
The recommended strategy for preventing an attack is
to verify that the resource_id matches the base of the
web API URL that being accessed. For example, if
https://service.contoso.com/data is being accessed, the
resource_id can be htttps://service.contoso.com/. The
client application must reject a resource_id that does not
begin with the base URL unless there is a reliable
alternate way to verify the id.
Bearer scheme error codes
The RFC 6750 specification defines the following errors for resources that use the WWW-Authenticate header
and Bearer scheme in the response.
HTTP STATUS CODE
ERROR CODE
DESCRIPTION
CLIENT ACTION
400
invalid_request
The request is not wellformed. For example, it
might be missing a
parameter or using the
same parameter twice.
Fix the error and retry the
request. This type of error
should occur only during
development and be
detected in initial testing.
HTTP STATUS CODE
ERROR CODE
DESCRIPTION
CLIENT ACTION
401
invalid_token
The access token is missing,
invalid, or is revoked. The
value of the
error_description parameter
provides additional detail.
Request a new token from
the authorization server. If
the new token fails, an
unexpected error has
occurred. Send an error
message to the user and
retry after random delays.
403
insufficient_scope
The access token does not
contain the impersonation
permissions required to
access the resource.
Send a new authorization
request to the authorization
endpoint. If the response
contains the scope
parameter, use the scope
value in the request to the
resource.
403
insufficient_access
The subject of the token
does not have the
permissions that are
required to access the
resource.
Prompt the user to use a
different account or to
request permissions to the
specified resource.
Refreshing the access tokens
Access Tokens are short-lived and must be refreshed after they expire to continue accessing resources. You can
refresh the access_token by submitting another POST request to the /token endpoint, but this time providing
the refresh_token instead of the code .
Refresh tokens do not have specified lifetimes. Typically, the lifetimes of refresh tokens are relatively long.
However, in some cases, refresh tokens expire, are revoked, or lack sufficient privileges for the desired action.
Your application needs to expect and handle errors returned by the token issuance endpoint correctly.
When you receive a response with a refresh token error, discard the current refresh token and request a new
authorization code or access token. In particular, when using a refresh token in the Authorization Code Grant
flow, if you receive a response with the interaction_required or invalid_grant error codes, discard the refresh
token and request a new authorization code.
A sample request to the tenant-specific endpoint (you can also use the common endpoint) to get a new
access token using a refresh token looks like this:
// Line breaks for legibility only
POST /{tenant}/oauth2/token HTTP/1.1
Host: https://login.microsoftonline.com
Content-Type: application/x-www-form-urlencoded
client_id=6731de76-14a6-49ae-97bc-6eba6914391e
&refresh_token=OAAABAAAAiL9Kn2Z27UubvWFPbm0gLWQJVzCTE9UkP3pSx1aXxUjq...
&grant_type=refresh_token
&resource=https%3A%2F%2Fservice.contoso.com%2F
&client_secret=JqQX2PNo9bpM0uEihUPzyrh
// NOTE: Only required for web apps
PARAMETER
DESCRIPTION
access_token
The new access token that was requested.
PARAMETER
DESCRIPTION
expires_in
The remaining lifetime of the token in seconds. A typical
value is 3600 (one hour).
expires_on
The date and time on which the token expires. The date is
represented as the number of seconds from 1970-0101T0:0:0Z UTC until the expiration time.
refresh_token
A new OAuth 2.0 refresh_token that can be used to request
new access tokens when the one in this response expires.
resource
Identifies the secured resource that the access token can be
used to access.
scope
Impersonation permissions granted to the native client
application. The default permission is user_impersonation.
The owner of the target resource can register alternate
values in Azure AD.
token_type
The token type. The only supported value is bearer.
Successful response
A successful token response will look like:
{
"token_type": "Bearer",
"expires_in": "3600",
"expires_on": "1460404526",
"resource": "https://service.contoso.com/",
"access_token":
"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik5HVEZ2ZEstZnl0aEV1THdqcHdBSk9NOW4tQSJ9.eyJhdWQiOiJodHRwczovL
3NlcnZpY2UuY29udG9zby5jb20vIiwiaXNzIjoiaHR0cHM6Ly9zdHMud2luZG93cy5uZXQvN2ZlODE0NDctZGE1Ny00Mzg1LWJlY2ItNmRl
NTdmMjE0NzdlLyIsImlhdCI6MTM4ODQ0MDg2MywibmJmIjoxMzg4NDQwODYzLCJleHAiOjEzODg0NDQ3NjMsInZlciI6IjEuMCIsInRpZCI
6IjdmZTgxNDQ3LWRhNTctNDM4NS1iZWNiLTZkZTU3ZjIxNDc3ZSIsIm9pZCI6IjY4Mzg5YWUyLTYyZmEtNGIxOC05MWZlLTUzZGQxMDlkNz
RmNSIsInVwbiI6ImZyYW5rbUBjb250b3NvLmNvbSIsInVuaXF1ZV9uYW1lIjoiZnJhbmttQGNvbnRvc28uY29tIiwic3ViIjoiZGVOcUlqO
UlPRTlQV0pXYkhzZnRYdDJFYWJQVmwwQ2o4UUFtZWZSTFY5OCIsImZhbWlseV9uYW1lIjoiTWlsbGVyIiwiZ2l2ZW5fbmFtZSI6IkZyYW5r
IiwiYXBwaWQiOiIyZDRkMTFhMi1mODE0LTQ2YTctODkwYS0yNzRhNzJhNzMwOWUiLCJhcHBpZGFjciI6IjAiLCJzY3AiOiJ1c2VyX2ltcGV
yc29uYXRpb24iLCJhY3IiOiIxIn0.JZw8jC0gptZxVC7l5sFkdnJgP3_tRjeQEPgUn28XctVe3QqmheLZw7QVZDPCyGycDWBaqy7FLpSekET_BftDkewRhyHk9FW_KeEz0ch2c3i08NGNDbr6XYGVa
yNuSesYk5Aw_p3ICRlUV1bqEwkJkzs9EEkQg4hbefqJS6yS1HoV_2EsEhpd_wCQpxK89WPs3hLYZETRJtG5kvCCEOvSHXmDE6eTHGTnEgsIk-UlPe275Dvou4gEAwLofhLDQbMSjnlV5VLsjimNBVcSRFShoxmQwBJR_b2011Y5IuD6St5zPnzruBbZYkGNurQK63TJPWmRd3mbJsGM0mf3C
UQ",
"refresh_token": "AwABAAAAv YNqmf9SoAylD1PycGCB90xzZeEDg6oBzOIPfYsbDWNf621pKo2Q3GGTHYlmNfwocOlrxK69hkha2CF12azM_NYhgO668yfcUl4VBbiSHZyd1NVZG5QTIOcbObu3qnLutbpadZGAxqjIbMkQ2bQS09fTrjMBtDE3D6kSMIodpCec
oANon9b0LATkpitimVCrl PM1KaPlrEqdFSBzjqfTGAMxZGUTdM0t4B4rTfgV29ghDOHRc2BC_hHeJaJICqjZ3mY2b_YNqmf9SoAylD1PycGCB90xzZeEDg6oBzOIPfYsbDWNf621pKo2Q3GGTHYlmNfwocOlrxK69hkha2CF12azM_NYhgO668yfmVCrl-NyfN3oyG4ZCWu18M9-vEou4Sq-1oMDzExgAf61noxzkNiaTecMVe5cq6wHqYQjfV9DOz4lbceuYCAA"
}
Error response
A sample error response could look like this:
{
"error": "invalid_resource",
"error_description": "AADSTS50001: The application named https://foo.microsoft.com/mail.read was not
found in the tenant named 295e01fc-0c56-4ac3-ac57-5d0ed568f872. This can happen if the application has not
been installed by the administrator of the tenant or consented to by any user in the tenant. You might
have sent your authentication request to the wrong tenant.\r\nTrace ID: ef1f89f6-a14f-49de-986861bd4072f0a9\r\nCorrelation ID: b6908274-2c58-4e91-aea9-1f6b9c99347c\r\nTimestamp: 2016-04-11 18:59:01Z",
"error_codes": [
50001
],
"timestamp": "2016-04-11 18:59:01Z",
"trace_id": "ef1f89f6-a14f-49de-9868-61bd4072f0a9",
"correlation_id": "b6908274-2c58-4e91-aea9-1f6b9c99347c"
}
PARAMETER
DESCRIPTION
error
An error code string that can be used to classify types of
errors that occur, and can be used to react to errors.
error_description
A specific error message that can help a developer identify
the root cause of an authentication error.
error_codes
A list of STS-specific error codes that can help in diagnostics.
timestamp
The time at which the error occurred.
trace_id
A unique identifier for the request that can help in
diagnostics.
correlation_id
A unique identifier for the request that can help in
diagnostics across components.
For a description of the error codes and the recommended client action, see Error codes for token endpoint
errors.
Service to service calls using client credentials
2/13/2017 • 2 min to read • Edit Online
The OAuth 2.0 Client Credentials Grant Flow permits a web service (a confidential client) to use its own
credentials to authenticate when calling another web service, instead of impersonating a user. In this scenario, the
client is typically a middle-tier web service, a daemon service, or web site.
Client credentials grant flow diagram
The following diagram explains how the client credentials grant flow works in Azure Active Directory (Azure AD).
1.
2.
3.
4.
The client application authenticates to the Azure AD token issuance endpoint and requests an access token.
The Azure AD token issuance endpoint issues the access token.
The access token is used to authenticate to the secured resource.
Data from the secured resource is returned to the web application.
Register the Services in Azure AD
Register both the calling service and the receiving service in Azure Active Directory (Azure AD). For detailed
instructions, see Integrating applications with Azure Active Directory.
Request an Access Token
To request an access token, use an HTTP POST to the tenant-specific Azure AD endpoint.
https://login.microsoftonline.com/<tenant id>/oauth2/token
Service-to-service access token request
A service-to-service access token request contains the following parameters.
PARAMETER
response_type
DESCRIPTION
required
Specifies the requested response type.
In a Client Credentials Grant flow, the
value must be client_credentials.
PARAMETER
DESCRIPTION
client_id
required
Specifies the Azure AD client id of the
calling web service. To find the calling
application's client ID, in the Azure
Management Portal, click Active
Directory, click the directory, click the
application, and then click Configure.
client_secret
required
Enter a key registered for the calling
web service in Azure AD. To create a
key, in the Azure Management Portal,
click Active Directory, click the
directory, click the application, and then
click Configure.
resource
required
Enter the App ID URI of the receiving
web service. To find the App ID URI, in
the Azure Management Portal, click
Active Directory, click the directory,
click the application, and then click
Configure.
Example
The following HTTP POST requests an access token for the https://service.contoso.com/ web service. The
client_id identifies the web service that requests the access token.
POST contoso.com/oauth2/token HTTP/1.1
Host: login.microsoftonline.com
Content-Type: application/x-www-form-urlencoded
grant_type=client_credentials&client_id=625bc9f6-3bf6-4b6d-94bae97cf07a22de&client_secret=qkDwDJlDfig2IpeuUZYKH1Wb8q1V0ju6sILxQQqhJ+s=&resource=https%3A%2F%2Fservice.contoso
.com%2F
Service-to-Service Access Token Response
A success response contains a JSON OAuth 2.0 response with the following parameters.
PARAMETER
DESCRIPTION
access_token
The requested access token. The calling web service can use
this token to authenticate to the receiving web service.
access_type
Indicates the token type value. The only type that Azure AD
supports is Bearer. For more information about bearer
tokens, see The OAuth 2.0 Authorization Framework: Bearer
Token Usage (RFC 6750).
expires_in
How long the access token is valid (in seconds).
expires_on
The time when the access token expires. The date is
represented as the number of seconds from 1970-0101T0:0:0Z UTC until the expiration time. This value is used to
determine the lifetime of cached tokens.
PARAMETER
DESCRIPTION
resource
The App ID URI of the receiving web service.
Example
The following example shows a success response to a request for an access token to a web service.
{
"access_token":"eyJhbGciOiJSUzI1NiIsIng1dCI6IjdkRC1nZWNOZ1gxWmY3R0xrT3ZwT0IyZGNWQSIsInR5cCI6IkpXVCJ9.eyJhdWQiO
iJodHRwczovL3NlcnZpY2UuY29udG9zby5jb20vIiwiaXNzIjoiaHR0cHM6Ly9zdHMud2luZG93cy5uZXQvN2ZlODE0NDctZGE1Ny00Mzg1LWJ
lY2ItNmRlNTdmMjE0NzdlLyIsImlhdCI6MTM4ODQ0ODI2NywibmJmIjoxMzg4NDQ4MjY3LCJleHAiOjEzODg0NTIxNjcsInZlciI6IjEuMCIsI
nRpZCI6IjdmZTgxNDQ3LWRhNTctNDM4NS1iZWNiLTZkZTU3ZjIxNDc3ZSIsIm9pZCI6ImE5OTE5MTYyLTkyMTctNDlkYS1hZTIyLWYxMTM3YzI
1Y2RlYSIsInN1YiI6ImE5OTE5MTYyLTkyMTctNDlkYS1hZTIyLWYxMTM3YzI1Y2RlYSIsImlkcCI6Imh0dHBzOi8vc3RzLndpbmRvd3MubmV0L
zdmZTgxNDQ3LWRhNTctNDM4NS1iZWNiLTZkZTU3ZjIxNDc3ZS8iLCJhcHBpZCI6ImQxN2QxNWJjLWM1NzYtNDFlNS05MjdmLWRiNWYzMGRkNTh
mMSIsImFwcGlkYWNyIjoiMSJ9.aqtfJ7G37CpKV901Vm9sGiQhde0WMg6luYJR4wuNR2ffaQsVPPpKirM5rbc6o5CmW1OtmaAIdwDcL6i9ZT9o
oIIicSRrjCYMYWHX08ip-tj-uWUihGztI02xKdWiycItpWiHxapQm0a8Ti1CWRjJghORC1B1-fah_yWx6Cjuf4QE8xJcuZHX0pVZNPX22PHYV5KmvPTq2HtIqdboKyZy3Y4y3geOrRIFElZYoqjqSv5q9Jgtj5ERsNQIjefpyxW3EwPtFqMcDm4ebiAEpoEWRN4QYOMxnC9OUBeG9oLA0lTfmhgHLA
tvJogJcYFzwngTsVo6HznsvPWy7UP3MINA",
"token_type":"Bearer",
"expires_in":"3599",
"expires_on":"1388452167",
"resource":"https://service.contoso.com/"
}
See also
OAuth 2.0 in Azure AD
Service to service calls using delegated user identity
in the On-Behalf-Of flow
5/4/2017 • 6 min to read • Edit Online
The OAuth 2.0 On-Behalf-Of flow serves the use case where an application invokes a service/web API, which in turn
needs to call another service/web API. The idea is to propagate the user’s authentication through the request chain.
For the middle-tier service to make authenticated requests to the downstream service, it needs to secure an access
token from Azure Active Directory (Azure AD), on behalf of the user.
On-Behalf-Of flow diagram
Assume that the user has been authenticated on an application using the OAuth 2.0 authorization code grant flow.
At this point, the application has an access token (token A) with the user’s claims and consent to access the middletier web API (API A). Now, API A needs to make an authenticated request to the downstream web API (API B).
The steps that follow constitute the On-Behalf-Of flow and are explained with the help of the following diagram.
1. The client application makes a request to API A with the token A set in the authorization header.
2. API A authenticates to the Azure AD token issuance endpoint and requests a token to access API B.
3. The Azure AD token issuance endpoint validates API A's credentials with token A and issues the access token for
API B (token B).
4. The token B is set in the authorization header of the request to API B.
5. Data from the secured resource is returned by API B.
Register the application and service in Azure AD
Register both the client application and the middle-tier service in Azure AD.
Register the middle -tier service
1. Sign in to the Azure portal.
2. On the top bar, click on your account and under the Directory list, choose the Active Directory tenant where you
wish to register your application.
3. Click on More Services in the left hand nav, and choose Azure Active Directory.
4. Click on App registrations and choose New application registration.
5. Enter a friendly name for the application, and select the application type. Based on the application type set the
sign-on URL or redirect URL to the base URL. Click on Create to create the application.
6. While still in the Azure portal, choose your application and click on Settings. From the Settings menu, choose
Keys and add a key - select a key duration of either 1 year or 2 years. When you save this page, the key value
will be displayed, copy and save the value in a safe location - you will need this key later to configure the
application settings in your implementation - this key value will not be displayed again, nor retrievable by any
other means, so please record it as soon as it is visible from the Azure Portal.
Register the client application
1. Sign in to the Azure portal.
2. On the top bar, click on your account and under the Directory list, choose the Active Directory tenant where you
wish to register your application.
3. Click on More Services in the left hand nav, and choose Azure Active Directory.
4. Click on App registrations and choose New application registration.
5. Enter a friendly name for the application, and select the application type. Based on the application type set the
sign-on URL or redirect URL to the base URL. Click on Create to create the application.
6. Configure Permissions for your application - in the Settings menu, choose the Required permissions section,
click on Add, then Select an API, and type the name of the middle-tier service in the textbox. Then, click on
Select Permissions and select 'Access service name'.
Configure known client applications
In this scenario, the middle-tier service has no user interaction to obtain the user's consent to access the
downstream API. Therefore, the option to grant access to the downstream API must be presented upfront as a part
of the consent step during authentication. To achieve this, follow the steps below to explicitly bind the client app's
registration in Azure AD with the registration of the middle-tier service, which merges the consent required by both
the client and middle-tier into a single dialog.
1. Navigate to the middle-tier service registration, and click on Manifest to open the manifest editor.
2. In the manifest, locate the knownClientApplications array property, and add the Client ID of the client application
as an element.
3. Save the manifest by clicking the save button.
Service to service access token request
To request an access token, make an HTTP POST to the tenant-specific Azure AD endpoint with the following
parameters.
https://login.microsoftonline.com/<tenant>/oauth2/token
PARAMETER
DESCRIPTION
PARAMETER
DESCRIPTION
grant_type
required
The type of the token request. For a
request using a JWT, the value must be
urn:ietf:params:oauth:granttype:jwt-bearer.
assertion
required
The value of the token used in the
request.
client_id
required
The App ID assigned to the calling
service during registration with Azure
AD. To find the App ID in the Azure
Management Portal, click Active
Directory, click the directory, and then
click the application name.
client_secret
required
The key registered for the calling service
in Azure AD. This value should have
been noted at the time of registration.
resource
required
The App ID URI of the receiving service
(secured resource). To find the App ID
URI, in the Azure Management Portal,
click Active Directory, click the
directory, click the application name,
click All settings and then click
Properties.
requested_token_use
required
Specifies how the request should be
processed. In the On-Behalf-Of flow,
the value must be on_behalf_of.
scope
required
A space separated list of scopes of the
access request. For OpenID Connect,
the scope openid must be specified.
Example
The following HTTP POST requests an access token for the https://graph.windows.net web API. The
identifies the service that requests the access token.
client_id
POST /oauth2/token HTTP/1.1
Host: login.microsoftonline.com
Content-Type: application/x-www-form-urlencoded
resource=https%3A%2F%2Fgraph.windows.net&client_id=625391af-c675-43e5-8e44edd3e30ceb15&client_secret=0Y1W%2BY3yYb3d9N8vSjvm8WrGzVZaAaHbHHcGbcgG%2BoI%3D&grant_type=urn%3Aietf%3Aparams%3A
oauth%3Agrant-type%3Ajwtbearer&assertion=eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6InowMzl6ZHNGdWl6cEJmQlZLMVRuMjVRSFlPMCIsImtpZCI6In
owMzl6ZHNGdWl6cEJmQlZLMVRuMjVRSFlPMCJ9.eyJhdWQiOiJodHRwczovL2Rkb2JhbGlhbm91dGxvb2sub25taWNyb3NvZnQuY29tLzE5MjNm
ODYyLWU2ZGMtNDFhMy04MWRhLTgwMmJhZTAwYWY2ZCIsImlzcyI6Imh0dHBzOi8vc3RzLndpbmRvd3MubmV0LzI2MDM5Y2NlLTQ4OWQtNDAwMi0
4MjkzLTViMGM1MTM0ZWFjYi8iLCJpYXQiOjE0OTM0MjMxNTIsIm5iZiI6MTQ5MzQyMzE1MiwiZXhwIjoxNDkzNDY2NjUyLCJhY3IiOiIxIiwiYW
lvIjoiWTJaZ1lCRFF2aTlVZEc0LzM0L3dpQndqbjhYeVp4YmR1TFhmVE1QeG8yYlN2elgreHBVQSIsImFtciI6WyJwd2QiXSwiYXBwaWQiOiJiM
zE1MDA3OS03YmViLTQxN2YtYTA2YS0zZmRjNzhjMzI1NDUiLCJhcHBpZGFjciI6IjAiLCJlX2V4cCI6MzAyNDAwLCJmYW1pbHlfbmFtZSI6IlRl
c3QiLCJnaXZlbl9uYW1lIjoiTmF2eWEiLCJpcGFkZHIiOiIxNjcuMjIwLjEuMTc3IiwibmFtZSI6Ik5hdnlhIFRlc3QiLCJvaWQiOiIxY2Q0YmN
hYy1iODA4LTQyM2EtOWUyZi04MjdmYmIxYmI3MzkiLCJwbGF0ZiI6IjMiLCJzY3AiOiJ1c2VyX2ltcGVyc29uYXRpb24iLCJzdWIiOiJEVXpYbk
dKMDJIUk0zRW5pbDFxdjZCakxTNUllQy0tQ2ZpbzRxS1MzNEc4IiwidGlkIjoiMjYwMzljY2UtNDg5ZC00MDAyLTgyOTMtNWIwYzUxMzRlYWNiI
iwidW5pcXVlX25hbWUiOiJuYXZ5YUBkZG9iYWxpYW5vdXRsb29rLm9ubWljcm9zb2Z0LmNvbSIsInVwbiI6Im5hdnlhQGRkb2JhbGlhbm91dGxv
b2sub25taWNyb3NvZnQuY29tIiwidmVyIjoiMS4wIn0.R-KeXO7lK0r5uLwxB8g5CrcPAwRln5SccJCfEjU6IUqpqcjWcDzeDdNOySiVPDU_ZU5knJmzRCF8fcjFtPsaA4R7vdIEbDuOur15FXSvE8FvVSjP_49
OH6hBYqoSUAslN3FMfbO6Z8YfCIY4tSOB2I6ahQ_x4ZWFWglC3w5mK_4iX81bqi95eV4RUKefUuHhQDXtWhrSgIEC0YiluMvA4TnaJdLq_tWXIc4_Tq_KfpkvI004ONKgU7EAMEr1wZ4aDcJV2yf22gQ1sCSig6EGSTmm
zDuEPsYiyd4NhidRZJP4HiiQh-hePBQsgcSgYGvz9wC6n57ufYKh2wm_Ti3Q&requested_token_use=on_behalf_of&scope=openid
Service to service access token response
A success response contains a JSON OAuth 2.0 response with the following parameters.
PARAMETER
DESCRIPTION
token_type
Indicates the token type value. The only type that Azure AD
supports is Bearer. For more information about bearer
tokens, see the OAuth 2.0 Authorization Framework: Bearer
Token Usage (RFC 6750).
scope
The scope of access to the secured resource granted to the
application.
expires_in
The length of time the access token is valid (in seconds).
expires_on
The time when the access token expires. The date is
represented as the number of seconds from 1970-0101T0:0:0Z UTC until the expiration time. This value is used to
determine the lifetime of cached tokens.
resource
The App ID URI of the receiving service (secured resource).
access_token
The requested access token. The calling service can use this
token to authenticate to the receiving service.
id_token
The requested id token. The calling service can use this to
verify the user's identity and begin a session with the user.
refresh_token
The refresh token for the requested access token. The calling
service can use this token to request another access token
after the current access token expires.
Success response example
The following example shows a success response to a request for an access token for the https://graph.windows.net
web API.
{
"token_type":"Bearer",
"scope":"User.Read",
"expires_in":"43482",
"ext_expires_in":"302683",
"expires_on":"1493466951",
"not_before":"1493423168",
"resource":"https://graph.windows.net",
"access_token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6InowMzl6ZHNGdWl6cEJmQlZLMVRuMjVRSFlPMCIsImtpZCI6Ino
wMzl6ZHNGdWl6cEJmQlZLMVRuMjVRSFlPMCJ9.eyJhdWQiOiJodHRwczovL2dyYXBoLndpbmRvd3MubmV0IiwiaXNzIjoiaHR0cHM6Ly9zdHMud
2luZG93cy5uZXQvMjYwMzljY2UtNDg5ZC00MDAyLTgyOTMtNWIwYzUxMzRlYWNiLyIsImlhdCI6MTQ5MzQyMzE2OCwibmJmIjoxNDkzNDIzMTY4
LCJleHAiOjE0OTM0NjY5NTEsImFjciI6IjEiLCJhaW8iOiJBU1FBMi84REFBQUE1NnZGVmp0WlNjNWdBVWwrY1Z0VFpyM0VvV2NvZEoveWV1S2Z
qcTZRdC9NPSIsImFtciI6WyJwd2QiXSwiYXBwaWQiOiI2MjUzOTFhZi1jNjc1LTQzZTUtOGU0NC1lZGQzZTMwY2ViMTUiLCJhcHBpZGFjciI6Ij
EiLCJlX2V4cCI6MzAyNjgzLCJmYW1pbHlfbmFtZSI6IlRlc3QiLCJnaXZlbl9uYW1lIjoiTmF2eWEiLCJpcGFkZHIiOiIxNjcuMjIwLjEuMTc3I
iwibmFtZSI6Ik5hdnlhIFRlc3QiLCJvaWQiOiIxY2Q0YmNhYy1iODA4LTQyM2EtOWUyZi04MjdmYmIxYmI3MzkiLCJwbGF0ZiI6IjMiLCJwdWlk
IjoiMTAwMzNGRkZBMTJFRDdGRSIsInNjcCI6IlVzZXIuUmVhZCIsInN1YiI6IjNKTUlaSWJlYTc1R2hfWHdDN2ZzX0JDc3kxa1l1ekZKLTUyVm1
Zd0JuM3ciLCJ0aWQiOiIyNjAzOWNjZS00ODlkLTQwMDItODI5My01YjBjNTEzNGVhY2IiLCJ1bmlxdWVfbmFtZSI6Im5hdnlhQGRkb2JhbGlhbm
91dGxvb2sub25taWNyb3NvZnQuY29tIiwidXBuIjoibmF2eWFAZGRvYmFsaWFub3V0bG9vay5vbm1pY3Jvc29mdC5jb20iLCJ1dGkiOiJ4Q3dme
mhhLVAwV0pRT0x4Q0dnS0FBIiwidmVyIjoiMS4wIn0.cqmUVjfVbqWsxJLUI1Z4FRx1mNQAHP-L0F4EMN09r8FY9bIKeO0q1eTdP11Nkj_k4BmtaZsTcK_mUygdMqEp9AfyVyA1HYvokcgGCW_Z6DMlVGqlIU4ssEkL9abgl1REHElPhpwBFFBBenOk9iHddD1GddTn6vJbK
C3qAaNM5VarjSPu50bVvCrqKNvFixTb5bbdnSzQr6n6ACiEimiI1aNOPR2DeKUyWBPaQcU5EAK0ef5IsVJC1yaYDlAcUYIILMDLCD9ebjsy0t9pj_7lvjzUSrbMdSCCdzCqez_MSNxrk1Nu9Aecug
kBYp3UVUZOIyythVrj6-sVvLZKUutQ",
"refresh_token":"AQABAAAAAABnfiG-mA6NTae7CdWW7QfdjKGu9t1scy_TDEmLi4eLQMjJGt_nAoVu6A4oSu1KsRiz8XyQIPKQxSGfbf2FoSKhm2K8TYzbJuswYusQpJaHUQnSqEvdaCeFuqXHBv84wjFhuanzF9dQZB_Ng5za9xKlUENrNtlq9XuLNVKzxEyeUM7JyxzdY7JiEphWImwgOYf6II
316d0Z6-H3oYsFezf4Xsjz-MOBYEov0P64UaB5nJMvDyApV-NWpgklLASfNoSPGb67Bc02aFRZrm4kLkxTl6eKE6hSo0XU2z2t70stFJDxvNQobnvNHrAmBaHWPAcC3FGwFnBOojpZB2tzG1gLEbmdROVDp8kHEYAwnRK947Py12fJNKExUdN0njmXrKxNZ
_fEM33LHW1Tf4kMX_GvNmbWHtBnIyG0w5emb-b54ef5AwV5_tGUeivTCCysgucEc-S7G8Cz0xNJ_BOiM_4bAv9iFmrm9STkltpz0Tftg8WKmaJiC0xXj6uTf4ZkX79mJJIuuM7XP4ARIcLpkktyg2Iym9jcZqymRkGH2Rm9sxBwC4eeZXM7M5a7TJ5CqOdfuE3sBPq40RdEWMFLcrAzFvP0VDR8NKHIrPR1AcUruat9DETmTNJukdlJN3O41nWdZOVoJMuKN3uz2wQ2Ld1z0Mb9_6YfMox9KTJNzRzcL52r4V_y3kB6ekaOZ9wQ3HxGBQ4zFt-2U0mSszIAA",
"id_token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJub25lIn0.eyJhdWQiOiI2MjUzOTFhZi1jNjc1LTQzZTUtOGU0NC1lZGQzZTMwY2ViMTUiLCJ
pc3MiOiJodHRwczovL3N0cy53aW5kb3dzLm5ldC8yNjAzOWNjZS00ODlkLTQwMDItODI5My01YjBjNTEzNGVhY2IvIiwiaWF0IjoxNDkzNDIzMT
Y4LCJuYmYiOjE0OTM0MjMxNjgsImV4cCI6MTQ5MzQ2Njk1MSwiYW1yIjpbInB3ZCJdLCJmYW1pbHlfbmFtZSI6IlRlc3QiLCJnaXZlbl9uYW1lI
joiTmF2eWEiLCJpcGFkZHIiOiIxNjcuMjIwLjEuMTc3IiwibmFtZSI6Ik5hdnlhIFRlc3QiLCJvaWQiOiIxY2Q0YmNhYy1iODA4LTQyM2EtOWUy
Zi04MjdmYmIxYmI3MzkiLCJwbGF0ZiI6IjMiLCJzdWIiOiJEVXpYbkdKMDJIUk0zRW5pbDFxdjZCakxTNUllQy0tQ2ZpbzRxS1MzNEc4IiwidGl
kIjoiMjYwMzljY2UtNDg5ZC00MDAyLTgyOTMtNWIwYzUxMzRlYWNiIiwidW5pcXVlX25hbWUiOiJuYXZ5YUBkZG9iYWxpYW5vdXRsb29rLm9ubW
ljcm9zb2Z0LmNvbSIsInVwbiI6Im5hdnlhQGRkb2JhbGlhbm91dGxvb2sub25taWNyb3NvZnQuY29tIiwidXRpIjoieEN3ZnpoYS1QMFdKUU9Me
ENHZ0tBQSIsInZlciI6IjEuMCJ9."
}
Error response example
An error response is returned by Azure AD token endpoint when trying to acquire an access token for the
downstream API, if the downstream API has a conditional access policy such as multi-factor authentication set on it.
The middle-tier service should surface this error to the client application so that the client application can provide
the user interaction to satisfy the conditional access policy.
{
"error":"interaction_required",
"error_description":"AADSTS50079: Due to a configuration change made by your administrator, or because you
moved to a new location, you must enroll in multi-factor authentication to access 'bf8d80f9-9098-4972-b203500f535113b1'.\r\nTrace ID: b72a68c3-0926-4b8e-bc35-3150069c2800\r\nCorrelation ID: 73d656cf-54b1-4eb2-b42926d8165a52d7\r\nTimestamp: 2017-05-01 22:43:20Z",
"error_codes":[50079],
"timestamp":"2017-05-01 22:43:20Z",
"trace_id":"b72a68c3-0926-4b8e-bc35-3150069c2800",
"correlation_id":"73d656cf-54b1-4eb2-b429-26d8165a52d7",
"claims":"{\"access_token\":{\"polids\":{\"essential\":true,\"values\":[\"9ab03e19-ed42-4168-b6b77001fb3e933a\"]}}}"
}
Use the access token to access the secured resource
Now the service can use the token acquired above to make authenticated requests to the web API, by setting the
token in the Authorization header.
Example
GET /me?api-version=2013-11-08 HTTP/1.1
Host: graph.windows.net
Authorization: Bearer
eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6InowMzl6ZHNGdWl6cEJmQlZLMVRuMjVRSFlPMCIsImtpZCI6InowMzl6ZHNGdWl6cEJ
mQlZLMVRuMjVRSFlPMCJ9.eyJhdWQiOiJodHRwczovL2dyYXBoLndpbmRvd3MubmV0IiwiaXNzIjoiaHR0cHM6Ly9zdHMud2luZG93cy5uZXQvM
jYwMzljY2UtNDg5ZC00MDAyLTgyOTMtNWIwYzUxMzRlYWNiLyIsImlhdCI6MTQ5MzQyMzE2OCwibmJmIjoxNDkzNDIzMTY4LCJleHAiOjE0OTM0
NjY5NTEsImFjciI6IjEiLCJhaW8iOiJBU1FBMi84REFBQUE1NnZGVmp0WlNjNWdBVWwrY1Z0VFpyM0VvV2NvZEoveWV1S2ZqcTZRdC9NPSIsImF
tciI6WyJwd2QiXSwiYXBwaWQiOiI2MjUzOTFhZi1jNjc1LTQzZTUtOGU0NC1lZGQzZTMwY2ViMTUiLCJhcHBpZGFjciI6IjEiLCJlX2V4cCI6Mz
AyNjgzLCJmYW1pbHlfbmFtZSI6IlRlc3QiLCJnaXZlbl9uYW1lIjoiTmF2eWEiLCJpcGFkZHIiOiIxNjcuMjIwLjEuMTc3IiwibmFtZSI6Ik5hd
nlhIFRlc3QiLCJvaWQiOiIxY2Q0YmNhYy1iODA4LTQyM2EtOWUyZi04MjdmYmIxYmI3MzkiLCJwbGF0ZiI6IjMiLCJwdWlkIjoiMTAwMzNGRkZB
MTJFRDdGRSIsInNjcCI6IlVzZXIuUmVhZCIsInN1YiI6IjNKTUlaSWJlYTc1R2hfWHdDN2ZzX0JDc3kxa1l1ekZKLTUyVm1Zd0JuM3ciLCJ0aWQ
iOiIyNjAzOWNjZS00ODlkLTQwMDItODI5My01YjBjNTEzNGVhY2IiLCJ1bmlxdWVfbmFtZSI6Im5hdnlhQGRkb2JhbGlhbm91dGxvb2sub25taW
Nyb3NvZnQuY29tIiwidXBuIjoibmF2eWFAZGRvYmFsaWFub3V0bG9vay5vbm1pY3Jvc29mdC5jb20iLCJ1dGkiOiJ4Q3dmemhhLVAwV0pRT0x4Q
0dnS0FBIiwidmVyIjoiMS4wIn0.cqmUVjfVbqWsxJLUI1Z4FRx1mNQAHP-L0F4EMN09r8FY9bIKeO0q1eTdP11Nkj_k4BmtaZsTcK_mUygdMqEp9AfyVyA1HYvokcgGCW_Z6DMlVGqlIU4ssEkL9abgl1REHElPhpwBFFBBenOk9iHddD1GddTn6vJbK
C3qAaNM5VarjSPu50bVvCrqKNvFixTb5bbdnSzQr6n6ACiEimiI1aNOPR2DeKUyWBPaQcU5EAK0ef5IsVJC1yaYDlAcUYIILMDLCD9ebjsy0t9pj_7lvjzUSrbMdSCCdzCqez_MSNxrk1Nu9Aecug
kBYp3UVUZOIyythVrj6-sVvLZKUutQ
Next steps
Learn more about the OAuth2.0 protocol and another way to perform service to service auth using client
credentials.
Service to service auth using OAuth 2.0 client credentials grant in Azure AD
OAuth 2.0 in Azure AD
Azure AD token reference
2/17/2017 • 15 min to read • Edit Online
Azure Active Directory (Azure AD) emits several types of security tokens in the processing of each authentication flow. This
document describes the format, security characteristics, and contents of each type of token.
Types of tokens
Azure AD supports the OAuth 2.0 authorization protocol, which makes use of both access_tokens and refresh_tokens. It also
supports authentication and sign-in via OpenID Connect, which introduces a third type of token, the id_token. Each of these tokens is
represented as a "bearer token".
A bearer token is a lightweight security token that grants the “bearer” access to a protected resource. In this sense, the “bearer” is
any party that can present the token. Though authentication with Azure AD is required in order to receive a bearer token, steps must
be taken to secure the token, to prevent interception by an unintended party. Because bearer tokens do not have a built-in
mechanism to prevent unauthorized parties from using them, they must be transported in a secure channel such as transport layer
security (HTTPS). If a bearer token is transmitted in the clear, a man-in the middle attack can be used to acquire the token and gain
unauthorized access to a protected resource. The same security principles apply when storing or caching bearer tokens for later use.
Always ensure that your app transmits and stores bearer tokens in a secure manner. For more security considerations on bearer
tokens, see RFC 6750 Section 5.
Many of the tokens issued by Azure AD are implemented as JSON Web Tokens, or JWTs. A JWT is a compact, URL-safe means of
transferring information between two parties. The information contained in JWTs are known as "claims", or assertions of
information about the bearer and subject of the token. The claims in JWTs are JSON objects encoded and serialized for transmission.
Since the JWTs issued by Azure AD are signed, but not encrypted, you can easily inspect the contents of a JWT for debugging
purposes. There are several tools available for doing so, such as jwt.calebb.net. For more information on JWTs, you can refer to the
JWT specification.
Id_tokens
Id_tokens are a form of sign-in security token that your app receives when performing authentication using OpenID Connect. They
are represented as JWTs, and contain claims that you can use for signing the user into your app. You can use the claims in an
id_token as you see fit - commonly they are used for displaying account information or making access control decisions in an app.
Id_tokens are signed, but not encrypted at this time. When your app receives an id_token, it must validate the signature to prove the
token's authenticity and validate a few claims in the token to prove its validity. The claims validated by an app vary depending on
scenario requirements, but there are some common claim validations that your app must perform in every scenario.
See the following section for information on id_tokens claims, as well as a sample id_token. Note that the claims in id_tokens are not
returned in any particular order. In addition, new claims can be introduced into id_tokens at any point in time - your app should not
break as new claims are introduced. The following list includes the claims that your app can reliably interpret at the time of this
writing. If necessary, even more detail can be found in the OpenID Connect specification.
Sample id_token
eyJ0eXAiOiJKV1QiLCJhbGciOiJub25lIn0.eyJhdWQiOiIyZDRkMTFhMi1mODE0LTQ2YTctODkwYS0yNzRhNzJhNzMwOWUiLCJpc3MiOiJodHRwczovL3N0cy53aW5
kb3dzLm5ldC83ZmU4MTQ0Ny1kYTU3LTQzODUtYmVjYi02ZGU1N2YyMTQ3N2UvIiwiaWF0IjoxMzg4NDQwODYzLCJuYmYiOjEzODg0NDA4NjMsImV4cCI6MTM4ODQ0ND
c2MywidmVyIjoiMS4wIiwidGlkIjoiN2ZlODE0NDctZGE1Ny00Mzg1LWJlY2ItNmRlNTdmMjE0NzdlIiwib2lkIjoiNjgzODlhZTItNjJmYS00YjE4LTkxZmUtNTNkZ
DEwOWQ3NGY1IiwidXBuIjoiZnJhbmttQGNvbnRvc28uY29tIiwidW5pcXVlX25hbWUiOiJmcmFua21AY29udG9zby5jb20iLCJzdWIiOiJKV3ZZZENXUGhobHBTMVpz
Zjd5WVV4U2hVd3RVbTV5elBtd18talgzZkhZIiwiZmFtaWx5X25hbWUiOiJNaWxsZXIiLCJnaXZlbl9uYW1lIjoiRnJhbmsifQ.
TIP
For practice, try inspecting the claims in the sample id_token by pasting it into calebb.net.
Claims in id_tokens
JWT CLAIM
NAME
DESCRIPTION
JWT CLAIM
appid
NAME
DESCRIPTION
Application ID
Identifies the application that is using the
token to access a resource. The application can
act as itself or on behalf of a user. The
application ID typically represents an
application object, but it can also represent a
service principal object in Azure AD.
Example JWT Value:
"appid":"15CB020F-3984-482A-864D1D92265E8268"
aud
Audience
The intended recipient of the token. The
application that receives the token must verify
that the audience value is correct and reject
any tokens intended for a different audience.
Example SAML Value:
<AudienceRestriction>
<Audience>
https://contoso.com
</Audience>
</AudienceRestriction>
Example JWT Value:
"aud":"https://contoso.com"
appidacr
Application Authentication Context Class
Reference
Indicates how the client was authenticated.
For a public client, the value is 0. If client ID
and client secret are used, the value is 1.
Example JWT Value:
"appidacr": "0"
acr
Authentication Context Class Reference
Indicates how the subject was authenticated,
as opposed to the client in the Application
Authentication Context Class Reference claim.
A value of "0" indicates the end-user
authentication did not meet the requirements
of ISO/IEC 29115.
Example JWT Value:
"acr": "0"
Authentication Instant
Records the date and time when
authentication occurred.
Example SAML Value:
<AuthnStatement AuthnInstant="2011-1229T05:35:22.000Z">
amr
Authentication Method
Identifies how the subject of the token was
authenticated.
Example SAML Value:
<AuthnContextClassRef>
http://schemas.microsoft.com/ws/2008/06/identity/claims/authenticationmethod/p
</AuthnContextClassRef>
Example JWT Value:
“amr”: ["pwd"]
JWT CLAIM
given_name
NAME
DESCRIPTION
First Name
Provides the first or "given" name of the user,
as set on the Azure AD user object.
Example SAML Value:
<Attribute
Name=”http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname”>
<AttributeValue>Frank<AttributeValue>
Example JWT Value:
"given_name": "Frank"
groups
Groups
Provides object IDs that represent the
subject's group memberships. These values
are unique (see Object ID) and can be safely
used for managing access, such as enforcing
authorization to access a resource. The groups
included in the groups claim are configured on
a per-application basis, through the
"groupMembershipClaims" property of the
application manifest. A value of null will
exclude all groups, a value of "SecurityGroup"
will include only Active Directory Security
Group memberships, and a value of "All" will
include both Security Groups and Office 365
Distribution Lists.
Example SAML Value:
<Attribute
Name="http://schemas.microsoft.com/ws/2008/06/identity/claims/groups">
<AttributeValue>07dd8a60-bf6d-4e17-8844230b77145381</AttributeValue>
Example JWT Value:
“groups”: ["0e129f5b-6b0a-4944-982d-f776045632af",
…]
idp
Identity Provider
Records the identity provider that
authenticated the subject of the token. This
value is identical to the value of the Issuer
claim unless the user account is in a different
tenant than the issuer.
Example SAML Value:
<Attribute Name=”
http://schemas.microsoft.com/identity/claims/identityprovider”>
<AttributeValue>https://sts.windows.net/cbb1a5acf33b-45fa-9bf5-f37db0fed422/<AttributeValue>
Example JWT Value:
"idp":”https://sts.windows.net/cbb1a5ac-f33b-45fa9bf5-f37db0fed422/”
iat
IssuedAt
Stores the time at which the token was issued.
It is often used to measure token freshness.
Example SAML Value:
<Assertion ID="_d5ec7a9b-8d8f-4b44-8c949812612142be" IssueInstant="2014-0106T20:20:23.085Z" Version="2.0"
xmlns="urn:oasis:names:tc:SAML:2.0:assertion">
Example JWT Value:
"iat": 1390234181
JWT CLAIM
iss
NAME
DESCRIPTION
Issuer
Identifies the security token service (STS) that
constructs and returns the token. In the
tokens that Azure AD returns, the issuer is
sts.windows.net. The GUID in the Issuer claim
value is the tenant ID of the Azure AD
directory. The tenant ID is an immutable and
reliable identifier of the directory.
Example SAML Value:
<Issuer>https://sts.windows.net/cbb1a5ac-f33b-45fa9bf5-f37db0fed422/</Issuer>
Example JWT Value:
"iss":”https://sts.windows.net/cbb1a5ac-f33b-45fa-9bf5f37db0fed422/”
family_name
Last Name
Provides the last name, surname, or family
name of the user as defined in the Azure AD
user object.
Example SAML Value:
<Attribute Name=”
http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname”>
<AttributeValue>Miller<AttributeValue>
Example JWT Value:
"family_name": "Miller"
unique_name
Name
Provides a human readable value that
identifies the subject of the token. This value is
not guaranteed to be unique within a tenant
and is designed to be used only for display
purposes.
Example SAML Value:
<Attribute
Name=”http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name”>
<AttributeValue>[email protected]<AttributeValue>
Example JWT Value:
"unique_name": "[email protected]"
oid
Object ID
Contains a unique identifier of an object in
Azure AD. This value is immutable and cannot
be reassigned or reused. Use the object ID to
identify an object in queries to Azure AD.
Example SAML Value:
<Attribute
Name="http://schemas.microsoft.com/identity/claims/objectidentifier">
<AttributeValue>528b2ac2-aa9c-45e1-88d4959b53bc7dd0<AttributeValue>
Example JWT Value:
"oid":"528b2ac2-aa9c-45e1-88d4-959b53bc7dd0"
JWT CLAIM
roles
NAME
DESCRIPTION
Roles
Represents all application roles that the
subject has been granted both directly and
indirectly through group membership and can
be used to enforce role-based access control.
Application roles are defined on a perapplication basis, through the appRoles
property of the application manifest. The
value property of each application role is the
value that appears in the roles claim.
Example SAML Value:
<Attribute
Name="http://schemas.microsoft.com/ws/2008/06/identity/claims/role">
<AttributeValue>Admin</AttributeValue>
Example JWT Value:
“roles”: ["Admin", … ]
scp
Scope
Indicates the impersonation permissions
granted to the client application. The default
permission is user_impersonation . The owner of
the secured resource can register additional
values in Azure AD.
Example JWT Value:
"scp": "user_impersonation"
sub
Subject
Identifies the principal about which the token
asserts information, such as the user of an
application. This value is immutable and
cannot be reassigned or reused, so it can be
used to perform authorization checks safely.
Because the subject is always present in the
tokens the Azure AD issues, we recommended
using this value in a general purpose
authorization system.
SubjectConfirmation is not a claim. It describes
how the subject of the token is verified.
Bearer indicates that the subject is confirmed
by their possession of the token.
Example SAML Value:
<Subject>
<NameID>S40rgb3XjhFTv6EQTETkEzcgVmToHKRkZUIsJlmLdVc</NameID>
<SubjectConfirmation
Method="urn:oasis:names:tc:SAML:2.0:cm:bearer" />
</Subject>
Example JWT Value:
"sub":"92d0312b-26b9-4887-a338-7b00fb3c5eab"
tid
Tenant ID
An immutable, non-reusable identifier that
identifies the directory tenant that issued the
token. You can use this value to access
tenant-specific directory resources in a multitenant application. For example, you can use
this value to identify the tenant in a call to the
Graph API.
Example SAML Value:
<Attribute
Name=”http://schemas.microsoft.com/identity/claims/tenantid”>
<AttributeValue>cbb1a5ac-f33b-45fa-9bf5f37db0fed422<AttributeValue>
Example JWT Value:
"tid":"cbb1a5ac-f33b-45fa-9bf5-f37db0fed422"
JWT CLAIM
nbf
,
exp
NAME
DESCRIPTION
Token Lifetime
Defines the time interval within which a token
is valid. The service that validates the token
should verify that the current date is within
the token lifetime, else it should reject the
token. The service might allow for up to five
minutes beyond the token lifetime range to
account for any differences in clock time ("time
skew") between Azure AD and the service.
Example SAML Value:
<Conditions
NotBefore="2013-03-18T21:32:51.261Z"
NotOnOrAfter="2013-03-18T22:32:51.261Z"
>
Example JWT Value:
"nbf":1363289634, "exp":1363293234
upn
User Principal Name
Stores the user name of the user principal.
Example JWT Value:
"upn": [email protected]
ver
Version
Stores the version number of the token.
Example JWT Value:
"ver": "1.0"
Access tokens
Upon successful authentication, Azure AD returns an access token, which can be used to access protected resources. The access
token is a base 64 encoded JSON Web Token (JWT) and its contents can be inspected by running it through a decoder.
If your app only uses access tokens to get access to APIs, you can (and should) treat access tokens as completely opaque - they are
just strings which your app can pass to resources in HTTP requests.
When you request an access token, Azure AD also returns some metadata about the access token for your app's consumption. This
information includes the expiry time of the access token and the scopes for which it is valid. This allows your app to perform
intelligent caching of access tokens without having to parse open the access token itself.
If your app is an API protected with Azure AD that expects access tokens in HTTP requests, then you should perform validation and
inspection of the tokens you receive. Your app should perform validation of the access token before using it to access resources. For
more information on validation, please see Validating Tokens.
For details on how to do this with .NET, see Protect a Web API using Bearer tokens from Azure AD.
Refresh tokens
Refresh tokens are security tokens, which your app can use to acquire new access tokens in an OAuth 2.0 flow. It allows your app to
achieve long-term access to resources on behalf of a user without requiring interaction by the user.
Refresh tokens are multi-resource. That is to say that a refresh token received during a token request for one resource can be
redeemed for access tokens to a completely different resource. To do this, set the resource parameter in the request to the targeted
resource.
Refresh tokens are completely opaque to your app. They are long-lived, but your app should not be written to expect that a refresh
token will last for any period of time. Refresh tokens can be invalidated at any moment in time for a variety of reasons. The only way
for your app to know if a refresh token is valid is to attempt to redeem it by making a token request to Azure AD token endpoint.
When you redeem a refresh token for a new access token, you will receive a new refresh token in the token response. You should
save the newly issued refresh token, replacing the one you used in the request. This will guarantee that your refresh tokens remain
valid for as long as possible.
Validating tokens
In order to validate an id_token or an access_token, your app should validate both the token's signature and the claims. In order to
validate access tokens, your app should also validate the issuer, the audience and the signing tokens. These need to be validated
against the values in the OpenID discovery document. For example, the tenant independent version of the document is located at
https://login.windows.net/common/.well-known/openid-configuration. Azure AD middleware has built-in capabilities for validating
access tokens, and you can browse through our samples to find one in the language of your choice. For more information on how to
explicitly validate a JWT token, please see the manual JWT validation sample.
We provide libraries and code samples that show how to easily handle token validation - the below information is simply provided
for those who wish to understand the underlying process. There are also several third party open source libraries available for JWT
validation - there is at least one option for almost every platform and language out there. For more information about Azure AD
authentication libraries and code samples, please see Azure AD authentication libraries.
Validating the signature
A JWT contains three segments, which are separated by the . character. The first segment is known as the header, the second as
the body, and the third as the signature. The signature segment can be used to validate the authenticity of the token so that it can
be trusted by your app.
Tokens issued by Azure AD are signed using industry standard asymmetric encryption algorithms, such as RSA 256. The header of
the JWT contains information about the key and encryption method used to sign the token:
{
"typ": "JWT",
"alg": "RS256",
"x5t": "kriMPdmBvx68skT8-mPAB3BseeA"
}
The alg claim indicates the algorithm that was used to sign the token, while the
was used to sign the token.
x5t
claim indicates the particular public key that
At any given point in time, Azure AD may sign an id_token using any one of a certain set of public-private key pairs. Azure AD
rotates the possible set of keys on a periodic basis, so your app should be written to handle those key changes automatically. A
reasonable frequency to check for updates to the public keys used by Azure AD is every 24 hours.
You can acquire the signing key data necessary to validate the signature by using the OpenID Connect metadata document located
at:
https://login.microsoftonline.com/common/.well-known/openid-configuration
TIP
Try this URL in a browser!
This metadata document is a JSON object containing several useful pieces of information, such as the location of the various
endpoints required for performing OpenID Connect authentication.
It also includes a jwks_uri , which gives the location of the set of public keys used to sign tokens. The JSON document located at the
jwks_uri contains all of the public key information in use at that particular moment in time. Your app can use the kid claim in the
JWT header to select which public key in this document has been used to sign a particular token. It can then perform signature
validation using the correct public key and the indicated algorithm.
Performing signature validation is outside the scope of this document - there are many open source libraries available for helping
you do so if necessary.
Validating the claims
When your app receives a token (either an id_token upon user sign-in, or an access token as a bearer token in the HTTP request) it
should also perform a few checks against the claims in the token. These include but are not limited to:
The Audience claim - to verify that the token was intended to be given to your app.
The Not Before and Expiration Time claims - to verify that the token has not expired.
The Issuer claim - to verify that the token was indeed issued to your app by Azure AD.
The Nonce - to mitigate a token replay attack.
and more...
For a full list of claim validations your app should perform for ID Tokens, refer to the OpenID Connect specification. Details of the
expected values for these claims are included in the preceding id_token section section.
Sample Tokens
This section displays samples of SAML and JWT tokens that Azure AD returns. These samples let you see the claims in context.
SAML Token
This is a sample of a typical SAML token.
<?xml version="1.0" encoding="UTF-8"?>
<t:RequestSecurityTokenResponse xmlns:t="http://schemas.xmlsoap.org/ws/2005/02/trust">
<t:Lifetime>
<wsu:Created xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">2014-1224T05:15:47.060Z</wsu:Created>
<wsu:Expires xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">2014-1224T06:15:47.060Z</wsu:Expires>
</t:Lifetime>
<wsp:AppliesTo xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy">
<EndpointReference xmlns="http://www.w3.org/2005/08/addressing">
<Address>https://contoso.onmicrosoft.com/MyWebApp</Address>
</EndpointReference>
</wsp:AppliesTo>
<t:RequestedSecurityToken>
<Assertion xmlns="urn:oasis:names:tc:SAML:2.0:assertion" ID="_3ef08993-846b-41de-99df-b7f3ff77671b" IssueInstant="2014-1224T05:20:47.060Z" Version="2.0">
<Issuer>https://sts.windows.net/b9411234-09af-49c2-b0c3-653adc1f376e/</Issuer>
<ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
<ds:SignedInfo>
<ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#" />
<ds:SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256" />
<ds:Reference URI="#_3ef08993-846b-41de-99df-b7f3ff77671b">
<ds:Transforms>
<ds:Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" />
<ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#" />
</ds:Transforms>
<ds:DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256" />
<ds:DigestValue>cV1J580U1pD24hEyGuAxrbtgROVyghCqI32UkER/nDY=</ds:DigestValue>
</ds:Reference>
</ds:SignedInfo>
<ds:SignatureValue>j+zPf6mti8Rq4Kyw2NU2nnu0pbJU1z5bR/zDaKaO7FCTdmjUzAvIVfF8pspVR6CbzcYM3HOAmLhuWmBkAAk6qQUBmKsw+XlmF/pB/ivJFdgZ
SLrtlBs1P/WBV3t04x6fRW4FcIDzh8KhctzJZfS5wGCfYw95er7WJxJi0nU41d7j5HRDidBoXgP755jQu2ZER7wOYZr6ff+ha+/Aj3UMw+8ZtC+WCJC3yyENHDAnp2R
fgdElJal68enn668fk8pBDjKDGzbNBO6qBgFPaBT65YvE/tkEmrUxdWkmUKv3y7JWzUYNMD9oUlut93UTyTAIGOs5fvP9ZfK2vNeMVJW7Xg==
</ds:SignatureValue>
<KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
<X509Data>
<X509Certificate>MIIDPjCCAabcAwIBAgIQsRiM0jheFZhKk49YD0SK1TAJBgUrDgMCHQUAMC0xKzApBgNVBAMTImFjY291bnRzLmFjY2Vzc2NvbnRyb2wud2luZG
93cy5uZXQwHhcNMTQwMTAxMDcwMDAwWhcNMTYwMTAxMDcwMDAwWjAtMSswKQYDVQQDEyJhY2NvdW50cy5hY2Nlc3Njb250cm9sLndpbmRvd3MubmV0MIIBIjANBgkqh
kiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAkSCWg6q9iYxvJE2NIhSyOiKvqoWCO2GFipgH0sTSAs5FalHQosk9ZNTztX0ywS/AHsBeQPqYygfYVJL6/EgzVuwRk5txr9e3
n1uml94fLyq/AXbwo9yAduf4dCHTP8CWR1dnDR+Qnz/4PYlWVEuuHHONOw/blbfdMjhY+C/BYM2E3pRxbohBb3x//CfueV7ddz2LYiH3wjz0QS/7kjPiNCsXcNyKQEO
TkbHFi3mu0u13SQwNddhcynd/GTgWN8A+6SN1r4hzpjFKFLbZnBt77ACSiYx+IHK4Mp+NaVEi5wQtSsjQtI++XsokxRDqYLwus1I1SihgbV/STTg5enufuwIDAQABo2
IwYDBeBgNVHQEEVzBVgBDLebM6bK3BjWGqIBrBNFeNoS8wLTErMCkGA1UEAxMiYWNjb3VudHMuYWNjZXNzY29udHJvbC53aW5kb3dzLm5ldIIQsRiM0jheFZhKk49YD
0SK1TAJBgUrDgMCHQUAA4IBAQCJ4JApryF77EKC4zF5bUaBLQHQ1PNtA1uMDbdNVGKCmSp8M65b8h0NwlIjGGGy/unK8P6jWFdm5IlZ0YPTOgzcRZguXDPj7ajyvlVE
Q2K2ICvTYiRQqrOhEhZMSSZsTKXFVwNfW6ADDkN3bvVOVbtpty+nBY5UqnI7xbcoHLZ4wYD251uj5+lo13YLnsVrmQ16NCBYq2nQFNPuNJw6t3XUbwBHXpF46aLT1/e
Gf/7Xx6iy8yPJX4DyrpFTutDz882RWofGEO5t4Cw+zZg70dJ/hH/ODYRMorfXEW+8uKmXMKmX2wyxMKvfiPbTy5LmAU8Jvjs2tLg4rOBcXWLAIarZ</X509Certific
ate>
</X509Data>
</KeyInfo>
</ds:Signature>
<Subject>
<NameID Format="urn:oasis:names:tc:SAML:2.0:nameidformat:persistent">m_H3naDei2LNxUmEcWd0BZlNi_jVET1pMLR6iQSuYmo</NameID>
<SubjectConfirmation Method="urn:oasis:names:tc:SAML:2.0:cm:bearer" />
</Subject>
<Conditions NotBefore="2014-12-24T05:15:47.060Z" NotOnOrAfter="2014-12-24T06:15:47.060Z">
<AudienceRestriction>
<Audience>https://contoso.onmicrosoft.com/MyWebApp</Audience>
</AudienceRestriction>
</Conditions>
<AttributeStatement>
<Attribute Name="http://schemas.microsoft.com/identity/claims/objectidentifier">
<AttributeValue>a1addde8-e4f9-4571-ad93-3059e3750d23</AttributeValue>
</Attribute>
<Attribute Name="http://schemas.microsoft.com/identity/claims/tenantid">
<AttributeValue>b9411234-09af-49c2-b0c3-653adc1f376e</AttributeValue>
</Attribute>
<Attribute Name="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name">
<AttributeValue>[email protected]</AttributeValue>
</Attribute>
<Attribute Name="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname">
<AttributeValue>Admin</AttributeValue>
</Attribute>
<Attribute Name="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname">
<AttributeValue>Sample</AttributeValue>
</Attribute>
<Attribute Name="http://schemas.microsoft.com/ws/2008/06/identity/claims/groups">
<AttributeValue>5581e43f-6096-41d4-8ffa-04e560bab39d</AttributeValue>
<AttributeValue>07dd8a89-bf6d-4e81-8844-230b77145381</AttributeValue>
<AttributeValue>0e129f4g-6b0a-4944-982d-f776000632af</AttributeValue>
<AttributeValue>3ee07328-52ef-4739-a89b-109708c22fb5</AttributeValue>
<AttributeValue>329k14b3-1851-4b94-947f-9a4dacb595f4</AttributeValue>
<AttributeValue>6e32c650-9b0a-4491-b429-6c60d2ca9a42</AttributeValue>
<AttributeValue>f3a169a7-9a58-4e8f-9d47-b70029v07424</AttributeValue>
<AttributeValue>8e2c86b2-b1ad-476d-9574-544d155aa6ff</AttributeValue>
<AttributeValue>1bf80264-ff24-4866-b22c-6212e5b9a847</AttributeValue>
<AttributeValue>4075f9c3-072d-4c32-b542-03e6bc678f3e</AttributeValue>
<AttributeValue>76f80527-f2cd-46f4-8c52-8jvd8bc749b1</AttributeValue>
<AttributeValue>0ba31460-44d0-42b5-b90c-47b3fcc48e35</AttributeValue>
<AttributeValue>edd41703-8652-4948-94a7-2d917bba7667</AttributeValue>
</Attribute>
<Attribute Name="http://schemas.microsoft.com/identity/claims/identityprovider">
<AttributeValue>https://sts.windows.net/b9411234-09af-49c2-b0c3-653adc1f376e/</AttributeValue>
</Attribute>
</AttributeStatement>
<AuthnStatement AuthnInstant="2014-12-23T18:51:11.000Z">
<AuthnContext>
<AuthnContextClassRef>urn:oasis:names:tc:SAML:2.0:ac:classes:Password</AuthnContextClassRef>
</AuthnContext>
</AuthnStatement>
</Assertion>
</t:RequestedSecurityToken>
<t:RequestedAttachedReference>
<SecurityTokenReference xmlns="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"
xmlns:d3p1="http://docs.oasis-open.org/wss/oasis-wss-wssecurity-secext-1.1.xsd" d3p1:TokenType="http://docs.oasisopen.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV2.0">
<KeyIdentifier ValueType="http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLID">_3ef08993-846b-41de99df-b7f3ff77671b</KeyIdentifier>
</SecurityTokenReference>
</t:RequestedAttachedReference>
<t:RequestedUnattachedReference>
<SecurityTokenReference xmlns="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"
xmlns:d3p1="http://docs.oasis-open.org/wss/oasis-wss-wssecurity-secext-1.1.xsd" d3p1:TokenType="http://docs.oasisopen.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV2.0">
<KeyIdentifier ValueType="http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLID">_3ef08993-846b-41de99df-b7f3ff77671b</KeyIdentifier>
</SecurityTokenReference>
</t:RequestedUnattachedReference>
<t:TokenType>http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV2.0</t:TokenType>
<t:RequestType>http://schemas.xmlsoap.org/ws/2005/02/trust/Issue</t:RequestType>
<t:KeyType>http://schemas.xmlsoap.org/ws/2005/05/identity/NoProofKey</t:KeyType>
</t:RequestSecurityTokenResponse>
JWT Token - User Impersonation
This is a sample of a typical JSON web token (JWT) used in an authorization code grant flow. In addition to claims, the token
includes a version number in ver and appidacr, the authentication context class reference, which indicates how the client was
authenticated. For a public client, the value is 0. If a client ID or client secret was used, the value is 1.
{
typ: "JWT",
alg: "RS256",
x5t: "kriMPdmBvx68skT8-mPAB3BseeA"
}.
{
aud: "https://contoso.onmicrosoft.com/scratchservice",
iss: "https://sts.windows.net/b9411234-09af-49c2-b0c3-653adc1f376e/",
iat: 1416968588,
nbf: 1416968588,
exp: 1416972488,
ver: "1.0",
tid: "b9411234-09af-49c2-b0c3-653adc1f376e",
amr: [
"pwd"
],
roles: [
"Admin"
],
oid: "6526e123-0ff9-4fec-ae64-a8d5a77cf287",
upn: "[email protected]",
unique_name: "[email protected]",
sub: "yf8C5e_VRkR1egGxJSDt5_olDFay6L5ilBA81hZhQEI",
family_name: "User",
given_name: "Sample",
groups: [
"0e129f6b-6b0a-4944-982d-f776000632af",
"323b13b3-1851-4b94-947f-9a4dacb595f4",
"6e32c250-9b0a-4491-b429-6c60d2ca9a42",
"f3a161a7-9a58-4e8f-9d47-b70022a07424",
"8d4c81b2-b1ad-476d-9574-544d155aa6ff",
"1bf80164-ff24-4866-b19c-6212e5b9a847",
"76f80127-f2cd-46f4-8c52-8edd8bc749b1",
"0ba27160-44d0-42b5-b90c-47b3fcc48e35"
],
appid: "b075ddef-0efa-123b-997b-de1337c29185",
appidacr: "1",
scp: "user_impersonation",
acr: "1"
}.
Related content
See the Azure AD Graph Policy operations and the Policy entity, to learn more about managing token lifetime policy via the
Azure AD Graph API.
For more information and samples on managing policies via PowerShell cmdlets, including samples, see Configurable token
lifetimes in Azure AD.
Signing key rollover in Azure Active Directory
3/31/2017 • 13 min to read • Edit Online
This topic discusses what you need to know about the public keys that are used in Azure Active Directory
(Azure AD) to sign security tokens. It is important to note that these keys rollover on a periodic basis and, in an
emergency, could be rolled over immediately. All applications that use Azure AD should be able to
programmatically handle the key rollover process or establish a periodic manual rollover process. Continue
reading to understand how the keys work, how to assess the impact of the rollover to your application and how
to update your application or establish a periodic manual rollover process to handle key rollover if necessary.
Overview of signing keys in Azure AD
Azure AD uses public-key cryptography built on industry standards to establish trust between itself and the
applications that use it. In practical terms, this works in the following way: Azure AD uses a signing key that
consists of a public and private key pair. When a user signs in to an application that uses Azure AD for
authentication, Azure AD creates a security token that contains information about the user. This token is signed
by Azure AD using its private key before it is sent back to the application. To verify that the token is valid and
actually originated from Azure AD, the application must validate the token’s signature using the public key
exposed by Azure AD that is contained in the tenant’s OpenID Connect discovery document or SAML/WS-Fed
federation metadata document.
For security purposes, Azure AD’s signing key rolls on a periodic basis and, in the case of an emergency, could
be rolled over immediately. Any application that integrates with Azure AD should be prepared to handle a key
rollover event no matter how frequently it may occur. If it doesn’t, and your application attempts to use an
expired key to verify the signature on a token, the sign-in request will fail.
There is always more than one valid key available in the OpenID Connect discovery document and the
federation metadata document. Your application should be prepared to use any of the keys specified in the
document, since one key may be rolled soon, another may be its replacement, and so forth.
How to assess if your application will be affected and what to do
about it
How your application handles key rollover depends on variables such as the type of application or what identity
protocol and library was used. The sections below assess whether the most common types of applications are
impacted by the key rollover and provide guidance on how to update the application to support automatic
rollover or manually update the key.
Native client applications accessing resources
Web applications / APIs accessing resources
Web applications / APIs protecting resources and built using Azure App Services
Web applications / APIs protecting resources using .NET OWIN OpenID Connect, WS-Fed or
WindowsAzureActiveDirectoryBearerAuthentication middleware
Web applications / APIs protecting resources using .NET Core OpenID Connect or JwtBearerAuthentication
middleware
Web applications / APIs protecting resources using Node.js passport-azure-ad module
Web applications / APIs protecting resources and created with Visual Studio 2015 or Visual Studio 2017
Web applications protecting resources and created with Visual Studio 2013
Web APIs protecting resources and created with Visual Studio 2013
Web applications protecting resources and created with Visual Studio 2012
Web applications protecting resources and created with Visual Studio 2010, 2008 o using Windows Identity
Foundation
Web applications / APIs protecting resources using any other libraries or manually implementing any of the
supported protocols
This guidance is not applicable for:
Applications added from Azure AD Application Gallery (including Custom) have separate guidance with
regards to signing keys. More information.
On-premises applications published via application proxy don't have to worry about signing keys.
Native client applications accessing resources
Applications that are only accessing resources (i.e Microsoft Graph, KeyVault, Outlook API and other Microsoft
APIs) generally only obtain a token and pass it along to the resource owner. Given that they are not protecting
any resources, they do not inspect the token and therefore do not need to ensure it is properly signed.
Native client applications, whether desktop or mobile, fall into this category and are thus not impacted by the
rollover.
Web applications / APIs accessing resources
Applications that are only accessing resources (i.e Microsoft Graph, KeyVault, Outlook API and other Microsoft
APIs) generally only obtain a token and pass it along to the resource owner. Given that they are not protecting
any resources, they do not inspect the token and therefore do not need to ensure it is properly signed.
Web applications and web APIs that are using the app-only flow (client credentials / client certificate), fall into
this category and are thus not impacted by the rollover.
Web applications / APIs protecting resources and built using Azure App Services
Azure App Services' Authentication / Authorization (EasyAuth) functionality already has the necessary logic to
handle key rollover automatically.
Web applications / APIs protecting resources using .NET OWIN OpenID Connect, WS -Fed or
WindowsAzureActiveDirectoryBearerAuthentication middleware
If your application is using the .NET OWIN OpenID Connect, WS-Fed or
WindowsAzureActiveDirectoryBearerAuthentication middleware, it already has the necessary logic to handle
key rollover automatically.
You can confirm that your application is using any of these by looking for any of the following snippets in your
application's Startup.cs or Startup.Auth.cs
app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions
{
// ...
});
app.UseWsFederationAuthentication(
new WsFederationAuthenticationOptions
{
// ...
});
app.UseWindowsAzureActiveDirectoryBearerAuthentication(
new WindowsAzureActiveDirectoryBearerAuthenticationOptions
{
// ...
});
Web applications / APIs protecting resources using .NET Core OpenID Connect or JwtBearerAuthentication
middleware
If your application is using the .NET Core OWIN OpenID Connect or JwtBearerAuthentication middleware, it
already has the necessary logic to handle key rollover automatically.
You can confirm that your application is using any of these by looking for any of the following snippets in your
application's Startup.cs or Startup.Auth.cs
app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions
{
// ...
});
app.UseJwtBearerAuthentication(
new JwtBearerAuthenticationOptions
{
// ...
});
Web applications / APIs protecting resources using Node.js passport-azure -ad module
If your application is using the Node.js passport-ad module, it already has the necessary logic to handle key
rollover automatically.
You can confirm that your application passport-ad by searching for the following snippet in your application's
app.js
var OIDCStrategy = require('passport-azure-ad').OIDCStrategy;
passport.use(new OIDCStrategy({
//...
));
Web applications / APIs protecting resources and created with Visual Studio 2015 or Visual Studio 2017
If your application was built using a web application template in Visual Studio 2015 or Visual Studio 2017 and
you selected Work And School Accounts from the Change Authentication menu, it already has the
necessary logic to handle key rollover automatically. This logic, embedded in the OWIN OpenID Connect
middleware, retrieves and caches the keys from the OpenID Connect discovery document and periodically
refreshes them.
If you added authentication to your solution manually, your application might not have the necessary key
rollover logic. You will need to write it yourself, or follow the steps in Web applications / APIs using any other
libraries or manually implementing any of the supported protocols..
Web applications protecting resources and created with Visual Studio 2013
If your application was built using a web application template in Visual Studio 2013 and you selected
Organizational Accounts from the Change Authentication menu, it already has the necessary logic to
handle key rollover automatically. This logic stores your organization’s unique identifier and the signing key
information in two database tables associated with the project. You can find the connection string for the
database in the project’s Web.config file.
If you added authentication to your solution manually, your application might not have the necessary key
rollover logic. You will need to write it yourself, or follow the steps in Web applications / APIs using any other
libraries or manually implementing any of the supported protocols..
The following steps will help you verify that the logic is working properly in your application.
1. In Visual Studio 2013, open the solution, and then click on the Server Explorer tab on the right window.
2. Expand Data Connections, DefaultConnection, and then Tables. Locate the IssuingAuthorityKeys table,
right-click it, and then click Show Table Data.
3. In the IssuingAuthorityKeys table, there will be at least one row, which corresponds to the thumbprint
value for the key. Delete any rows in the table.
4. Right-click the Tenants table, and then click Show Table Data.
5. In the Tenants table, there will be at least one row, which corresponds to a unique directory tenant
identifier. Delete any rows in the table. If you don't delete the rows in both the Tenants table and
IssuingAuthorityKeys table, you will get an error at runtime.
6. Build and run the application. After you have logged in to your account, you can stop the application.
7. Return to the Server Explorer and look at the values in the IssuingAuthorityKeys and Tenants table.
You’ll notice that they have been automatically repopulated with the appropriate information from the
federation metadata document.
Web APIs protecting resources and created with Visual Studio 2013
If you created a web API application in Visual Studio 2013 using the Web API template, and then selected
Organizational Accounts from the Change Authentication menu, you already have the necessary logic in
your application.
If you manually configured authentication, follow the instructions below to learn how to configure your Web
API to automatically update its key information.
The following code snippet demonstrates how to get the latest keys from the federation metadata document,
and then use the JWT Token Handler to validate the token. The code snippet assumes that you will use your
own caching mechanism for persisting the key to validate future tokens from Azure AD, whether it be in a
database, configuration file, or elsewhere.
using
using
using
using
using
using
using
using
using
using
using
using
System;
System.Collections.Generic;
System.Linq;
System.Text;
System.Threading.Tasks;
System.IdentityModel.Tokens;
System.Configuration;
System.Security.Cryptography.X509Certificates;
System.Xml;
System.IdentityModel.Metadata;
System.ServiceModel.Security;
System.Threading;
namespace JWTValidation
{
public class JWTValidator
{
private string MetadataAddress = "[Your Federation Metadata document address goes here]";
// Validates the JWT Token that's part of the Authorization header in an HTTP request.
public void ValidateJwtToken(string token)
{
JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler()
{
{
// Do not disable for production code
CertificateValidator = X509CertificateValidator.None
};
TokenValidationParameters validationParams = new TokenValidationParameters()
{
AllowedAudience = "[Your App ID URI goes here, as registered in the Azure Classic Portal]",
ValidIssuer = "[The issuer for the token goes here, such as
https://sts.windows.net/68b98905-130e-4d7c-b6e1-a158a9ed8449/]",
SigningTokens = GetSigningCertificates(MetadataAddress)
// Cache the signing tokens by your desired mechanism
};
Thread.CurrentPrincipal = tokenHandler.ValidateToken(token, validationParams);
}
// Returns a list of certificates from the specified metadata document.
public List<X509SecurityToken> GetSigningCertificates(string metadataAddress)
{
List<X509SecurityToken> tokens = new List<X509SecurityToken>();
if (metadataAddress == null)
{
throw new ArgumentNullException(metadataAddress);
}
using (XmlReader metadataReader = XmlReader.Create(metadataAddress))
{
MetadataSerializer serializer = new MetadataSerializer()
{
// Do not disable for production code
CertificateValidationMode = X509CertificateValidationMode.None
};
EntityDescriptor metadata = serializer.ReadMetadata(metadataReader) as EntityDescriptor;
if (metadata != null)
{
SecurityTokenServiceDescriptor stsd =
metadata.RoleDescriptors.OfType<SecurityTokenServiceDescriptor>().First();
if (stsd != null)
{
IEnumerable<X509RawDataKeyIdentifierClause> x509DataClauses = stsd.Keys.Where(key
=> key.KeyInfo != null && (key.Use == KeyType.Signing || key.Use == KeyType.Unspecified)).
Select(key =>
key.KeyInfo.OfType<X509RawDataKeyIdentifierClause>().First());
tokens.AddRange(x509DataClauses.Select(token => new X509SecurityToken(new
X509Certificate2(token.GetX509RawData()))));
}
else
{
throw new InvalidOperationException("There is no RoleDescriptor of type
SecurityTokenServiceType in the metadata");
}
}
else
{
throw new Exception("Invalid Federation Metadata document");
}
}
return tokens;
}
}
}
Web applications protecting resources and created with Visual Studio 2012
If your application was built in Visual Studio 2012, you probably used the Identity and Access Tool to configure
your application. It’s also likely that you are using the Validating Issuer Name Registry (VINR). The VINR is
responsible for maintaining information about trusted identity providers (Azure AD) and the keys used to
validate tokens issued by them. The VINR also makes it easy to automatically update the key information stored
in a Web.config file by downloading the latest federation metadata document associated with your directory,
checking if the configuration is out of date with the latest document, and updating the application to use the
new key as necessary.
If you created your application using any of the code samples or walkthrough documentation provided by
Microsoft, the key rollover logic is already included in your project. You will notice that the code below already
exists in your project. If your application does not already have this logic, follow the steps below to add it and to
verify that it’s working correctly.
1. In Solution Explorer, add a reference to the System.IdentityModel assembly for the appropriate project.
2. Open the Global.asax.cs file and add the following using directives:
using System.Configuration; using System.IdentityModel.Tokens;
3. Add the following method to the Global.asax.cs file:
protected void RefreshValidationSettings() { string configPath = AppDomain.CurrentDomain.BaseDirectory +
"\\" + "Web.config"; string metadataAddress =
ConfigurationManager.AppSettings["ida:FederationMetadataLocation"];
ValidatingIssuerNameRegistry.WriteToConfig(metadataAddress, configPath); }
4. Invoke the RefreshValidationSettings() method in the Application_Start() method in Global.asax.cs as
shown:
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); ...
RefreshValidationSettings(); }
Once you have followed these steps, your application’s Web.config will be updated with the latest information
from the federation metadata document, including the latest keys. This update will occur every time your
application pool recycles in IIS; by default IIS is set to recycle applications every 29 hours.
Follow the steps below to verify that the key rollover logic is working.
1. After you have verified that your application is using the code above, open the Web.config file and
navigate to the block, specifically looking for the following few lines:
<issuerNameRegistry type="System.IdentityModel.Tokens.ValidatingIssuerNameRegistry,
System.IdentityModel.Tokens.ValidatingIssuerNameRegistry"> <authority
name="https://sts.windows.net/ec4187af-07da-4f01-b18f-64c2f5abecea/"> <keys> <add
thumbprint="3A38FA984E8560F19AADC9F86FE9594BB6AD049B" /> </keys>
2. In the setting, change the thumbprint value by replacing any character with a different one. Save the
Web.config file.
3. Build the application, and then run it. If you can complete the sign-in process, your application is successfully
updating the key by downloading the required information from your directory’s federation metadata
document. If you are having issues signing in, ensure the changes in your application are correct by reading
the Adding Sign-On to Your Web Application Using Azure AD topic, or downloading and inspecting the
following code sample: Multi-Tenant Cloud Application for Azure Active Directory.
Web applications protecting resources and created with Visual Studio 2008 or 2010 and Windows Identity
Foundation (WIF ) v1.0 for .NET 3.5
If you built an application on WIF v1.0, there is no provided mechanism to automatically refresh your
application’s configuration to use a new key.
Easiest way Use the FedUtil tooling included in the WIF SDK, which can retrieve the latest metadata
document and update your configuration.
Update your application to .NET 4.5, which includes the newest version of WIF located in the System
namespace. You can then use the Validating Issuer Name Registry (VINR) to perform automatic updates of
the application’s configuration.
Perform a manual rollover as per the instructions at the end of this guidance document.
Instructions to use the FedUtil to update your configuration:
1. Verify that you have the WIF v1.0 SDK installed on your development machine for Visual Studio 2008 or
2010. You can download it from here if you have not yet installed it.
2. In Visual Studio, open the solution, and then right-click the applicable project and select Update federation
metadata. If this option is not available, FedUtil and/or the WIF v1.0 SDK has not been installed.
3. From the prompt, select Update to begin updating your federation metadata. If you have access to the
server environment where the application is hosted, you can optionally use FedUtil’s automatic metadata
update scheduler.
4. Click Finish to complete the update process.
Web applications / APIs protecting resources using any other libraries or manually implementing any of the
supported protocols
If you are using some other library or manually implemented any of the supported protocols, you'll need to
review the library or your implementation to ensure that the key is being retrieved from either the OpenID
Connect discovery document or the federation metadata document. One way to check for this is to do a search
in your code or the library's code for any calls out to either the OpenID discovery document or the federation
metadata document.
If they key is being stored somewhere or hardcoded in your application, you can manually retrieve the key and
update it accordingly by perform a manual rollover as per the instructions at the end of this guidance
document. It is strongly encouraged that you enhance your application to support automatic rollover
using any of the approaches outline in this article to avoid future disruptions and overhead if Azure AD
increases it's rollover cadence or has an emergency out-of-band rollover.
How to test your application to determine if it will be affected
You can validate whether your application supports automatic key rollover by downloading the scripts and
following the instructions in this GitHub repository.
How to perform a manual rollover if you application does not
support automatic rollover
If your application does not support automatic rollover, you will need to establish a process that periodically
monitors Azure AD's signing keys and performs a manual rollover accordingly. This GitHub repository contains
scripts and instructions on how to do this.
Federation metadata
2/13/2017 • 4 min to read • Edit Online
Azure Active Directory (Azure AD) publishes a federation metadata document for services that is configured to
accept the security tokens that Azure AD issues. The federation metadata document format is described in the Web
Services Federation Language (WS-Federation) Version 1.2, which extends Metadata for the OASIS Security
Assertion Markup Language (SAML) v2.0.
Tenant-specific and Tenant-independent metadata endpoints
Azure AD publishes tenant-specific and tenant-independent endpoints.
Tenant-specific endpoints are designed for a particular tenant. 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.
Tenant-independent endpoints provide information that is common to all Azure AD tenants. This information
applies to tenants hosted at login.microsoftonline.com and is shared across tenants. Tenant-independent
endpoints are recommended for multi-tenant applications, since they are not associated with any particular tenant.
Federation metadata endpoints
Azure AD publishes federation metadata at
https://login.microsoftonline.com/<TenantDomainName>/FederationMetadata/2007-06/FederationMetadata.xml
For tenant-specific endpoints, the
TenantDomainName
.
can be one of the following types:
A registered domain name of an Azure AD tenant, such as: contoso.onmicrosoft.com .
The immutable tenant ID of the domain, such as 72f988bf-86f1-41af-91ab-2d7cd011db45 .
For tenant-independent endpoints, the TenantDomainName is common . This document lists only the Federation
Metadata elements that are common to all Azure AD tenants that are hosted at login.microsoftonline.com.
For example, a tenant-specific endpoint might be
https:// login.microsoftonline.com/contoso.onmicrosoft.com/FederationMetadata/2007-06/FederationMetadata.xml
.
The tenant-independent endpoint is https://login.microsoftonline.com/common/FederationMetadata/200706/FederationMetadata.xml. You can view the federation metadata document by typing this URL in a browser.
Contents of federation Metadata
The following section provides information needed by services that consume the tokens issued by Azure AD.
Entity ID
The EntityDescriptor element contains an EntityID attribute. The value of the EntityID attribute represents the
issuer, that is, the security token service (STS) that issued the token. It is important to validate the issuer when you
receive a token.
The following metadata shows a sample tenant-specific
EntityDescriptor
element with an
EntityID
element.
<EntityDescriptor
xmlns="urn:oasis:names:tc:SAML:2.0:metadata"
ID="_b827a749-cfcb-46b3-ab8b-9f6d14a1294b"
entityID="https://sts.windows.net/72f988bf-86f1-41af-91ab-2d7cd011db45/">
You can replace the tenant ID in the tenant-independent endpoint with your tenant ID to create a tenant-specific
EntityID value. The resulting value will be the same as the token issuer. The strategy allows a multi-tenant
application to validate the issuer for a given tenant.
The following metadata shows a sample tenant-independent
a literal, not a placeholder.
EntityID
element. Please note, that the
{tenant}
is
<EntityDescriptor
xmlns="urn:oasis:names:tc:SAML:2.0:metadata"
ID="="_0e5bd9d0-49ef-4258-bc15-21ce143b61bd"
entityID="https://sts.windows.net/{tenant}/">
Token signing certificates
When a service receives a token that is issued by a Azure AD tenant, the signature of the token must be validated
with a signing key that is published in the federation metadata document. The federation metadata includes the
public portion of the certificates that the tenants use for token signing. The certificate raw bytes appear in the
KeyDescriptor element. The token signing certificate is valid for signing only when the value of the use attribute
is signing .
A federation metadata document published by Azure AD can have multiple signing keys, such as when Azure AD is
preparing to update the signing certificate. When a federation metadata document includes more than one
certificate, a service that is validating the tokens should support all certificates in the document.
The following metadata shows a sample
KeyDescriptor
element with a signing key.
<KeyDescriptor use="signing">
<KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
<X509Data>
<X509Certificate>
MIIDPjCCAiqgAwIBAgIQVWmXY/+9RqFA/OG9kFulHDAJBgUrDgMCHQUAMC0xKzApBgNVBAMTImFjY291bnRzLmFjY2Vzc2NvbnRyb2wud2luZG
93cy5uZXQwHhcNMTIwNjA3MDcwMDAwWhcNMTQwNjA3MDcwMDAwWjAtMSswKQYDVQQDEyJhY2NvdW50cy5hY2Nlc3Njb250cm9sLndpbmRvd3Mu
bmV0MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArCz8Sn3GGXmikH2MdTeGY1D711EORX/lVXpr+ecGgqfUWF8MPB07XkYuJ54DAu
YT318+2XrzMjOtqkT94VkXmxv6dFGhG8YZ8vNMPd4tdj9c0lpvWQdqXtL1TlFRpD/P6UMEigfN0c9oWDg9U7Ilymgei0UXtf1gtcQbc5sSQU0S
4vr9YJp2gLFIGK11Iqg4XSGdcI0QWLLkkC6cBukhVnd6BCYbLjTYy3fNs4DzNdemJlxGl8sLexFytBF6YApvSdus3nFXaMCtBGx16HzkK9ne3l
obAwL2o79bP4imEGqg+ibvyNmbrwFGnQrBc1jTF9LyQX9q+louxVfHs6ZiVwIDAQABo2IwYDBeBgNVHQEEVzBVgBCxDDsLd8xkfOLKm4Q/Szjt
oS8wLTErMCkGA1UEAxMiYWNjb3VudHMuYWNjZXNzY29udHJvbC53aW5kb3dzLm5ldIIQVWmXY/+9RqFA/OG9kFulHDAJBgUrDgMCHQUAA4IBAQ
AkJtxxm/ErgySlNk69+1odTMP8Oy6L0H17z7XGG3w4TqvTUSWaxD4hSFJ0e7mHLQLQD7oV/erACXwSZn2pMoZ89MBDjOMQA+e6QzGB7jmSzPTN
mQgMLA8fWCfqPrz6zgH+1F1gNp8hJY57kfeVPBiyjuBmlTEBsBlzolY9dd/55qqfQk6cgSeCbHCy/RU/iep0+UsRMlSgPNNmqhj5gmN2AFVCN9
6zF694LwuPae5CeR2ZcVknexOWHYjFM0MgUSw0ubnGl0h9AJgGyhvNGcjQqu9vd1xkupFgaN+f7P3p3EVN5csBg5H94jEcQZT7EKeTiZ6bTrpD
Anrr8tDCy8ng
</X509Certificate>
</X509Data>
</KeyInfo>
</KeyDescriptor>
The KeyDescriptor element appears in two places in the federation metadata document; in the WS-Federationspecific section and the SAML-specific section. The certificates published in both sections will be the same.
In the WS-Federation-specific section, a WS-Federation metadata reader would read the certificates from a
RoleDescriptor element with the SecurityTokenServiceType type.
The following metadata shows a sample
RoleDescriptor
element.
<RoleDescriptor xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:fed="http://docs.oasisopen.org/wsfed/federation/200706"
xsi:type="fed:SecurityTokenServiceType"protocolSupportEnumeration="http://docs.oasisopen.org/wsfed/federation/200706">
In the SAML-specific section, a WS-Federation metadata reader would read the certificates from a
IDPSSODescriptor element.
The following metadata shows a sample
IDPSSODescriptor
element.
<IDPSSODescriptor protocolSupportEnumeration="urn:oasis:names:tc:SAML:2.0:protocol">
There are no differences in the format of tenant-specific and tenant-independent certificates.
WS -Federation endpoint URL
The federation metadata includes the URL that is Azure AD uses for single sign-in and single sign-out in WSFederation protocol. This endpoint appears in the PassiveRequestorEndpoint element.
The following metadata shows a sample
PassiveRequestorEndpoint
element for a tenant-specific endpoint.
<fed:PassiveRequestorEndpoint>
<EndpointReference xmlns="http://www.w3.org/2005/08/addressing">
<Address>
https://login.microsoftonline.com/72f988bf-86f1-41af-91ab-2d7cd011db45/wsfed
</Address>
</EndpointReference>
</fed:PassiveRequestorEndpoint>
For the tenant-independent endpoint, the WS-Federation URL appears in the WS-Federation endpoint, as shown in
the following sample.
<fed:PassiveRequestorEndpoint>
<EndpointReference xmlns="http://www.w3.org/2005/08/addressing">
<Address>
https://login.microsoftonline.com/common/wsfed
</Address>
</EndpointReference>
</fed:PassiveRequestorEndpoint>
SAML protocol endpoint URL
The federation metadata includes the URL that Azure AD uses for single sign-in and single sign-out in SAML 2.0
protocol. These endpoints appear in the IDPSSODescriptor element.
The sign-in and sign-out URLs appear in the
The following metadata shows a sample
SingleSignOnService
PassiveResistorEndpoint
and
SingleLogoutService
elements.
for a tenant-specific endpoint.
<IDPSSODescriptor protocolSupportEnumeration="urn:oasis:names:tc:SAML:2.0:protocol">
…
<SingleLogoutService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect"
Location="https://login.microsoftonline.com/contoso.onmicrosoft.com/saml2" />
<SingleSignOnService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect"
Location="https://login.microsoftonline.com/contoso.onmicrosoft.com /saml2" />
</IDPSSODescriptor>
Similarly the endpoints for the common SAML 2.0 protocol endpoints are published in the tenant-independent
federation metadata, as shown in the following sample.
<IDPSSODescriptor protocolSupportEnumeration="urn:oasis:names:tc:SAML:2.0:protocol">
…
<SingleLogoutService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect"
Location="https://login.microsoftonline.com/common/saml2" />
<SingleSignOnService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect"
Location="https://login.microsoftonline.com/common/saml2" />
</IDPSSODescriptor>
Application and service principal objects in Azure
Active Directory (Azure AD)
5/1/2017 • 3 min to read • Edit Online
Sometimes the meaning of the term "application" can be misunderstood when used in the context of Azure AD.
The goal of this article is to make it clearer, by clarifying conceptual and concrete aspects of Azure AD application
integration, with an illustration of registration and consent for a multi-tenant application.
Overview
An application that has been integrated with Azure AD has implications that go beyond the software aspect.
"Application" is frequently used as a conceptual term, referring to not only the the application software, but also
its Azure AD registration and role in authentication/authorization "conversations" at runtime. By definition, an
application can function in a client role (consuming a resource), a resource server role (exposing APIs to clients),
or even both. The conversation protocol is defined by an OAuth 2.0 Authorization Grant flow, allowing the
client/resource to access/protect a resource's data respectively. Now let's go a level deeper, and see how the
Azure AD application model represents an application at design-time and run-time.
Application registration
When you register an Azure AD application in the Azure portal, two objects are created in your Azure AD tenant:
an application object, and a service principal object.
Application object
An Azure AD application is defined by its one and only application object, which resides in the Azure AD tenant
where the application was registered, known as the application's "home" tenant. The Azure AD Graph Application
entity defines the schema for an application object's properties.
Service principal object
The service principal object defines the policy and permissions for an application's use in a specific tenant,
providing the basis for a security principal to represent the application at run-time. The Azure AD Graph
ServicePrincipal entity defines the schema for a service principal object's properties.
Application and service principal relationship
Consider the application object as the global representation of your application for use across all tenants, and the
service principal as the local representation for use in a specific tenant. The application object serves as the
template from which common and default properties are derived for use in creating corresponding service
principal objects. An application object therefore has a 1:1 relationship with the software application, and a
1:many relationship with its corresponding service principal object(s).
A service principal must be created in each tenant where the application will be used, enabling it to establish an
identity for sign-in and/or access to resources being secured by the tenant. A single-tenant application will have
only one service principal (in its home tenant), usually created and consented for use during application
registration. A multi-tenant Web application/API will also have a service principal created in each tenant where a
user from that tenant has consented to its use.
NOTE
Any changes you make to your application object, are also reflected in its service principal object in the application's home
tenant only (the tenant where it was registered). For multi-tenant applications, changes to the application object are not
reflected in any consumer tenants' service principal objects, until the access is removed via the Application Access Panel
and granted again.
Also note that native applications are registered as multi-tenant by default.
Example
The following diagram illustrates the relationship between an application's application object and corresponding
service principal objects, in the context of a sample multi-tenant application called HR app. There are three Azure
AD tenants in this scenario:
Adatum - the tenant used by the company that developed the HR app
Contoso - the tenant used by the Contoso organization, which is a consumer of the HR app
Fabrikam - the tenant used by the Fabrikam organization, which also consumes the HR app
In the previous diagram, Step 1 is the process of creating the application and service principal objects in the
application's home tenant.
In Step 2, when Contoso and Fabrikam administrators complete consent, a service principal object is created in
their company's Azure AD tenant and assigned the permissions that the administrator granted. Also note that the
HR app could be configured/designed to allow consent by users for individual use.
In Step 3, the consumer tenants of the HR application (Contoso and Fabrikam) each have their own service
principal object. Each represents their use of an instance of the application at runtime, governed by the
permissions consented by the respective administrator.
Next steps
An application's application object can be accessed via the Azure AD Graph API, the Azure portal's application
manifest editor, or Azure AD PowerShell cmdlets, as represented by its OData Application entity.
An application's service principal object can be accessed via the Azure AD Graph API or Azure AD PowerShell
cmdlets, as represented by its OData ServicePrincipal entity.
The Azure AD Graph Explorer is useful for querying both the application and service principal objects.
How and why applications are added to Azure AD
3/28/2017 • 6 min to read • Edit Online
One of the initially puzzling things when viewing a list of applications in your instance of Azure Active Directory is
understanding where the applications came from and why they are there. This article will provide a high level
overview of how applications are represented in the directory and provide you with context that will assist you in
understanding how an application came to be in your directory.
What services does Azure AD provide to applications?
Applications are added to Azure AD to leverage one or more of the services it provides. Those services include:
App authentication and authorization
User authentication & authorization
Single sign-on (SSO) using federation or password
User provisioning & synchronization
Role-based access control; Use the directory to define application roles to perform roles based authorization
checks in an app.
oAuth authorization services (used by Office 365 and other Microsoft apps to authorize access to
APIs/resources.)
Application publishing & proxy; Publish an app from a private network to the internet
How are applications represented in the directory?
Applications are represented in the Azure AD using 2 objects: an application object and a service principal object.
There is one application object, registered in a "home"/"owner" or "publishing" directory and one or more service
principal objects representing the application in every directory in which it acts.
The application object describes the app to Azure AD (the multi-tenant service) and may include any of the
following: (Note: This is not an exhaustive list.)
Name, Logo & Publisher
Secrets (symmetric and/or asymmetric keys used to authenticate the app)
API dependencies (oAuth)
APIs/resources/scopes published (oAuth)
App roles (RBAC)
SSO metadata and configuration (SSO)
User provisioning metadata and configuration
Proxy metadata and configuration
The service principal is a record of the application in every directory, where the application acts including its home
directory. The service principal:
Refers back to an application object via the app id property
Records local user and group app-role assignments
Records local user and admin permissions granted to the app
For example: permission for the app to access a particular users email
Records local policies including conditional access policy
Records local alternate local settings for an app
Claims transformation rules
Attribute mappings (User provisioning)
Tenant specific app roles (if the app supports custom roles)
Name/Logo
A diagram of application objects and service principals across directories
As you can see from the diagram above. Microsoft maintains two directories internally (on the left) it uses to
publish applications.
One for Microsoft Apps (Microsoft services directory)
One for pre-integrated 3rd Party Apps (App Gallery directory)
Application publishers/vendors who integrate with Azure AD are required to have a publishing directory. (Some
SAAS Directory).
Applications that you add yourself include:
Apps you developed (integrated with AAD)
Apps you connected for single-sign-on
Apps you published using the Azure AD application proxy.
A couple of notes and exceptions
Not all service principals point back to application objects. Huh? When Azure AD was originally built the services
provided to applications were much more limited and the service principal was sufficient for establishing an app
identity. The original service principal was closer in shape to the Windows Server Active Directory service
account. For this reason it's still possible to create service principals using the Azure AD PowerShell without first
creating an application object. The Graph API requires an app object before creating a service principal.
Not all of the information described above is currently exposed programmatically. The following are only
available in the UI:
Claims transformation rules
Attribute mappings (User provisioning)
For more detailed information on the service principal and application objects please refer to the Azure AD
Graph REST API reference documentation. Hint: The Azure AD Graph API documentation is the closest thing to a
schema reference for Azure AD that's currently available.
Application
Service Principal
How are apps added to my Azure AD instance?
There are many ways an app can be added to Azure AD:
Add an app from the Azure Active Directory App Gallery
Sign up/into a 3rd Party App integrated with Azure Active Directory (For example: Smartsheet or DocuSign)
During sign up/in users are asked to give permission to the app to access their profile and other
permissions. The first person to give consent causes a service principal representing the app to be added
to the directory.
Sign up/into Microsoft online services like Office 365
When you subscribe to Office 365 or begin a trial one or more service principals are created in the
directory representing the various services that are used to deliver all of the functionality associated with
Office 365.
Some Office 365 services like SharePoint create service principals on an on-going basis to allow secure
communication between components including workflows.
Add an app you're developing in the Azure Management Portal see:
https://msdn.microsoft.com/library/azure/dn132599.aspx
Add an app you're developing using Visual Studio see:
ASP.Net Authentication Methods
Connected Services
Add an app to use to use the Azure AD Application Proxy
Connect an app for single sign on using SAML or Password SSO
Many others including various developer experiences in Azure and/in API explorer experiences across developer
centers
Who has permission to add applications to my Azure AD instance?
Only global administrators can:
Add apps from the Azure AD app gallery (pre-integrated 3rd Party Apps)
Publish an app using the Azure AD Application Proxy
All users in your directory have rights to add applications that they are developing and discretion over which
applications they share/give access to their organizational data. Remember user sign up/in to an app and granting
permissions may result in a service principal being created.
This might initially sound concerning, but keep the following in mind:
Apps have been able to leverage Windows Server Active Directory for user authentication for many years
without requiring the application to be registered/recorded in the directory. Now the organization will have
improved visibility to exactly how many apps are using the directory and what for.
No need for admin driven app publishing/registration process. With Active Directory Federation Services it was
likely that an admin had to add an app as a relying party on behalf of developers. Now developers can selfservice.
Users signing in/up to apps using their organization accounts for business purposes is a good thing. If they
subsequently leave the organization they will lose access to their account in the application they were using.
Having a record of what data was shared with which application is a good thing. Data is more transportable
than ever and having a clear record of who shared what data with which applications is useful.
Apps who use Azure AD for oAuth decide exactly what permissions that users are able to grant to applications
and which permissions require an admin to agree to. It should go without saying that only admins can consent
to larger scopes and more significant permissions.
Users adding and allowing apps to access their data are audited events so you can view the Audit Reports
within the Azure Managment portal to determine how an app was added to the directory.
Note: Microsoft itself has been operating using the default configuration for many months now.
With all of that said it is possible to prevent users in your directory from adding applications and from exercising
discretion over what information they share with applications by modifying Directory configuration in the Azure
Management portal. The following configuration can be accessed within the Azure Management portal on your
Directory's "Configure" tab.
Next steps
Learn more about how to add applications to Azure AD and how to configure services for apps.
Developers: Learn how to integrate an application with AAD
Developers: Review sample code for apps integrated with Azure Active Directory on GitHub
Developers and IT Pros: Review the REST API documentation for the Azure Active Directory Graph API
IT Pros: Learn how to use Azure Active Directory pre-integrated applications from the App Gallery
IT Pros: Find tutorials for configuring specific pre-integrated apps
IT Pros: Learn how to publish an app using the Azure Active Directory Application Proxy
See also
Article Index for Application Management in Azure Active Directory
Understanding the Azure Active Directory
application manifest
2/10/2017 • 6 min to read • Edit Online
Applications that integrate with Azure Active Directory (AD) must be registered with an Azure AD tenant,
providing a persistent identity configuration for the application. This configuration is consulted at runtime,
enabling scenarios that allow an application to outsource and broker authentication/authorization through Azure
AD. For more information about the Azure AD application model, see the Adding, Updating, and Removing an
Application article.
Updating an application's identity configuration
There are actually multiple options available for updating the properties on an application's identity configuration,
which vary in capabilities and degrees of difficulty, including the following:
The Azure portal's Web user interface allows you to update the most common properties of an application.
This is the quickest and least error prone way of updating your application's properties, but does not give you
full access to all properties, like the next two methods.
For more advanced scenarios where you need to update properties that are not exposed in the Azure classic
portal, you can modify the application manifest. This is the focus of this article and is discussed in more
detail starting in the next section.
It's also possible to write an application that uses the Graph API to update your application, which requires
the most effort. This may be an attractive option though, if you are writing management software, or need to
update application properties on a regular basis in an automated fashion.
Using the application manifest to update an application's identity
configuration
Through the Azure portal, you can manage your application's identity configuration by updating the application
manifest using the inline manifest editor. You can also download and upload the application manifest as a JSON
file. No actual file is stored in the directory. The application manifest is merely an HTTP GET operation on the
Azure AD Graph API Application entity, and the upload is an HTTP PATCH operation on the Application entity.
As a result, in order to understand the format and properties of the application manifest, you will need to
reference the Graph API Application entity documentation. Examples of updates that can be performed though
application manifest upload include:
Declare permission scopes (oauth2Permissions) exposed by your web API. See the "Exposing Web APIs to
Other Applications" topic in Integrating Applications with Azure Active Directory for information on
implementing user impersonation using the oauth2Permissions delegated permission scope. As mentioned
previously, Application entity properties are documented in the Graph API Entity and Complex Type reference
article, including the oauth2Permissions property which is a collection of type OAuth2Permission.
Declare application roles (appRoles) exposed by your app. The Application entity's appRoles property is a
collection of type AppRole. See the Role based access control in cloud applications using Azure AD article for
an implementation example.
Declare known client applications (knownClientApplications), which allow you to logically tie the
consent of the specified client application(s) to the resource/web API.
Request Azure AD to issue group memberships claim for the signed in user (groupMembershipClaims).
This can also be configured to issue claims about the user's directory roles memberships. See the
Authorization in Cloud Applications using AD Groups article for an implementation example.
Allow your application to support OAuth 2.0 Implicit grant flows (oauth2AllowImplicitFlow). This type of
grant flow is used with embedded JavaScript web pages or Single Page Applications (SPA). For more
information on the implicit authorization grant, see Understanding the OAuth2 implicit grant flow in Azure
Active Directory.
Enable use of X509 certificates as the secret key (keyCredentials). See the Build service and daemon apps
in Office 365 and Developer’s guide to auth with Azure Resource Manager API articles for implementation
examples.
Add a new App ID URI for your application (identifierURIs[]). App ID URIs are used to uniquely identify an
application within its Azure AD tenant (or across multiple Azure AD tenants, for multi-tenant scenarios when
qualified via verified custom domain). They are used when requesting permissions to a resource application, or
acquiring an access token for a resource application. When you update this element, the same update is made
to the corresponding service principal's servicePrincipalNames[] collection, which lives in the application's
home tenant.
The application manifest also provides a good way to track the state of your application registration. Because it's
available in JSON format, the file representation can be checked into your source control, along with your
application's source code.
Step by step example
Now lets walk through the steps required to update your application's identity configuration through the
application manifest. We will highlight one of the preceding examples, showing how to declare a new permission
scope on a resource application:
1.
2.
3.
4.
5.
6.
Sign in to the Azure portal.
After you've authenticated, choose your Azure AD tenant by selecting it from the top right corner of the page.
Select Azure Active Directory extension from the left navigation panel and click on App Registrations.
Find the application you want to update in the list and click on it.
From the application page, click Manifest to open the inline manifest editor.
You can directly edit the manifest using this editor. Note that the manifest follows the schema for the
Application entity as we mentioned earlier: For example, assuming we want to implement/expose a new
permission called "Employees.Read.All" on our resource application (API), you would simply add a
new/second element to the oauth2Permissions collection, ie:
"oauth2Permissions": [
{
"adminConsentDescription": "Allow the application to access MyWebApplication on behalf of the signedin user.",
"adminConsentDisplayName": "Access MyWebApplication",
"id": "aade5b35-ea3e-481c-b38d-cba4c78682a0",
"isEnabled": true,
"type": "User",
"userConsentDescription": "Allow the application to access MyWebApplication on your behalf.",
"userConsentDisplayName": "Access MyWebApplication",
"value": "user_impersonation"
},
{
"adminConsentDescription": "Allow the application to have read-only access to all Employee data.",
"adminConsentDisplayName": "Read-only access to Employee records",
"id": "2b351394-d7a7-4a84-841e-08a6a17e4cb8",
"isEnabled": true,
"type": "User",
"userConsentDescription": "Allow the application to have read-only access to your Employee data.",
"userConsentDisplayName": "Read-only access to your Employee records",
"value": "Employees.Read.All"
}
],
The entry must be unique, and you must therefore generate a new Globally Unique ID (GUID) for the "id"
property. In this case, because we specified "type": "User" , this permission can be consented to by any
account authenticated by the Azure AD tenant in which the resource/API application is registered. This
grants the client application permission to access it on the account's behalf. The description and display
name strings are used during consent and for display in the Azure portal.
7. When you're finished updating the manifest, click Save to save the manifest.
Now that the manifest is saved, you can give a registered client application access to the new permission we
added above. This time you can use the Azure portal's Web UI instead of editing the client application's manifest:
1. First go to the Settings blade of the client application to which you wish to add access to the new API, click
Required Permissions and choose Select an API.
2. Then you will be presented with the list of registered resource applications (APIs) in the tenant. Click the
resource application to select it, or type the name of the application the search box. When you've found the
application, click Select.
3. This will take you to the Select Permissions page, which will show the list of Application Permissions and
Delegated Permissions available for the resource application. Select the new permission in order to add it to
the client's requested list of permissions. This new permission will be stored in the client application's identity
configuration, in the "requiredResourceAccess" collection property.
That's it. Now your applications will run using their new identity configuration.
Next steps
For more details on the relationship between an application's Application and Service Principal object(s), see
Application and service principal objects in Azure AD.
See the Azure AD developer glossary for definitions of some of the core Azure Active Directory (AD) developer
concepts.
Please use the comments section below to provide feedback and help us refine and shape our content.
Configurable token lifetimes in Azure Active
Directory (Public Preview)
3/28/2017 • 20 min to read • Edit Online
You can specify the lifetime of a token issued by Azure Active Directory (Azure AD). You can set token lifetimes for
all apps in your organization, for a multi-tenant (multi-organization) application, or for a specific service principal in
your organization.
NOTE
This capability currently is in Public Preview. Be prepared to revert or remove any changes. The feature is available in any
Azure Active Directory subscription during Public Preview. However, when the feature becomes generally available, some
aspects of the feature might require an Azure Active Directory Premium subscription.
In Azure AD, a policy object represents a set of rules that are enforced on individual applications or on all
applications in an organization. Each policy type has a unique structure, with a set of properties that are applied to
objects to which they are assigned.
You can designate a policy as the default policy for your organization. The policy is applied to any application in the
organization, as long as it is not overridden by a policy with a higher priority. You also can assign a policy to
specific applications. The order of priority varies by policy type.
Token types
You can set token lifetime policies for refresh tokens, access tokens, session tokens, and ID tokens.
Access tokens
Clients use access tokens to access a protected resource. An access token can be used only for a specific
combination of user, client, and resource. Access tokens cannot be revoked and are valid until their expiry. A
malicious actor that has obtained an access token can use it for extent of its lifetime. Adjusting the lifetime of an
access token is a trade-off between improving system performance and increasing the amount of time that the
client retains access after the user’s account is disabled. Improved system performance is achieved by reducing the
number of times a client needs to acquire a fresh access token.
Refresh tokens
When a client acquires an access token to access a protected resource, the client receives both a refresh token and
an access token. The refresh token is used to obtain new access/refresh token pairs when the current access token
expires. A refresh token is bound to a combination of user and client. A refresh token can be revoked, and the
token's validity is checked every time the token is used.
It's important to make a distinction between confidential clients and public clients. For more information about
different types of clients, see RFC 6749.
Token lifetimes with confidential client refresh tokens
Confidential clients are applications that can securely store a client password (secret). They can prove that requests
are coming from the client application and not from a malicious actor. For example, a web app is a confidential
client because it can store a client secret on the web server. It is not exposed. Because these flows are more secure,
the default lifetimes of refresh tokens issued to these flows is until-revoked , cannot be changed by using policy,
and will not be revoked on voluntary password resets.
Token lifetimes with public client refresh tokens
Public clients cannot securely store a client password (secret). For example, an iOS/Android app cannot obfuscate a
secret from the resource owner, so it is considered a public client. You can set policies on resources to prevent
refresh tokens from public clients older than a specified period from obtaining a new access/refresh token pair. (To
do this, use the Refresh Token Max Inactive Time property.) You also can use policies to set a period beyond which
the refresh tokens are no longer accepted. (To do this, use the Refresh Token Max Age property.) You can adjust the
lifetime of a refresh token to control when and how often the user is required to reenter credentials, instead of
being silently reauthenticated, when using a public client application.
ID tokens
ID tokens are passed to websites and native clients. ID tokens contain profile information about a user. An ID token
is bound to a specific combination of user and client. ID tokens are considered valid until their expiry. Usually, a
web application matches a user’s session lifetime in the application to the lifetime of the ID token issued for the
user. You can adjust the lifetime of an ID token to control how often the web application expires the application
session, and how often it requires the user to be reauthenticated with Azure AD (either silently or interactively).
Single sign-on session tokens
When a user authenticates with Azure AD and selects the Keep me signed in check box, a single sign-on session
(SSO) is established with the user’s browser and Azure AD. The SSO token, in the form of a cookie, represents this
session. Note that the SSO session token is not bound to a specific resource/client application. SSO session tokens
can be revoked, and their validity is checked every time they are used.
Azure AD uses two kinds of SSO session tokens: persistent and nonpersistent. Persistent session tokens are stored
as persistent cookies by the browser. Nonpersistent session tokens are stored as session cookies. (Session cookies
are destroyed when the browser is closed.)
Nonpersistent session tokens have a lifetime of 24 hours. Persistent tokens have a lifetime of 180 days. Any time
an SSO session token is used within its validity period, the validity period is extended another 24 hours or 180
days, depending on the token type. If an SSO session token is not used within its validity period, it is considered
expired and is no longer accepted.
You can use a policy to set the time after the first session token was issued beyond which the session token is no
longer accepted. (To do this, use the Session Token Max Age property.) You can adjust the lifetime of a session
token to control when and how often a user is required to reenter credentials, instead of being silently
authenticated, when using a web application.
Token lifetime policy properties
A token lifetime policy is a type of policy object that contains token lifetime rules. Use the properties of the policy to
control specified token lifetimes. If no policy is set, the system enforces the default lifetime value.
Configurable token lifetime properties
PROPERTY
POLICY PROPERTY
STRING
Access Token
Lifetime
AFFECTS
DEFAULT
MINIMUM
MAXIMUM
AccessTokenLifeti
me
Access tokens, ID
tokens, SAML2
tokens
1 hour
10 minutes
1 day
Refresh Token
Max Inactive
Time
MaxInactiveTime
Refresh tokens
14 days
10 minutes
90 days
Single-Factor
Refresh Token
Max Age
MaxAgeSingleFac
tor
Refresh tokens
(for any users)
90 days
10 minutes
Until-revoked1
POLICY PROPERTY
STRING
AFFECTS
DEFAULT
MINIMUM
MAXIMUM
Multi-Factor
Refresh Token
Max Age
MaxAgeMultiFact
or
Refresh tokens
(for any users)
90 days
10 minutes
Until-revoked1
Single-Factor
Session Token
Max Age
MaxAgeSessionSi
ngleFactor2
Session tokens
(persistent and
nonpersistent)
Until-revoked
10 minutes
Until-revoked1
Multi-Factor
Session Token
Max Age
MaxAgeSessionM
ultiFactor3
Session tokens
(persistent and
nonpersistent)
Until-revoked
10 minutes
Until-revoked1
PROPERTY
1365
days is the maximum explicit length that can be set for these attributes.
2If MaxAgeSessionSingleFactor is not set, this value takes the MaxAgeSingleFactor value. If neither
parameter is set, the property takes the default value (until-revoked).
3If MaxAgeSessionMultiFactor is not set, this value takes the MaxAgeMultiFactor value. If neither parameter
is set, the property takes the default value (until-revoked).
Exceptions
PROPERTY
AFFECTS
DEFAULT
Refresh Token Max Inactive Time
(issued for federated users who have
insufficient revocation information)
Refresh tokens (issued for federated
users who have insufficient revocation
information)
12 hours
Refresh Token Max Inactive Time
(issued for confidential clients)
Refresh tokens (issued for confidential
clients)
90 days
Refresh Token Max Age (issued for
confidential clients)
Refresh tokens (issued for confidential
clients)
Until-revoked
Policy evaluation and prioritization
You can create and then assign a token lifetime policy to a specific application, to your organization, and to service
principals. Multiple policies might apply to a specific application. The token lifetime policy that takes effect follows
these rules:
If a policy is explicitly assigned to the service principal, it is enforced.
If no policy is explicitly assigned to the service principal, a policy explicitly assigned to the parent organization of
the service principal is enforced.
If no policy is explicitly assigned to the service principal or to the organization, the policy assigned to the
application is enforced.
If no policy has been assigned to the service principal, the organization, or the application object, the default
values is enforced. (See the table in Configurable token lifetime properties.)
For more information about the relationship between application objects and service principal objects, see
Application and service principal objects in Azure Active Directory.
A token’s validity is evaluated at the time the token is used. The policy with the highest priority on the application
that is being accessed takes effect.
NOTE
Here's an example scenario.
A user wants to access two web applications: Web Application A and Web Application B.
Factors:
Both web applications are in the same parent organization.
Token Lifetime Policy 1 with a Session Token Max Age of eight hours is set as the parent organization’s default.
Web Application A is a regular-use web application and isn’t linked to any policies.
Web Application B is used for highly sensitive processes. Its service principal is linked to Token Lifetime Policy 2, which has
a Session Token Max Age of 30 minutes.
At 12:00 PM, the user starts a new browser session and tries to access Web Application A. The user is redirected to Azure AD
and is asked to sign in. This creates a cookie that has a session token in the browser. The user is redirected back to Web
Application A with an ID token that allows the user to access the application.
At 12:15 PM, the user tries to access Web Application B. The browser redirects to Azure AD, which detects the session cookie.
Web Application B’s service principal is linked to Token Lifetime Policy 2, but it's also part of the parent organization, with
default Token Lifetime Policy 1. Token Lifetime Policy 2 takes effect because policies linked to service principals have a higher
priority than organization default policies. The session token was originally issued within the last 30 minutes, so it is
considered valid. The user is redirected back to Web Application B with an ID token that grants them access.
At 1:00 PM, the user tries to access Web Application A. The user is redirected to Azure AD. Web Application A is not linked to
any policies, but because it is in an organization with default Token Lifetime Policy 1, that policy takes effect. The session
cookie that was originally issued within the last eight hours is detected. The user is silently redirected back to Web
Application A with a new ID token. The user is not required to authenticate.
Immediately afterward, the user tries to access Web Application B. The user is redirected to Azure AD. As before, Token
Lifetime Policy 2 takes effect. Because the token was issued more than 30 minutes ago, the user is prompted to reenter their
sign-in credentials. A brand-new session token and ID token are issued. The user can then access Web Application B.
Configurable policy property details
Access Token Lifetime
String: AccessTokenLifetime
Affects: Access tokens, ID tokens
Summary: This policy controls how long access and ID tokens for this resource are considered valid. Reducing the
Access Token Lifetime property mitigates the risk of an access token or ID token being used by a malicious actor
for an extended period of time. (These tokens cannot be revoked.) The trade-off is that performance is adversely
affected, because the tokens have to be replaced more often.
Refresh Token Max Inactive Time
String: MaxInactiveTime
Affects: Refresh tokens
Summary: This policy controls how old a refresh token can be before a client can no longer use it to retrieve a new
access/refresh token pair when attempting to access this resource. Because a new refresh token usually is returned
when a refresh token is used, this policy prevents access if the client tries to access any resource by using the
current refresh token during the specified period of time.
This policy forces users who have not been active on their client to reauthenticate to retrieve a new refresh token.
The Refresh Token Max Inactive Time property must be set to a lower value than the Single-Factor Token Max Age
and the Multi-Factor Refresh Token Max Age properties.
Single -Factor Refresh Token Max Age
String: MaxAgeSingleFactor
Affects: Refresh tokens
Summary: This policy controls how long a user can use a refresh token to get a new access/refresh token pair after
they last authenticated successfully by using only a single factor. After a user authenticates and receives a new
refresh token, the user can use the refresh token flow for the specified period of time. (This is true as long as the
current refresh token is not revoked, and it is not left unused for longer than the inactive time.) At that point, the
user is forced to reauthenticate to receive a new refresh token.
Reducing the max age forces users to authenticate more often. Because single-factor authentication is considered
less secure than multi-factor authentication, we recommend that you set this property to a value that is equal to or
lesser than the Multi-Factor Refresh Token Max Age property.
Multi-Factor Refresh Token Max Age
String: MaxAgeMultiFactor
Affects: Refresh tokens
Summary: This policy controls how long a user can use a refresh token to get a new access/refresh token pair after
they last authenticated successfully by using multiple factors. After a user authenticates and receives a new refresh
token, the user can use the refresh token flow for the specified period of time. (This is true as long as the current
refresh token is not revoked, and it is not unused for longer than the inactive time.) At that point, users are forced
to reauthenticate to receive a new refresh token.
Reducing the max age forces users to authenticate more often. Because single-factor authentication is considered
less secure than multi-factor authentication, we recommend that you set this property to a value that is equal to or
greater than the Single-Factor Refresh Token Max Age property.
Single -Factor Session Token Max Age
String: MaxAgeSessionSingleFactor
Affects: Session tokens (persistent and nonpersistent)
Summary: This policy controls how long a user can use a session token to get a new ID and session token after
they last authenticated successfully by using only a single factor. After a user authenticates and receives a new
session token, the user can use the session token flow for the specified period of time. (This is true as long as the
current session token is not revoked and has not expired.) After the specified period of time, the user is forced to
reauthenticate to receive a new session token.
Reducing the max age forces users to authenticate more often. Because single-factor authentication is considered
less secure than multi-factor authentication, we recommend that you set this property to a value that is equal to or
less than the Multi-Factor Session Token Max Age property.
Multi-Factor Session Token Max Age
String: MaxAgeSessionMultiFactor
Affects: Session tokens (persistent and nonpersistent)
Summary: This policy controls how long a user can use a session token to get a new ID and session token after the
last time they authenticated successfully by using multiple factors. After a user authenticates and receives a new
session token, the user can use the session token flow for the specified period of time. (This is true as long as the
current session token is not revoked and has not expired.) After the specified period of time, the user is forced to
reauthenticate to receive a new session token.
Reducing the max age forces users to authenticate more often. Because single-factor authentication is considered
less secure than multi-factor authentication, we recommend that you set this property to a value that is equal to or
greater than the Single-Factor Session Token Max Age property.
Example token lifetime policies
Many scenarios are possible in Azure AD when you can create and manage token lifetimes for apps, service
principals, and your overall organization. In this section, we walk through a few common policy scenarios that can
help you impose new rules for:
Token Lifetime
Token Max Inactive Time
Token Max Age
In the examples, you can learn how to:
Manage an organization's default policy
Create a policy for web sign-in
Create a policy for a native app that calls a web API
Manage an advanced policy
Prerequisites
In the following examples, you create, update, link, and delete policies for apps, service principals, and your overall
organization. If you are new to Azure AD, we recommend that you learn about how to get an Azure AD tenant
before you proceed with these examples.
To get started, do the following steps:
1. Download the latest Azure AD PowerShell Module Public Preview release.
2. Run the Connect command to sign in to your Azure AD admin account. Run this command each time you
start a new session.
Connect-AzureAD -Confirm
3. To see all policies that have been created in your organization, run the following command. Run this
command after most operations in the following scenarios. Running the command also helps you get the **
** of your policies.
Get-AzureADPolicy
Example: Manage an organization's default policy
In this example, you create a policy that lets your users sign in less frequently across your entire organization. To
do this, create a token lifetime policy for Single-Factor Refresh Tokens, which is applied across your organization.
The policy is applied to every application in your organization, and to each service principal that doesn’t already
have a policy set.
1. Create a token lifetime policy.
a. Set the Single-Factor Refresh Token to "until-revoked." The token doesn't expire until access is
revoked. Create the following policy definition:
@('{
"TokenLifetimePolicy":
{
"Version":1,
"MaxAgeSingleFactor":"until-revoked"
}
}')
b. To create the policy, run the following command:
New-AzureADPolicy -Definition @('{"TokenLifetimePolicy":{"Version":1,
"MaxAgeSingleFactor":"until-revoked"}}') -DisplayName "OrganizationDefaultPolicyScenario" IsOrganizationDefault $true -Type "TokenLifetimePolicy"
c. To see your new policy, and to get the policy's ObjectId, run the following command:
Get-AzureADPolicy
2. Update the policy.
You might decide that the first policy you set in this example is not as strict as your service requires. To set
your Single-Factor Refresh Token to expire in two days, run the following command:
Set-AzureADPolicy -Id <ObjectId FROM GET COMMAND> -DisplayName
"OrganizationDefaultPolicyUpdatedScenario" -Definition @('{"TokenLifetimePolicy":
{"Version":1,"MaxAgeSingleFactor":"2.00:00:00"}}')
Example: Create a policy for web sign-in
In this example, you create a policy that requires users to authenticate more frequently in your web app. This policy
sets the lifetime of the access/ID tokens and the max age of a multi-factor session token to the service principal of
your web app.
1. Create a token lifetime policy.
This policy, for web sign-in, sets the access/ID token lifetime and the max single-factor session token age to
two hours.
a. To create the policy, run this command:
New-AzureADPolicy -Definition @('{"TokenLifetimePolicy":
{"Version":1,"AccessTokenLifetime":"02:00:00","MaxAgeSessionSingleFactor":"02:00:00"}}') DisplayName "WebPolicyScenario" -IsOrganizationDefault $false -Type "TokenLifetimePolicy"
b. To see your new policy, and to get the policy ObjectId, run the following command:
Get-AzureADPolicy
2. Assign the policy to your service principal. You also need to get the ObjectId of your service principal.
a. To see all your organization's service principals, you can query Microsoft Graph. Or, in Azure AD
Graph Explorer, sign in to your Azure AD account.
b. When you have the ObjectId of your service principal, run the following command:
Add-AzureADServicePrincipalPolicy -Id <ObjectId of the ServicePrincipal> -RefObjectId <ObjectId
of the Policy>
Example: Create a policy for a native app that calls a web API
In this example, you create a policy that requires users to authenticate less frequently. The policy also lengthens the
amount of time a user can be inactive before the user must reauthenticate. The policy is applied to the web API.
When the native app requests the web API as a resource, this policy is applied.
1. Create a token lifetime policy.
a. To create a strict policy for a web API, run the following command:
New-AzureADPolicy -Definition @('{"TokenLifetimePolicy":
{"Version":1,"MaxInactiveTime":"30.00:00:00","MaxAgeMultiFactor":"untilrevoked","MaxAgeSingleFactor":"180.00:00:00"}}') -DisplayName "WebApiDefaultPolicyScenario" IsOrganizationDefault $false -Type "TokenLifetimePolicy"
b. To see your new policy, and to get the policy ObjectId, run the following command:
Get-AzureADPolicy
2. Assign the policy to your web API. You also need to get the ObjectId of your application. The best way to
find your app's ObjectId is to use the Azure portal.
When you have the ObjectId of your app, run the following command:
```PowerShell
Add-AzureADApplicationPolicy -Id <ObjectId of the Application> -RefObjectId <ObjectId of the Policy>
```
Example: Manage an advanced policy
In this example, you create a few policies, to learn how the priority system works. You also can learn how to
manage multiple policies that are applied to several objects.
1. Create a token lifetime policy.
a. To create an organization default policy that sets the Single-Factor Refresh Token lifetime to 30 days,
run the following command:
New-AzureADPolicy -Definition @('{"TokenLifetimePolicy":
{"Version":1,"MaxAgeSingleFactor":"30.00:00:00"}}') -DisplayName "ComplexPolicyScenario" IsOrganizationDefault $true -Type "TokenLifetimePolicy"
b. To see your new policy, and to get the policy's ObjectId, run the following command:
Get-AzureADPolicy
2. Assign the policy to a service principal.
Now, you have a policy that applies to the entire organization. You might want to preserve this 30-day
policy for a specific service principal, but change the organization default policy to the upper limit of "untilrevoked."
a. To see all your organization's service principals, you can query Microsoft Graph. Or, in Azure AD
Graph Explorer, sign in by using your Azure AD account.
b. When you have the ObjectId of your service principal, run the following command:
```PowerShell
Add-AzureADServicePrincipalPolicy -Id <ObjectId of the ServicePrincipal> -RefObjectId <ObjectId
of the Policy>
```
3. Set the
IsOrganizationDefault
flag to false:
Set-AzureADPolicy -Id <ObjectId of Policy> -DisplayName "ComplexPolicyScenario" -IsOrganizationDefault
$false
4. Create a new organization default policy:
New-AzureADPolicy -Definition @('{"TokenLifetimePolicy":{"Version":1,"MaxAgeSingleFactor":"untilrevoked"}}') -DisplayName "ComplexPolicyScenarioTwo" -IsOrganizationDefault $true -Type
"TokenLifetimePolicy"
You now have the original policy linked to your service principal, and the new policy is set as your
organization default policy. It's important to remember that policies applied to service principals have
priority over organization default policies.
Cmdlet reference
Manage policies
You can use the following cmdlets to manage policies.
New-AzureADPolicy
Creates a new policy.
New-AzureADPolicy -Definition <Array of Rules> -DisplayName <Name of Policy> -IsOrganizationDefault <boolean>
-Type <Policy Type>
PARAMETERS
DESCRIPTION
EXAMPLE
Definition
Array of stringified JSON that contains
all the policy's rules.
-Definition @('{"TokenLifetimePolicy":
{"Version":1,"MaxInactiveTime":"20:00:00"}}')
DisplayName
String of the policy name.
-DisplayName "MyTokenPolicy"
IsOrganizationDefault
If true, sets the policy as the
organization's default policy. If false,
does nothing.
-IsOrganizationDefault $true
Type
Type of policy. For token lifetimes,
always use "TokenLifetimePolicy."
-Type "TokenLifetimePolicy"
Sets an alternative ID for the policy.
-AlternativeIdentifier "myAltId"
AlternativeIdentifier
[Optional]
Get-AzureADPolicy
Gets all Azure AD policies or a specified policy.
Get-AzureADPolicy
PARAMETERS
Id
DESCRIPTION
[Optional]
ObjectId (Id) of the policy you want.
EXAMPLE
-Id <ObjectId of Policy>
Get-AzureADPolicyAppliedObject
Gets all apps and service principals that are linked to a policy.
Get-AzureADPolicyAppliedObject -Id <ObjectId of Policy>
PARAMETERS
DESCRIPTION
ObjectId (Id) of the policy you want.
Id
EXAMPLE
-Id <ObjectId of Policy>
Set-AzureADPolicy
Updates an existing policy.
Set-AzureADPolicy -Id <ObjectId of Policy> -DisplayName <string>
PARAMETERS
DESCRIPTION
EXAMPLE
Id
ObjectId (Id) of the policy you want.
-Id <ObjectId of Policy>
DisplayName
String of the policy name.
-DisplayName "MyTokenPolicy"
Array of stringified JSON that contains
all the policy's rules.
-Definition @('{"TokenLifetimePolicy":
{"Version":1,"MaxInactiveTime":"20:00:00"}}')
If true, sets the policy as the
organization's default policy. If false,
does nothing.
-IsOrganizationDefault $true
Type of policy. For token lifetimes,
always use "TokenLifetimePolicy."
-Type "TokenLifetimePolicy"
Sets an alternative ID for the policy.
-AlternativeIdentifier "myAltId"
Definition
[Optional]
IsOrganizationDefault
Type
[Optional]
[Optional]
AlternativeIdentifier
[Optional]
Remove-AzureADPolicy
Deletes the specified policy.
Remove-AzureADPolicy -Id <ObjectId of Policy>
PARAMETERS
Id
DESCRIPTION
ObjectId (Id) of the policy you want.
EXAMPLE
-Id <ObjectId of Policy>
Application policies
You can use the following cmdlets for application policies.
Add-AzureADApplicationPolicy
Links the specified policy to an application.
Add-AzureADApplicationPolicy -Id <ObjectId of Application> -RefObjectId <ObjectId of Policy>
PARAMETERS
DESCRIPTION
EXAMPLE
Id
ObjectId (Id) of the application.
-Id <ObjectId of Application>
RefObjectId
ObjectId of the policy.
-RefObjectId <ObjectId of Policy>
Get-AzureADApplicationPolicy
Gets the policy that is assigned to an application.
Get-AzureADApplicationPolicy -Id <ObjectId of Application>
PARAMETERS
Id
DESCRIPTION
ObjectId (Id) of the application.
EXAMPLE
-Id <ObjectId of Application>
Remove-AzureADApplicationPolicy
Removes a policy from an application.
Remove-AzureADApplicationPolicy -Id <ObjectId of Application> -PolicyId <ObjectId of Policy>
PARAMETERS
DESCRIPTION
EXAMPLE
Id
ObjectId (Id) of the application.
-Id <ObjectId of Application>
PolicyId
ObjectId of the policy.
-PolicyId <ObjectId of Policy>
Service principal policies
You can use the following cmdlets for service principal policies.
Add-AzureADServicePrincipalPolicy
Links the specified policy to a service principal.
Add-AzureADServicePrincipalPolicy -Id <ObjectId of ServicePrincipal> -RefObjectId <ObjectId of Policy>
PARAMETERS
DESCRIPTION
EXAMPLE
Id
ObjectId (Id) of the application.
-Id <ObjectId of Application>
RefObjectId
ObjectId of the policy.
-RefObjectId <ObjectId of Policy>
Get-AzureADServicePrincipalPolicy
Gets any policy linked to the specified service principal.
Get-AzureADServicePrincipalPolicy -Id <ObjectId of ServicePrincipal>
PARAMETERS
Id
DESCRIPTION
ObjectId (Id) of the application.
EXAMPLE
-Id <ObjectId of Application>
Remove-AzureADServicePrincipalPolicy
Removes the policy from the specified service principal.
Remove-AzureADServicePrincipalPolicy -Id <ObjectId of ServicePrincipal> -PolicyId <ObjectId of Policy>
PARAMETERS
DESCRIPTION
EXAMPLE
Id
ObjectId (Id) of the application.
-Id <ObjectId of Application>
PolicyId
ObjectId of the policy.
-PolicyId <ObjectId of Policy>
Azure AD service limits and restrictions
2/9/2017 • 2 min to read • Edit Online
This article contains the usage constraints and other service limits for the Azure Active Directory (Azure AD) service.
If you’re looking for the full set of Microsoft Azure service limits, see Azure Subscription and Service Limits, Quotas,
and Constraints.
Here are the usage constraints and other service limits for the Azure Active Directory service.
CATEGORY
LIMITS
Directories
A single user can only be associated with a maximum of 20
Azure Active Directory directories.
Examples of possible combinations:
A single user creates 20 directories.
A single user is added to 20 directories as a member.
A single user creates 10 directories and later is added
by others to 10 different directories.
Objects
A maximum of 500,000 objects can be used in a single
directory by users of the Free edition of Azure Active
Directory.
A non-admin user can create no more than 250
objects.
Schema extensions
String type extensions can have maximum of 256
characters.
Binary type extensions are limited to 256 bytes.
100 extension values (across ALL types and ALL
applications) can be written to any single object.
Only “User”, “Group”, “TenantDetail”, “Device”,
“Application” and “ServicePrincipal” entities can be
extended with “String” type or “Binary” type singlevalued attributes.
Schema extensions are available only in Graph APIversion 1.21-preview. The application must be granted
write access to register an extension.
Applications
A maximum of 100 users can be owners of a single
application.
CATEGORY
LIMITS
Groups
A maximum of 100 users can be owners of a single
group.
Any number of objects can be members of a single
group in Azure Active Directory.
The number of members in a group you can
synchronize from your on-premises Active Directory to
Azure Active Directory is limited to 15K members,
using Azure Active Directory Directory Synchronization
(DirSync).
The number of members in a group you can
synchronize from your on-premises Active Directory to
Azure Active Directory using Azure AD Connect is
limited to 50K members.
Access Panel
There is no limit to the number of applications that can
be seen in the Access Panel per end user, for users
assigned licenses for Azure AD Premium or the
Enterprise Mobility Suite.
A maximum of 10 app tiles (examples: Box, Salesforce,
or Dropbox) can be seen in the Access Panel for each
end user for users assigned licenses for Free or Azure
AD Basic editions of Azure Active Directory. This limit
does not apply to Administrator accounts.
Reports
A maximum of 1,000 rows can be viewed or downloaded in
any report. Any additional data is truncated.
Administrative units
An object can be a member of no more than 30 administrative
units.
What's next
Sign up for Azure as an organization
How Azure subscriptions are associated with Azure AD
Sign-in Microsoft Account & Azure AD users in a
single app
1/23/2017 • 2 min to read • Edit Online
In the past, an app developer who wanted to support both Microsoft accounts and Azure Active Directory was
required to integrate with two separate systems. We've now introduced a new authentication API version that
enables you to sign in users in with both types of accounts using the Azure AD system. This converged
authentication system is known as the v2.0 endpoint. With the v2.0 endpoint, one simple integration allows you
to reach an audience that spans millions of users with both personal and work/school accounts.
Apps that use the v2.0 endpoint can also consume REST APIs from the Microsoft Graph and Office 365 using
either type of account.
Getting Started
Choose your favorite platform from the following list to build an app using our open source libraries &
frameworks. Alternatively, you can use our OAuth 2.0 & OpenID Connect protocol documentation to send &
receive protocol messages directly without using an auth library.
MOBILE & NATIVE APPS
WEB APPS & WEB APIS
INTEGRATE DIRECTLY WITH PROTOCOLS
Add Sign-In to an iOS App
Add Sign-In to an JS SPA
Register an Application
Add Sign-In to an Android App
Add Sign-In to a .NET MVC App
Mobile Apps with OAuth 2.0
Add Sign-In to a Windows Desktop
App
Add Sign-In to a Node JS Web App
Web Apps with OpenID Connect
Call Office 365 Rest APIs from an app
Daemon apps with the Client
Credentials Flow
Single Page Apps with OpenID Connect
Secure a .NET Web API
Secure a NodeJS Web API
Call Office 365 REST APIs from the web
What's New
The conceptual information here will be useful in understanding what is & what isn't possible with the v2.0
endpoint.
Learn about the types of apps you can build with the v2.0 endpoint.
Understand the limitations, restrictions, and constraints with the v2.0 endpoint.
We've recently added support for admin restricted scopes and the OAuth2 client credentials grant. Try them
out!
Reference
These links will be useful for exploring the platform in depth:
Build 2016: Getting Started with Microsoft Identities: Enterprise Grade Sign In For Your Apps
Get help on Stack Overflow using the azure-active-directory or adal tags.
v2.0 Protocol Reference
v2.0 Token Reference
v2.0 Library Reference
Scopes and Consent in the v2.0 endpoint
The Microsoft App Registration Portal
Office 365 REST API Reference
The Microsoft Graph
What's different about the v2.0 endpoint?
1/23/2017 • 9 min to read • Edit Online
If you're familiar with Azure Active Directory or have integrated apps with Azure AD in the past, there may be some
differences in the v2.0 endpoint that you would not expect. This document calls out those differences for your
understanding.
NOTE
Not all Azure Active Directory scenarios & features are supported by the v2.0 endpoint. To determine if you should use the
v2.0 endpoint, read about v2.0 limitations.
Microsoft accounts and Azure AD accounts
The v2.0 endpoint allow developers to write apps that accept sign-in from both Microsoft Accounts and Azure AD
accounts, using a single auth endpoint. This gives you the ability to write your app completely account-agnostic; it
can be ignorant of the type of account that the user signs in with. Of course, you can make your app aware of the
type of account being used in a particular session, but you don't have to.
For instance, if your app calls the Microsoft Graph, some additional functionality and data will be available to
enterprise users, such as their SharePoint sites or Directory data. But for many actions, such as Reading a user's
mail, the code can be written exactly the same for both Microsoft Accounts and Azure AD accounts.
Integrating your app with Microsoft Accounts and Azure AD accounts is now one simple process. You can use a
single set of endpoints, a single library, and a single app registration to gain access to both the consumer and
enterprise worlds. To learn more about the v2.0 endpoint, check out the overview.
New app registration portal
the v2.0 endpoint can only be registered in a new location: apps.dev.microsoft.com. This is the portal where you can
obtain an Application Id, customize the appearance of your app's sign-in page, and more. All you need to access the
portal is a Microsoft powered account - either personal or work/school account.
We will continue to add more and more functionality to this App Registration Portal over time. The intent is that
this portal will be the new location where you can go to manage anything and everything having to do with your
Microsoft apps.
One app Id for all platforms
In the original Azure Active Directory service, you may have registered several different apps for a single project.
You were forced to use separate app registrations for your native clients and web apps:
For example, if you built both a website and an iOS app, you had to register them separately, using two different
Application Ids. If you had a website and a backend web api, you might have registered each as a separate app in
Azure AD. If you had an iOS app and an Android app, you also might have registered two different apps.
Now, all you need is a single app registration and a single Application Id for each of your projects. You can add
several "platforms" to a each project, and provide the appropriate data for each platform you add. Of course, you
can create as many apps as you like depending on your requirements, but for the majority of cases only one
Application Id should be necessary.
Our aim is that this will lead to a more simplified app management and development experience, and create a
more consolidated view of a single project that you might be working on.
Scopes, not resources
In the original Azure AD service, an app can behave as a resource, or a recipient of tokens. A resource can define a
number of scopes or oAuth2Permissions that it understands, allowing client apps to request tokens to that
resource for a certain set of scopes. Consider the Azure AD Graph API as an example of a resource:
Resource Identifier, or AppID URI : https://graph.windows.net/
Scopes, or OAuth2Permissions : Directory.Read , Directory.Write , etc.
All of this holds true for the the v2.0 endpoint. An app can still behave as resource, define scopes, and be identified
by a URI. Client apps can still request access to those scopes. However, the way in which a client requests those
permissions has changed. In the past, an OAuth 2.0 authorize request to Azure AD might have looked like:
GET https://login.microsoftonline.com/common/oauth2/authorize?
client_id=2d4d11a2-f814-46a7-890a-274a72a7309e
&resource=https%3A%2F%2Fgraph.windows.net%2F
...
where the resource parameter indicated which resource the client app is requesting authorization for. Azure AD
computed the permissions required by the app based on static configuration in the Azure Portal, and issued tokens
accordingly. Now, the same OAuth 2.0 authorize request looks like:
GET https://login.microsoftonline.com/common/oauth2/v2.0/authorize?
client_id=2d4d11a2-f814-46a7-890a-274a72a7309e
&scope=https%3A%2F%2Fgraph.windows.net%2Fdirectory.read%20https%3A%2F%2Fgraph.windows.net%2Fdirectory.write
...
where the scope parameter indicates which resource and permissions the app is requesting authorization for. The
desired resource is still very present in the request - it is simply encompassed in each of the values of the scope
parameter. Using the scope parameter in this manner allows the v2.0 endpoint to be more compliant with the
OAuth 2.0 specification, and aligns more closely with common industry practices. It also enables apps to perform
incremental consent, which is described in the next section.
Incremental and dynamic consent
Apps registered in the generally available Azure AD service needed to specify their required OAuth 2.0 permissions
in the Azure Portal, at app creation time:
The permissions an app required were configured statically. While this allowed configuration of the app to exist in
the Azure Portal and kept the code nice and simple, it presents a few issues for developers:
An app had to know all of the permissions it would ever need at app creation time. Adding permissions over
time was a difficult process.
An app had to know all of the resources it would ever access ahead of time. It was difficult to create apps that
could access an arbitrary number of resources.
An app had to request all the permissions it would ever need upon the user's first sign-in. In some cases this led
to a very long list of permissions, which discouraged end-users from approving the app's access on initial signin.
With the v2.0 endpoint, you can specify the permissions your app needs dynamically, at runtime, during regular
usage of your app. To do so, you can specify the scopes your app needs at any given point in time by including
them in the scope parameter of an authorization request:
GET https://login.microsoftonline.com/common/oauth2/v2.0/authorize?
client_id=2d4d11a2-f814-46a7-890a-274a72a7309e
&scope=https%3A%2F%2Fgraph.windows.net%2Fdirectory.read%20https%3A%2F%2Fgraph.windows.net%2Fdirectory.write
...
The above requests permission for the app to read an Azure AD user's directory data, as well as write data to their
directory. If the user has consented to those permissions in the past for this particular app, they will simply enter
their credentials and be signed into the app. If the user has not consented to any of these permissions, the v2.0
endpoint will ask the user for consent to those permissions. To learn more, you can read up on permissions,
consent, and scopes.
Allowing an app to request permissions dynamically via the scope parameter gives you full control over your
user's experience. If you wish, you can choose to frontload your consent experience and ask for all permissions in
one initial authorization request. Or if your app requires a large number of permissions, you can choose to gather
those permissions from the user incrementally, as they attempt to use certain features of your app over time.
Well-known scopes
Offline access
the v2.0 endpoint may require the use of a new well-known permission for apps - the offline_access scope. All
apps will need to request this permission if they need to access resources on the behalf of a user for a prolonged
period of time, even when the user may not be actively using the app. The offline_access scope will appear to the
user in consent dialogs as "Access your data offline", which the user must agree to. Requesting the offline_access
permission will enable your web app to receive OAuth 2.0 refresh_tokens from the v2.0 endpoint. Refresh_tokens
are long-lived, and can be exchanged for new OAuth 2.0 access_tokens for extended periods of access.
If your app does not request the offline_access scope, it will not receive refresh_tokens. This means that when
you redeem an authorization_code in the OAuth 2.0 authorization code flow, you will only receive back an
access_token from the /token endpoint. That access_token will remain valid for a short period of time (typically
one hour), but will eventually expire. At that point in time, your app will need to redirect the user back to the
/authorize endpoint to retrieve a new authorization_code. During this redirect, the user may or may not need to
enter their credentials again or re-consent to permissions, depending on the the type of app.
To learn more about OAuth 2.0, refresh_tokens, and access_tokens, check out the v2.0 protocol reference.
OpenID, profile and email
In the original Azure Active Directory service, the most basic OpenID Connect sign-in flow would provide a wealth
of information about the user in the resulting id_token. The claims in an id_token can include the user's name,
preferred username, email address, object ID, and more.
We are now restricting the information that the openid scope affords your app access to. The ‘openid’ scope will
only allow your app to sign the user in, and receive an app-specific identifier for the user. If you want to obtain
personally identifiable information (PII) about the user in your app, your app will need to request additional
permissions from the user. We are introducing two new scopes – the email and profile scopes – which allow
you to do so.
The
scope is very straightforward – it allows your app access to the user’s primary email address via the
claim in the id_token. The profile scope affords your app access to all other basic information about the
user – their name, preferred username, object ID, and so on.
email
email
This allows you to code your app in a minimal-disclosure fashion – you can only ask the user for the set of
information that your app requires to do its job. For more information on these scopes, refer to the v2.0 scope
reference.
Token Claims
The claims in tokens issued by the v2.0 endpoint will not be identical to tokens issued by the generally available
Azure AD endpoints - apps migrating to the new service should not assume a particular claim will exist in id_tokens
or access_tokens. Tokens issued by the v2.0 endpoint are compliant with the OAuth 2.0 and OpenID Connect
specifications, but may follow different semantics than the generally available Azure AD service.
To learn about the specific claims emitted in v2.0 tokens, see the v2.0 token reference.
Limitations
There are a few restrictions to be aware of when using the v2.0 point. Please refer to the v2.0 limitations doc to see
if any of these restrictions apply to your particular scenario.
App types for the Azure Active Directory v2.0
endpoint
1/17/2017 • 6 min to read • Edit Online
The Azure Active Directory (Azure AD) v2.0 endpoint supports authentication for a variety of modern app
architectures, all of them based on industry-standard protocols OAuth 2.0 or OpenID Connect. This article
describes the types of apps that you can build by using Azure AD v2.0, regardless of your preferred language or
platform. The information in this article is designed to help you understand high-level scenarios before you start
working with the code.
NOTE
The v2.0 endpoint doesn't support all Azure Active Directory scenarios and features. To determine whether you should use
the v2.0 endpoint, read about v2.0 limitations.
The basics
You must register each app that uses the v2.0 endpoint in the Microsoft Application Registration Portal. The app
registration process collects and assigns these values for your app:
An Application ID that uniquely identifies your app
A redirect URI that you can use to direct responses back to your app
A few other scenario-specific values
For details, learn how to register an app.
After the app is registered, the app communicates with Azure AD by sending requests to the Azure AD v2.0
endpoint. We provide open-source frameworks and libraries that handle the details of these requests. You also
have the option to implement the authentication logic yourself by creating requests to these endpoints:
https://login.microsoftonline.com/common/oauth2/v2.0/authorize
https://login.microsoftonline.com/common/oauth2/v2.0/token
Web apps
For web apps (.NET, PHP, Java, Ruby, Python, Node) that the user accesses through a browser, you can use OpenID
Connect for user sign-in. In OpenID Connect, the web app receives an ID token. An ID token is a security token that
verifies the user's identity and provides information about the user in the form of claims:
// Partial raw ID token
eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6ImtyaU1QZG1Cd...
// Partial content of a decoded ID token
{
"name": "John Smith",
"email": "[email protected]",
"oid": "d9674823-dffc-4e3f-a6eb-62fe4bd48a58"
...
}
You can learn about all the types of tokens and claims that are available to an app in the v2.0 tokens reference.
In web server apps, the sign-in authentication flow takes these high-level steps:
You can ensure the user's identity by validating the ID token with a public signing key that is received from the
v2.0 endpoint. A session cookie is set, which can be used to identify the user on subsequent page requests.
To see this scenario in action, try one of the web app sign-in code samples in our v2.0 Getting Started section.
In addition to simple sign-in, a web server app might need to access another web service, such as a REST API. In
this case, the web server app engages in a combined OpenID Connect and OAuth 2.0 flow, by using the OAuth 2.0
authorization code flow. For more information about this scenario, read about getting started with web apps and
Web APIs.
Web APIs
You can use the v2.0 endpoint to secure web services, such as your app's RESTful Web API. Instead of ID tokens
and session cookies, a Web API uses an OAuth 2.0 access token to secure its data and to authenticate incoming
requests. The caller of a Web API appends an access token in the authorization header of an HTTP request, like this:
GET /api/items HTTP/1.1
Host: www.mywebapi.com
Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6...
Accept: application/json
...
The Web API uses the access token to verify the API caller's identity and to extract information about the caller
from claims that are encoded in the access token. To learn about all the types of tokens and claims that are
available to an app, see the v2.0 tokens reference.
A Web API can give users the power to opt in or opt out of specific functionality or data by exposing permissions,
also known as scopes. For a calling app to acquire permission to a scope, the user must consent to the scope
during a flow. The v2.0 endpoint asks the user for permission, and then records permissions in all access tokens
that the Web API receives. The Web API validates the access tokens it receives on each call and performs
authorization checks.
A Web API can receive access tokens from all types of apps, including web server apps, desktop and mobile apps,
single-page apps, server-side daemons, and even other Web APIs. The high-level flow for a Web API looks like this:
To learn more about authorization codes, refresh tokens, and the detailed steps of getting access tokens, read
about the OAuth 2.0 protocol.
To learn how to secure a Web API by using OAuth2 access tokens, check out the Web API code samples in our
Getting Started section.
Mobile and native apps
Device-installed apps, such as mobile and desktop apps, often need to access back-end services or Web APIs that
store data and perform functions on behalf of a user. These apps can add sign-in and authorization to back-end
services by using the OAuth 2.0 authorization code flow.
In this flow, the app receives an authorization code from the v2.0 endpoint when the user signs in. The
authorization code represents the app's permission to call back-end services on behalf of the user who is signed
in. The app can exchange the authorization code in the background for an OAuth 2.0 access token and a refresh
token. The app can use the access token to authenticate to Web APIs in HTTP requests, and use the refresh token to
get new access tokens when older access tokens expire.
Single-page apps (JavaScript)
Many modern apps have a single-page app front end that primarily is written in JavaScript. Often, it's written by
using a framework like AngularJS, Ember.js, or Durandal.js. The Azure AD v2.0 endpoint supports these apps by
using the OAuth 2.0 implicit flow.
In this flow, the app receives tokens directly from the v2.0 authorize endpoint, without any server-to-server
exchanges. All authentication logic and session handling takes place entirely in the JavaScript client, without extra
page redirects.
To see this scenario in action, try one of the single-page app code samples in our Getting Started section.
Daemons and server-side apps
Apps that have long-running processes or that operate without interaction with a user also need a way to access
secured resources, such as Web APIs. These apps can authenticate and get tokens by using the app's identity,
rather than a user's delegated identity, with the OAuth 2.0 client credentials flow.
In this flow, the app interacts directly with the
/token
endpoint to obtain endpoints:
To build a daemon app, see the client credentials documentation in our Getting Started section, or try a .NET
sample app.
Current limitations
Currently, the types of apps in this section are not supported by the v2.0 endpoint, but they are on the roadmap
for future development. For additional limitations and restrictions for the v2.0 endpoint, see Should I use the v2.0
endpoint?.
Chained Web APIs (on-behalf-of )
Many architectures include a Web API that needs to call another downstream Web API, both secured by the v2.0
endpoint. This scenario is common in native clients that have a Web API back end, which in turn calls an instance
of Microsoft Online Services like Office 365, or the Graph API.
This chained Web API scenario can be supported by using the OAuth 2.0 JSON Web Token (JWT) bearer
credentials grant, also known as the on-behalf-of flow. Currently, the on-behalf-of flow is not implemented in the
v2.0 endpoint. To see how this flow works in the generally available Azure AD service, check out the on-behalf-of
code sample on GitHub.
Should I use the v2.0 endpoint?
1/17/2017 • 9 min to read • Edit Online
When you build applications that integrate with Azure Active Directory (Azure AD), you need to decide whether
the v2.0 endpoint and authentication protocols meet your needs. The original Azure AD endpoint is still fully
supported and, in some respects, is more feature rich than v2.0. However, the v2.0 endpoint introduces
significant benefits for developers. The benefits of v2.0 might entice you to use the new programming model.
Here's our recommendation for using the v2.0 endpoint now:
If you want to support personal Microsoft accounts in your application, use the v2.0 endpoint. Before you do,
be sure that you understand the limitations that we discuss in this article, especially those that apply to work
and school accounts.
If your application needs to support only work and school accounts, use the original Azure AD endpoints.
Over time, the v2.0 endpoint will grow to eliminate the restrictions listed here, so that you will only ever need to
use the v2.0 endpoint. In the meantime, this article is intended to help you determine whether the v2.0 endpoint
is right for you. We will continue to update this article to reflect the current state of the v2.0 endpoint. Check
back to reevaluate your requirements against v2.0 capabilities.
If you have an existing Azure AD app that does not use the v2.0 endpoint, there's no need to start from scratch.
In the future, we will provide a way for you to use your existing Azure AD applications with the v2.0 endpoint.
Restrictions on app types
Currently, the following types of apps are not supported by the v2.0 endpoint. For a description of supported
app types, see App types for the Azure Active Directory v2.0 endpoint.
Standalone Web APIs
You can use the v2.0 endpoint to build a Web API that is secured with OAuth 2.0. However, that Web API can
receive tokens only from an application that has the same Application ID. You cannot access a Web API from a
client that has a different Application ID. The client won't be able to request or obtain permissions to your Web
API.
To see how to build a Web API that accepts tokens from a client that has the same Application ID, see the v2.0
endpoint Web API samples in our Getting Started section.
Web API on-behalf-of flow
Many architectures include a Web API that needs to call another downstream Web API, both secured by the v2.0
endpoint. This scenario is common in native clients that have a Web API back end, which in turn calls an
instance of Microsoft Online Services or another custom-built Web API that supports Azure AD.
You can create this scenario by using the OAuth 2.0 JSON Web Token (JWT) bearer credential grant, otherwise
known as the on-behalf-of flow. Currently, however, the on-behalf-of flow is not supported for the v2.0
endpoint. To see how this flow works in the generally available Azure AD service, check out the on-behalf-of
code sample on GitHub.
Restrictions on app registrations
Currently, for each app that you want to integrate with the v2.0 endpoint, you must create an app registration in
the new Microsoft Application Registration Portal. Existing Azure AD or Microsoft account apps are not
compatible with the v2.0 endpoint. Apps that are registered in any portal other than the Application
Registration Portal are not compatible with the v2.0 endpoint. In the future, we plan to provide a way to use an
existing application as a v2.0 app. Currently, though, there is no migration path for an existing app to work with
the v2.0 endpoint.
Apps that are registered in the Application Registration Portal will not work with the original Azure AD
authentication endpoint. However, you can use apps that you create in the Application Registration Portal to
integrate successfully with the Microsoft account authentication endpoint https://login.live.com .
In addition, app registrations that you create in the Application Registration Portal have the following caveats:
The homepage property, also known as the sign-on URL, is not supported. Without a homepage, these
applications will not appear in the Office MyApps panel.
Currently, only two app secrets are allowed per Application ID.
An app registration can be viewed and managed only by a single developer account. It cannot be shared
between multiple developers.
There are several restrictions on the format of the redirect URI that is allowed. For more information about
redirect URIs, see the next section.
Restrictions on redirect URIs
Currently, apps that are registered in the Application Registration Portal are restricted to a limited set of redirect
URI values. The redirect URI for web apps and services must begin with the scheme https , and all redirect URI
values must share a single DNS domain. For example, you cannot register a web app that has one of these
direct URIs:
https://login-east.contoso.com
https://login-west.contoso.com
The registration system compares the whole DNS name of the existing redirect URI to the DNS name of the
redirect URI that you are adding. The request to add the DNS name will fail if either of the following conditions
is true:
The whole DNS name of the new redirect URI does not match the DNS name of the existing redirect URI.
The whole DNS name of the new redirect URI is not a subdomain of the existing redirect URI.
For example, if the app has this redirect URI:
https://login.contoso.com
You can add to it, like this:
https://login.contoso.com/new
In this case, the DNS name matches exactly. Or, you can do this:
https://new.login.contoso.com
In this case, you're referring to a DNS subdomain of login.contoso.com. If you want to have an app that has
login-east.contoso.com and login-west.contoso.com as redirect URIs, you must add those redirect URIs in this
order:
https://contoso.com
https://login-east.contoso.com
https://login-west.contoso.com
You can add the latter two because they are subdomains of the first redirect URI, contoso.com. This limitation
will be removed in an upcoming release.
To learn how to register an app in the Application Registration Portal, see How to register an app with the v2.0
endpoint.
Restrictions on services and APIs
Currently, the v2.0 endpoint supports sign-in for any app that is registered in the Application Registration
Portal, and which falls in the list of supported authentication flows. However, these apps can acquire OAuth 2.0
access tokens for a very limited set of resources. The v2.0 endpoint issues access tokens only for:
The app that requested the token. An app can acquire an access token for itself, if the logical app is
composed of several different components or tiers. To see this scenario in action, check out our Getting
Started tutorials.
The Outlook Mail, Calendar, and Contacts REST APIs, all of which are located at https://outlook.office.com. To
learn how to write an app that accesses these APIs, see the Office Getting Started tutorials.
Microsoft Graph APIs. You can learn more about Microsoft Graph and the data that is available to you.
No other services are supported at this time. More Microsoft Online Services will be added in the future, in
addition to support for your own custom-built Web APIs and services.
Restrictions on libraries and SDKs
Currently, library support for the v2.0 endpoint is limited. If you want to use the v2.0 endpoint in a production
application, you have these options:
If you are building a web application, you can safely use Microsoft generally available server-side
middleware to perform sign-in and token validation. These include the OWIN Open ID Connect middleware
for ASP.NET and the Node.js Passport plug-in. For code samples that use Microsoft middleware, see our
Getting Started section.
For other platforms, and for native and mobile applications, you can integrate with the v2.0 endpoint by
directly sending and receiving protocol messages in your application code. The v2.0 OpenID Connect and
OAuth protocols are explicitly documented to help you perform such an integration.
Finally, you can use open-source Open ID Connect and OAuth libraries to integrate with the v2.0 endpoint.
The v2.0 protocol should be compatible with many open-source protocol libraries without major changes.
The availability of these kinds of libraries varies by language and platform. The Open ID Connect and OAuth
2.0 websites maintain a list of popular implementations. For more information, see Azure Active Directory
v2.0 and authentication libraries, and the list of open-source client libraries and samples that have been
tested with the v2.0 endpoint.
We have released an initial preview of the Microsoft Authentication Library (MSAL) only for .NET. You are
welcome to try out this library in .NET client and server applications, but as a preview library, it is not
accompanied by general availability (GA)-quality support.
Restrictions on protocols
The v2.0 endpoint supports only Open ID Connect and OAuth 2.0. However, not all features and capabilities of
each protocol have been incorporated into the v2.0 endpoint.
These typical protocol features and capabilities currently are not available in the v2.0 endpoint:
The OpenID Connect end_session_endpoint parameter, which allows an app to end the user's session, is not
available with the v2.0 endpoint.
ID tokens that are issued by the v2.0 endpoint have only a pairwise identifier for the user. This means that
two different applications receive different IDs for the same user. Note that by querying the Microsoft Graph
/me endpoint, you can get a correlatable ID for the user that you can use across applications.
ID tokens that are issued by the v2.0 endpoint do not contain an email claim for the user, even if you
acquire permission from the user to view their email.
The OpenID Connect UserInfo endpoint is not implemented on the v2.0 endpoint. However, all user profile
data that you potentially would receive at this endpoint is available from the Microsoft Graph /me endpoint.
The v2.0 endpoint does not support issuing role or group claims in ID tokens.
To better understand the scope of protocol functionality supported in the v2.0 endpoint, read through our
OpenID Connect and OAuth 2.0 protocol reference.
Restrictions for work and school accounts
A few features that are specific to Microsoft enterprise users are not yet supported by the v2.0 endpoint. For
more information, read the next sections.
Device -based conditional access, native and mobile apps, and Microsoft Graph
The v2.0 endpoint does not yet support device authentication for mobile and native applications, such as native
apps running on iOS or Android. For some organizations, this might block your native application from calling
Microsoft Graph. Device authentication is required when an administrator sets a device-based conditional
access policy on an application. For the v2.0 endpoint, the most likely scenario for device-based conditional
access is if an administrator were to set a policy on a resource in Microsoft Graph, such as the Outlook API. If an
administrator sets this policy and your native application requests a token to Microsoft Graph, the request
ultimately will fail because device authentication is not yet supported. Web applications that request tokens to
Microsoft Graph, however, are supported when device-based policies are configured. In the web app scenario,
device authentication is performed through the user’s web browser.
As a developer, you most likely have no control of when policies are set on Microsoft Graph resources. You
might not even be aware when it happens. If you are building an application for work and school users, you
should use the original Azure AD endpoint until the v2.0 endpoint supports device authentication. You can learn
more about device-based conditional access in Azure AD.
Windows integrated authentication for federated tenants
If you've used Active Directory Authentication Library (ADAL) (with the original Azure AD endpoint) in Windows
applications, you might have taken advantage of what is known as the Security Assertion Markup Language
(SAML) assertion grant. With this grant, users of federated Azure AD tenants can silently authenticate with their
on-premises Active Directory instance without entering credentials. Currently, the SAML assertion grant is not
supported on the v2.0 endpoint.
Add sign-in to an iOS app using a third-party library
with Graph API using the v2.0 endpoint
4/17/2017 • 14 min to read • Edit Online
The Microsoft identity platform uses open standards such as OAuth2 and OpenID Connect. Developers can use any
library they want to integrate with our services. To help developers use our platform with other libraries, we've
written a few walkthroughs like this one to demonstrate how to configure third-party libraries to connect to the
Microsoft identity platform. Most libraries that implement the RFC6749 OAuth2 spec can connect to the Microsoft
identity platform.
With the application that this walkthrough creates, users can sign in to their organization and then search for
others in their organization by using the Graph API.
If you're new to OAuth2 or OpenID Connect, much of this sample configuration may not make sense to you. We
recommend that you read v2.0 Protocols - OAuth 2.0 Authorization Code Flow for background.
NOTE
Some features of our platform that do have an expression in the OAuth2 or OpenID Connect standards, such as Conditional
Access and Intune policy management, require you to use our open source Microsoft Azure Identity Libraries.
The v2.0 endpoint does not support all Azure Active Directory scenarios and features.
NOTE
To determine if you should use the v2.0 endpoint, read about v2.0 limitations.
Download code from GitHub
The code for this tutorial is maintained on GitHub. To follow along, you can download the app's skeleton as a .zip or
clone the skeleton:
git clone --branch skeleton [email protected]:Azure-Samples/active-directory-ios-native-nxoauth2-v2.git
You can also just download the sample and get started right away:
git clone [email protected]:Azure-Samples/active-directory-ios-native-nxoauth2-v2.git
Register an app
Create a new app at the Application registration portal, or follow the detailed steps at How to register an app with
the v2.0 endpoint. Make sure to:
Copy the Application Id that's assigned to your app because you'll need it soon.
Add the Mobile platform for your app.
Copy the Redirect URI from the portal. You must use the default value of urn:ietf:wg:oauth:2.0:oob .
Download the third-party NXOAuth2 library and create a workspace
For this walkthrough, you will use the OAuth2Client from GitHub, which is an OAuth2 library for Mac OS X and iOS
(Cocoa and Cocoa touch). This library is based on draft 10 of the OAuth2 spec. It implements the native application
profile and supports the authorization endpoint of the user. These are all the things you'll need to integrate with
the Microsoft identity platform.
Add the library to your project by using CocoaPods
CocoaPods is a dependency manager for Xcode projects. It manages the previous installation steps automatically.
$ vi Podfile
1. Add the following to this podfile:
platform :ios, '8.0'
target 'QuickStart' do
pod 'NXOAuth2Client'
end
2. Load the podfile by using CocoaPods. This will create a new Xcode workspace that you will load.
$ pod install
...
$ open QuickStart.xcworkspace
Explore the structure of the project
The following structure is set up for our project in the skeleton:
A Master View with a UPN Search
A Detail View for the data about the selected user
A Login View where a user can sign in to the app to query the graph
We will move to various files in the skeleton to add authentication. Other parts of the code, such as the visual code,
do not pertain to identity but are provided for you.
Set up the settings.plst file in the library
In the QuickStart project, open the settings.plist file. Replace the values of the elements in the section to
reflect the values that you used in the Azure portal. Your code will reference these values whenever it uses the
Active Directory Authentication Library.
The clientId is the client ID of your application that you copied from the portal.
The redirectUri is the redirect URL that the portal provided.
Set up the NXOAuth2Client library in your LoginViewController
The NXOAuth2Client library requires some values to get set up. After you complete that task, you can use the
acquired token to call the Graph API. Because LoginView will be called any time we need to authenticate, it makes
sense to put configuration values in to that file.
Let's add some values to the
LoginViewController.m
file to set the context for authentication and
authorization. Details about the values follow the code.
NSString *scopes = @"openid offline_access User.Read";
NSString *authURL = @"https://login.microsoftonline.com/common/oauth2/v2.0/authorize";
NSString *loginURL = @"https://login.microsoftonline.com/common/login";
NSString *bhh = @"urn:ietf:wg:oauth:2.0:oob?code=";
NSString *tokenURL = @"https://login.microsoftonline.com/common/oauth2/v2.0/token";
NSString *keychain = @"com.microsoft.azureactivedirectory.samples.graph.QuickStart";
static NSString * const kIDMOAuth2SuccessPagePrefix = @"session_state=";
NSURL *myRequestedUrl;
NSURL *myLoadedUrl;
bool loginFlow = FALSE;
bool isRequestBusy;
NSURL *authcode;
Let's look at details about the code.
The first string is for
scopes
. The
User.Read
value allows you to read the basic profile of the signed in user.
You can learn more about all the available scopes at Microsoft Graph permission scopes.
For authURL , loginURL , bhh , and tokenURL , you should use the values provided previously. If you use the open
source Microsoft Azure Identity Libraries, we pull this data down for you by using our metadata endpoint. We've
done the hard work of extracting these values for you.
The keychain value is the container that the NXOAuth2Client library will use to create a keychain to store your
tokens. If you'd like to get single sign-on (SSO) across numerous apps, you can specify the same keychain in each
of your applications and request the use of that keychain in your Xcode entitlements. This is explained in the Apple
documentation.
The rest of these values are required to use the library and create places for you to carry values to the context.
Create a URL cache
Inside (void)viewDidLoad() , which is always called after the view is loaded, the following code primes a cache for
our use.
Add the following code:
- (void)viewDidLoad {
[super viewDidLoad];
self.loginView.delegate = self;
[self setupOAuth2AccountStore];
[self requestOAuth2Access];
NSURLCache *URLCache = [[NSURLCache alloc] initWithMemoryCapacity:4 * 1024 * 1024
diskCapacity:20 * 1024 * 1024
diskPath:nil];
[NSURLCache setSharedURLCache:URLCache];
}
Create a WebView for sign-in
A WebView can prompt the user for additional factors like SMS text message (if configured) or return error
messages to the user. Here you'll set up the WebView and then later write the code to handle the callbacks that will
happen in the WebView from the identity services.
-(void)requestOAuth2Access {
//to sign in to Microsoft APIs using OAuth2, we must show an embedded browser (UIWebView)
[[NXOAuth2AccountStore sharedStore] requestAccessToAccountWithType:@"myGraphService"
withPreparedAuthorizationURLHandler:^(NSURL *preparedURL) {
//navigate to the URL returned by NXOAuth2Client
NSURLRequest *r = [NSURLRequest requestWithURL:preparedURL];
[self.loginView loadRequest:r];
}];
}
Override the WebView methods to handle authentication
To tell the WebView what happens when a user needs to sign in as discussed previously, you can paste the
following code.
- (void)resolveUsingUIWebView:(NSURL *)URL {
// We get the auth token from a redirect so we need to handle that in the webview.
if (![NSThread isMainThread]) {
[self performSelectorOnMainThread:@selector(resolveUsingUIWebView:) withObject:URL waitUntilDone:YES];
return;
}
NSURLRequest *hostnameURLRequest = [NSURLRequest requestWithURL:URL
cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0f];
isRequestBusy = YES;
[self.loginView loadRequest:hostnameURLRequest];
NSLog(@"resolveUsingUIWebView ready (status: UNKNOWN, URL: %@)", self.loginView.request.URL);
}
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:
(UIWebViewNavigationType)navigationType {
NSLog(@"webView:shouldStartLoadWithRequest: %@ (%li)", request.URL, (long)navigationType);
// The webview is where all the communication happens. Slightly complicated.
myLoadedUrl = [webView.request mainDocumentURL];
NSLog(@"***Loaded url: %@", myLoadedUrl);
//if the UIWebView is showing our authorization URL or consent URL, show the UIWebView control
if ([request.URL.absoluteString rangeOfString:authURL options:NSCaseInsensitiveSearch].location !=
NSNotFound) {
self.loginView.hidden = NO;
} else if ([request.URL.absoluteString rangeOfString:loginURL options:NSCaseInsensitiveSearch].location !=
NSNotFound) {
//otherwise hide the UIWebView, we've left the authorization flow
self.loginView.hidden = NO;
} else if ([request.URL.absoluteString rangeOfString:bhh options:NSCaseInsensitiveSearch].location !=
NSNotFound) {
//otherwise hide the UIWebView, we've left the authorization flow
self.loginView.hidden = YES;
[[NXOAuth2AccountStore sharedStore] handleRedirectURL:request.URL];
}
else {
self.loginView.hidden = NO;
//read the Location from the UIWebView, this is how Microsoft APIs is returning the
//authentication code and relation information. This is controlled by the redirect URL we chose to use
from Microsoft APIs
//continue the OAuth2 flow
// [[NXOAuth2AccountStore sharedStore] handleRedirectURL:request.URL];
}
return YES;
}
Write code to handle the result of the OAuth2 request
The following code will handle the redirectURL that returns from the WebView. If authentication wasn't successful,
the code will try again. Meanwhile, the library will provide the error that you can see in the console or handle
asynchronously.
- (void)handleOAuth2AccessResult:(NSString *)accessResult {
AppData* data = [AppData getInstance];
//parse the response for success or failure
if (accessResult)
//if success, complete the OAuth2 flow by handling the redirect URL and obtaining a token
{
[[NXOAuth2AccountStore sharedStore] handleRedirectURL:accessResult];
} else {
//start over
[self requestOAuth2Access];
}
}
Set up the OAuth Context (called account store )
Here you can call
on the shared
account store for each service that you want the application to be able to access. The account type is a string that is
used as an identifier for a certain service. Because you are accessing the Graph API, the code refers to it as
"myGraphService" . You then set up an observer that will tell you when anything changes with the token. After you
get the token, you return the user back to the masterView .
-[NXOAuth2AccountStore setClientID:secret:authorizationURL:tokenURL:redirectURL:forAccountType:]
- (void)setupOAuth2AccountStore {
AppData* data = [AppData getInstance];
[[NXOAuth2AccountStore sharedStore] setClientID:data.clientId
secret:data.secret
scope:[NSSet setWithObject:scopes]
authorizationURL:[NSURL URLWithString:authURL]
tokenURL:[NSURL URLWithString:tokenURL]
redirectURL:[NSURL URLWithString:data.redirectUriString]
keyChainGroup: keychain
forAccountType:@"myGraphService"];
[[NSNotificationCenter defaultCenter] addObserverForName:NXOAuth2AccountStoreAccountsDidChangeNotification
object:[NXOAuth2AccountStore sharedStore]
queue:nil
usingBlock:^(NSNotification *aNotification) {
if (aNotification.userInfo) {
//account added, we have access
//we can now request protected data
NSLog(@"Success!! We have an access token.");
dispatch_async(dispatch_get_main_queue(),^ {
MasterViewController* masterViewController =
[self.storyboard instantiateViewControllerWithIdentifier:@"masterView"];
[self.navigationController
pushViewController:masterViewController animated:YES];
});
} else {
//account removed, we lost access
}
}];
[[NSNotificationCenter defaultCenter]
addObserverForName:NXOAuth2AccountStoreDidFailToRequestAccessNotification
object:[NXOAuth2AccountStore sharedStore]
queue:nil
usingBlock:^(NSNotification *aNotification) {
NSError *error = [aNotification.userInfo
objectForKey:NXOAuth2AccountStoreErrorKey];
NSLog(@"Error!! %@", error.localizedDescription);
}];
}
Set up the Master View to search and display the users from the Graph
API
A Master-View-Controller (MVC) app that displays the returned data in the grid is beyond the scope of this
walkthrough, and many online tutorials explain how to build one. All this code is in the skeleton file. However, you
do need to deal with a few things in this MVC application:
Intercept when a user types something in the search field
Provide an object of data back to the MasterView so it can display the results in the grid
We'll do those below.
Add a check to see if you're logged in
The application does little if the user is not signed in, so it's smart to check if there is already a token in the cache. If
not, you redirect to the LoginView for the user to sign in. If you recall, the best way to do actions when a view loads
is to use the viewDidLoad() method that Apple provides us.
- (void)viewDidLoad {
[super viewDidLoad];
NXOAuth2AccountStore *store = [NXOAuth2AccountStore sharedStore];
NSArray *accounts = [store accountsWithAccountType:@"myGraphService"];
if (accounts.count == 0) {
dispatch_async(dispatch_get_main_queue(),^ {
LoginViewController* userSelectController = [self.storyboard
instantiateViewControllerWithIdentifier:@"LoginUserView"];
[self.navigationController pushViewController:userSelectController animated:YES];
});
}
Update the Table View when data is received
When the Graph API returns data, you need to display the data. For simplicity, here is all the code to update the
table. You can just paste the right values in your MVC boilerplate code.
#pragma mark - Table View
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [upnArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TaskPrototypeCell"
forIndexPath:indexPath];
if ( cell == nil ) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:@"TaskPrototypeCell"];
}
User *user = nil;
user = [upnArray objectAtIndex:indexPath.row];
// Configure the cell
cell.textLabel.text = user.name;
[cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
return cell;
}
Provide a way to call the Graph API when someone types in the search field
When a user types a search in the box, you need to shove that over to the Graph API. The GraphAPICaller class,
which you will build in the following code, separates the lookup functionality from the presentation. For now, let's
write the code that feeds any search characters to the Graph API. We do this by providing a method called
lookupInGraph , which takes the string that we want to search for.
-(void)lookupInGraph:(NSString *)searchText {
if (searchText.length > 0) {
};
[GraphAPICaller searchUserList:searchText completionBlock:^(NSMutableArray* returnedUpns, NSError*
error) {
if (returnedUpns) {
upnArray = returnedUpns;
}
else
{
UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:nil message:[[NSString
alloc]initWithFormat:@"Error : %@", error.localizedDescription] delegate:nil cancelButtonTitle:@"Retry"
otherButtonTitles:@"Cancel", nil];
[alertView setDelegate:self];
dispatch_async(dispatch_get_main_queue(),^ {
[alertView show];
});
}
}];
}
Write a Helper class to access the Graph API
This is the core of our application. Whereas the rest was inserting code in the default MVC pattern from Apple, here
you write code to query the graph as the user types and then return that data. Here's the code, and a detailed
explanation follows it.
Create a new Objective C header file
Name the file GraphAPICaller.h , and add the following code.
@interface GraphAPICaller : NSObject<NSURLConnectionDataDelegate>
+(void) searchUserList:(NSString*)searchString
completionBlock:(void (^) (NSMutableArray*, NSError* error))completionBlock;
@end
Here you see that a specified method takes a string and returns a completionBlock. This completionBlock, as you
may have guessed,