Azure Ad b2c
Azure Ad b2c
Azure Active Directory B2C provides business-to-customer identity as a service. Your customers use their
preferred social, enterprise, or local account identities to get single sign-on access to your applications and APIs.
Azure Active Directory B2C (Azure AD B2C ) is a customer identity access management (CIAM ) solution capable of
supporting millions of users and billions of authentications per day. It takes care of the scaling and safety of the
authentication platform, monitoring and automatically handling threats like denial-of-service, password spray, or
brute force attacks.
By serving as the central authentication authority for your web applications, mobile apps, and APIs, Azure AD B2C
enables you to build a single sign-on (SSO ) solution for them all. Centralize the collection of user profile and
preference information, and capture detailed analytics about sign-in behavior and sign-up conversion.
Azure AD B2C can facilitate collecting the information from the user during registration or profile editing, then
hand that data off to the external system. Then, during future authentications, Azure AD B2C can retrieve the data
from the external system and, if needed, include it as a part of the authentication token response it sends to your
application.
Progressive profiling
Another user journey option includes progressive profiling. Progressive profiling allows your customers to quickly
complete their first transaction by collecting a minimal amount of information. Then, gradually collect more profile
data from the customer on future sign-ins.
WoodGrove allows their customers to sign up and sign in by using their Google, Facebook, or Microsoft accounts
as their identity provider. Or, they can sign up by using their email address and a password to create what's called a
local account.
When a customer selects Sign up with your personal account and then Sign up now, they're presented with a
custom sign-up page.
After entering an email address and selecting Send verification code, Azure AD B2C sends them the code. Once
they enter their code, select Verify code, and then enter the other information on the form, they must also agree
to the terms of service.
Clicking the Create button causes Azure AD B2C to redirect the user back to the WoodGrove Groceries website.
When it redirects, Azure AD B2C passes an OpenID Connect authentication token to the WoodGrove web
application. The user is now signed-in and ready to go, their display name shown in the top-right corner to indicate
they're signed in.
Next steps
Now that you have an idea of what Azure AD B2C is and some of the scenarios it can help with, dig a little deeper
into its features and technical aspects.
Azure AD B2C technical overview >
Technical and feature overview of Azure Active
Directory B2C
9/19/2019 • 14 minutes to read • Edit Online
A companion to About Azure Active Directory B2C, this article provides a more in-depth introduction to the
service. Discussed here are the primary resources you work with in the service, its features, and how these enable
you to provide a fully custom identity experience for your customers in your applications.
Figure: User directory within an Azure AD B2C tenant in the Azure portal
Consumer accounts
With a consumer account, users can sign in to the applications that you've secured with Azure AD B2C. Users with
consumer accounts can't, however, access Azure resources, for example the Azure portal.
A consumer account can be associated with these identity types:
Local identity, with the username and password stored locally in the Azure AD B2C directory. We often refer to
these identities as as "local accounts."
Social or enterprise identities, where the identity of the user is managed by a federated identity provider like
Facebook, Microsoft, ADFS, or Salesforce.
A user with a consumer account can sign in with multiple identities, for example username, email, employee ID,
government ID, and others. A single account can have multiple identities, both local and social.
With external identity provider federation, you can offer your consumers the ability to sign in with their existing
social or enterprise accounts, without having to create a new account just for your application.
On the sign-up or sign-in page, Azure AD B2C presents a list of external identity providers the user can choose for
sign-in. Once they select one of the external identity providers, they're taken (redirected) to the selected provider's
website to complete the sign in process. After the user successfully signs in, they're returned back to Azure AD
B2C for authentication of the account in your application.
To see how to add identity providers in Azure AD B2C, see Tutorial: Add identity providers to your applications in
Azure Active Directory B2C.
Identity experiences: user flows or custom policies
The extensible policy framework of Azure AD B2C is its core strength. Policies describe your users' identity
experiences such as sign up, sign in, and profile editing.
In Azure AD B2C, there are two primary paths you can take to provide these identity experiences: user flows and
custom policies.
User flows are predefined, built-in, configurable policies that we provide so you can create sign-up, sign-in,
and policy editing experiences in minutes.
Custom policies enable you to create your own user journeys for complex identity experience scenarios.
Both user flows and custom policies are powered by the Identity Experience Framework, Azure AD B2C's policy
orchestration engine.
User flow
To help you quickly set up the most common identity tasks, the Azure portal includes several predefined and
configurable policies called user flows.
You can configure user flow settings like these to control identity experience behaviors in your applications:
Account types used for sign-in, such as social accounts like a Facebook, or local accounts that use an email
address and password for sign-in
Attributes to be collected from the consumer, such as first name, postal code, or country of residency
Azure Multi-Factor Authentication (MFA)
Customization of the user interface
Set of claims in a token that your application receives after the user completes the user flow
Session management
...and more.
Most common identity scenarios for the majority of mobile, web, and single-page applications can be defined and
implemented effectively with user flows. We recommend that you use the built-in user flows unless you have
complex user journey scenarios that require the full flexibility of custom policies.
Learn more about user flows in User flows in Azure Active Directory B2C.
Custom policy
Custom policies unlock access to the full power of the Identity Experience Framework (IEF ) orchestration engine.
With custom policies, you can leverage IEF to build almost any authentication, user registration, or profile editing
experience that you can imagine.
The Identity Experience Framework gives you the ability to construct user journeys with any combination of steps.
For example:
Federate with other identity providers
First- and third-party multi-factor authentication (MFA) challenges
Collect any user input
Integrate with external systems using REST API communication
Each such user journey is defined by a policy, and you can build as many or as few policies as you need to enable
the best user experience for your organization.
A custom policy is defined by several XML files that refer to each other in a hierarchical chain. The XML elements
define the claims schema, claims transformations, content definitions, claims providers, technical profiles, user
journey orchestration steps, and other aspects of the identity experience.
The powerful flexibility of custom policies is most appropriate for when you need to build complex identity
scenarios. Developers configuring custom policies must define the trusted relationships in careful detail to include
metadata endpoints, exact claims exchange definitions, and configure secrets, keys, and certificates as needed by
each identity provider.
Learn more about custom policies in Custom policies in Azure Active Directory B2C.
Application integration
When a user wants to sign in to your application, whether it's a web, mobile, desktop, or single-page application
(SPA), the application initiates an authorization request to a user flow - or custom policy-provided endpoint. The
user flow or custom policy defines and controls the user's experience. When they complete a user flow, for
example the sign-up or sign-in flow, Azure AD B2C generates a token, then redirects the user back to your
application.
Multiple applications can use the same user flow or custom policy. A single application can use multiple user flows
or custom policies.
For example, to sign in to an application, the application uses the sign up or sign in user flow. After the user has
signed in, they may want to edit their profile, so the application initiates another authorization request, this time
using the profile edit user flow.
Localization
Language customization in Azure AD B2C allows you to accommodate different languages to suit your customer
needs. Microsoft provides the translations for 36 languages, but you can also provide your own translations for
any language. Even if your experience is provided for only a single language, you can customize any text on the
pages.
See how localization works in Language customization in Azure Active Directory B2C.
You can add a REST API call at any step in the user journey defined by a custom policy. For example, you can call a
REST API:
During sign-in, just before Azure AD B2C validates the credentials
Immediately after sign-in
Before Azure AD B2C creates a new account in the directory
After Azure AD B2C creates a new account in the directory
Before Azure AD B2C issues an access token
To see how to use custom policies for RESTful API integration in Azure AD B2C, see Integrate REST API claims
exchanges in your Azure AD B2C user journey.
Next steps
Now that you have deeper view into the features and technical aspects of Azure Active Directory B2C, get started
with the service by creating a B2C tenant:
Tutorial: Create an Azure Active Directory B2C tenant >
Quickstart: Set up sign in for an ASP.NET application
using Azure Active Directory B2C
12/9/2019 • 3 minutes to read • Edit Online
Azure Active Directory B2C (Azure AD B2C ) provides cloud identity management to keep your application,
business, and customers protected. Azure AD B2C enables your applications to authenticate to social accounts and
enterprise accounts using open standard protocols. In this quickstart, you use an ASP.NET application to sign in
using a social identity provider and call an Azure AD B2C protected web API.
If you don't have an Azure subscription, create a free account before you begin.
Prerequisites
Visual Studio 2019 with the ASP.NET and web development workload.
A social account from Facebook, Google, or Microsoft.
Download a zip file or clone the sample web application from GitHub.
You authenticate (sign in) using your social account credentials and authorize the application to read
information from your social account. By granting access, the application can retrieve profile information
from the social account such as your name and city.
3. Finish the sign-in process for the identity provider.
2. Change your Display name or City, and then click Continue to update your profile.
The changed is displayed in the upper right portion of the web application's home page.
The ASP.NET web application includes an Azure AD access token in the request to the protected web API
resource to perform operations on the user's to-do list items.
You've successfully used your Azure AD B2C user account to make an authorized call an Azure AD B2C protected
web API.
Clean up resources
You can use your Azure AD B2C tenant if you plan to try other Azure AD B2C quickstarts or tutorials. When no
longer needed, you can delete your Azure AD B2C tenant.
Next steps
In this quickstart, you used a sample ASP.NET application to:
Sign in with a custom login page
Sign in with a social identity provider
Create an Azure AD B2C account
Call a web API protected by Azure AD B2C
Get started creating your own Azure AD B2C tenant.
Create an Azure Active Directory B2C tenant in the Azure portal
Quickstart: Set up sign-in for a desktop app using
Azure Active Directory B2C
12/9/2019 • 2 minutes to read • Edit Online
Azure Active Directory B2C (Azure AD B2C ) provides cloud identity management to keep your application,
business, and customers protected. Azure AD B2C enables your applications to authenticate to social accounts and
enterprise accounts using open standard protocols. In this quickstart, you use a Windows Presentation Foundation
(WPF ) desktop application to sign in using a social identity provider and call an Azure AD B2C protected web API.
If you don't have an Azure subscription, create a free account before you begin.
Prerequisites
Visual Studio 2019 with the ASP.NET and web development workload.
A social account from either Facebook, Google, or Microsoft.
Download a zip file or clone the sample web app from GitHub.
The sample supports several sign-up options. These options include using a social identity provider or
creating a local account using an email address. For this quickstart, use a social identity provider account
from either Facebook, Google, or Microsoft.
2. Azure AD B2C presents a sign-in page for a fictitious company called Fabrikam for the sample web
application. To sign up using a social identity provider, click the button of the identity provider you want to
use.
You authenticate (sign in) using your social account credentials and authorize the application to read
information from your social account. By granting access, the application can retrieve profile information
from the social account such as your name and city.
3. Finish the sign-in process for the identity provider.
Your new account profile details are pre-populated with information from your social account.
2. Choose the identity provider associated with the account you created. For example, if you used Facebook as
the identity provider when you created your account, choose Facebook to modify the associated profile
details.
3. Change your Display name or City, and then click Continue.
A new access token is displayed in the Token info text box. If you want to verify the changes to your profile,
copy and paste the access token into the token decoder https://jwt.ms.

The application includes the Azure AD access token in the request to the protected web API resource. The web
API sends back the display name contained in the access token.
You've successfully used your Azure AD B2C user account to make an authorized call an Azure AD B2C protected
web API.
Clean up resources
You can use your Azure AD B2C tenant if you plan to try other Azure AD B2C quickstarts or tutorials. When no
longer needed, you can delete your Azure AD B2C tenant.
Next steps
In this quickstart, you used a sample desktop application to:
Sign in with a custom login page
Sign in with a social identity provider
Create an Azure AD B2C account
Call a web API protected by Azure AD B2C
Get started creating your own Azure AD B2C tenant.
Create an Azure Active Directory B2C tenant in the Azure portal
Quickstart: Set up sign-in for a single-page app using
Azure Active Directory B2C
12/9/2019 • 2 minutes to read • Edit Online
Azure Active Directory B2C (Azure AD B2C ) provides cloud identity management to keep your application,
business, and customers protected. Azure AD B2C enables your applications to authenticate to social accounts, and
enterprise accounts using open standard protocols. In this quickstart, you use a single-page application to sign in
using a social identity provider and call an Azure AD B2C protected web API.
If you don't have an Azure subscription, create a free account before you begin.
Prerequisites
Visual Studio 2019 with the ASP.NET and web development workload
Node.js
Social account from Facebook, Google, or Microsoft
Code sample from GitHub: active-directory-b2c-javascript-msal-singlepageapp
You can download the zip archive or clone the repository:
cd active-directory-b2c-javascript-msal-singlepageapp
npm install && npm update
node server.js
You authenticate (sign in) using your social account credentials and authorize the application to read
information from your social account. By granting access, the application can retrieve profile information
from the social account such as your name and city.
3. Finish the sign-in process for the identity provider.
Clean up resources
You can use your Azure AD B2C tenant if you plan to try other Azure AD B2C quickstarts or tutorials. When no
longer needed, you can delete your Azure AD B2C tenant.
Next steps
In this quickstart, you used a sample single-page application to:
Sign in with a custom login page
Sign in with a social identity provider
Create an Azure AD B2C account
Call a web API protected by Azure AD B2C
Get started creating your own Azure AD B2C tenant.
Create an Azure Active Directory B2C tenant in the Azure portal
Tutorial: Create an Azure Active Directory B2C
tenant
9/27/2019 • 3 minutes to read • Edit Online
Before your applications can interact with Azure Active Directory B2C (Azure AD B2C ), they must be registered
in a tenant that you manage.
In this article, you learn how to:
Create an Azure AD B2C tenant
Link your tenant to your subscription
Switch to the directory containing your Azure AD B2C tenant
Add the Azure AD B2C resource as a Favorite in the Azure portal
You learn how to register an application in the next tutorial.
If you don't have an Azure subscription, create a free account before you begin.
7. Once the tenant creation is complete, select the Create new B2C Tenant or Link to existing Tenant
link at the top of the tenant creation page.
Before your applications can interact with Azure Active Directory B2C (Azure AD B2C ), they must be registered in a
tenant that you manage. This tutorial shows you how to register a web application using the Azure portal.
In this article, you learn how to:
Register a web application
Create a client secret
If you don't have an Azure subscription, create a free account before you begin.
Prerequisites
If you haven't already created your own Azure AD B2C Tenant, create one now. You can use an existing Azure AD
B2C tenant.
Next steps
In this article, you learned how to:
Register a web application
Create a client secret
Next, learn how to create user flows to enable your users to sign up, sign in, and manage their profiles.
Create user flows in Azure Active Directory B2C >
Tutorial: Create user flows in Azure Active Directory
B2C
9/17/2019 • 4 minutes to read • Edit Online
In your applications you may have user flows that enable users to sign up, sign in, or manage their profile. You can
create multiple user flows of different types in your Azure Active Directory B2C (Azure AD B2C ) tenant and use
them in your applications as needed. User flows can be reused across applications.
In this article, you learn how to:
Create a sign-up and sign-in user flow
Create a profile editing user flow
Create a password reset user flow
This tutorial shows you how to create some recommended user flows by using the Azure portal. If you're looking
for information about how to set up a resource owner password credentials (ROPC ) flow in your application, see
Configure the resource owner password credentials flow in Azure AD B2C.
If you don't have an Azure subscription, create a free account before you begin.
Prerequisites
Register your applications that are part of the user flows you want to create.
5. On the Recommended tab, select the Sign up and sign in user flow.
6. Enter a Name for the user flow. For example, signupsignin1.
7. For Identity providers, select Email signup.
8. For User attributes and claims, choose the claims and attributes that you want to collect and send from
the user during sign-up. For example, select Show more, and then choose attributes and claims for
Country/Region, Display Name, and Postal Code. Click OK.
9. Click Create to add the user flow. A prefix of B2C_1 is automatically appended to the name.
Test the user flow
1. Select the user flow you created to open its overview page, then select Run user flow.
2. For Application, select the web application named webapp1 that you previously registered. The Reply URL
should show https://jwt.ms .
3. Click Run user flow, and then select Sign up now.
4. Enter a valid email address, click Send verification code, enter the verification code that you receive, then
select Verify code.
5. Enter a new password and confirm the password.
6. Select your country and region, enter the name that you want displayed, enter a postal code, and then click
Create. The token is returned to https://jwt.ms and should be displayed to you.
7. You can now run the user flow again and you should be able to sign in with the account that you created. The
returned token includes the claims that you selected of country/region, name, and postal code.
Next steps
In this article, you learned how to:
Create a sign-up and sign-in user flow
Create a profile editing user flow
Create a password reset user flow
Next, learn about adding identity providers to your applications to enable user sign-in with providers like Azure AD,
Amazon, Facebook, GitHub, LinkedIn, Microsoft, or Twitter.
Add identity providers to your applications >
Tutorial: Add identity providers to your applications
in Azure Active Directory B2C
12/9/2019 • 6 minutes to read • Edit Online
In your applications, you may want to enable users to sign in with different identity providers. An identity provider
creates, maintains, and manages identity information while providing authentication services to applications. You
can add identity providers that are supported by Azure Active Directory B2C (Azure AD B2C ) to your user flows
using the Azure portal.
In this article, you learn how to:
Create the identity provider applications
Add the identity providers to your tenant
Add the identity providers to your user flow
You typically use only one identity provider in your applications, but you have the option to add more. This tutorial
shows you how to add an Azure AD identity provider and a Facebook identity provider to your application. Adding
both of these identity providers to your application is optional. You can also add other identity providers, such as
Amazon, GitHub, Google, LinkedIn, Microsoft, or Twitter.
If you don't have an Azure subscription, create a free account before you begin.
Prerequisites
Create a user flow to enable users to sign up and sign in to your application.
Create applications
Identity provider applications provide the identifier and key to enable communication with your Azure AD B2C
tenant. In this section of the tutorial, you create an Azure AD application and a Facebook application from which
you get identifiers and keys to add the identity providers to your tenant. If you're adding just one of the identity
providers, you only need to create the application for that provider.
Create an Azure Active Directory application
To enable sign-in for users from Azure AD, you need to register an application within the Azure AD tenant. The
Azure AD tenant is not the same as your Azure AD B2C tenant.
1. Sign in to the Azure portal.
2. Make sure you're using the directory that contains your Azure AD tenant by selecting the Directory +
subscription filter in the top menu and choosing the directory that contains your Azure AD tenant.
3. Choose All services in the top-left corner of the Azure portal, and then search for and select App
registrations.
4. Select New registration.
5. Enter a name for your application. For example, Azure AD B2C App .
6. Accept the selection of Accounts in this organizational directory only for this application.
7. For the Redirect URI, accept the value of Web and enter the following URL in all lowercase letters,
replacing your-B2C-tenant-name with the name of your Azure AD B2C tenant.
https://your-B2C-tenant-name.b2clogin.com/your-B2C-tenant-name.onmicrosoft.com/oauth2/authresp
https://login.microsoftonline.com/your-AD-tenant-domain/.well-known/openid-configuration
{
"typ": "JWT",
"alg": "RS256",
"kid": "<key-ID>"
}.{
"exp": 1562346892,
"nbf": 1562343292,
"ver": "1.0",
"iss": "https://your-b2c-tenant.b2clogin.com/10000000-0000-0000-0000-000000000000/v2.0/",
"sub": "20000000-0000-0000-0000-000000000000",
"aud": "30000000-0000-0000-0000-000000000000",
"nonce": "defaultNonce",
"iat": 1562343292,
"auth_time": 1562343292,
"name": "User Name",
"idp": "facebook.com",
"postalCode": "12345",
"tfp": "B2C_1_signupsignin1"
}.[Signature]
Next steps
In this article, you learned how to:
Create the identity provider applications
Add the identity providers to your tenant
Add the identity providers to your user flow
Next, learn how to customize the UI of the pages shown to users as part of their identity experience in your
applications:
Customize the user interface of your applications in Azure Active Directory B2C
Tutorial: Customize the interface of user experiences
in Azure Active Directory B2C
12/9/2019 • 4 minutes to read • Edit Online
For more common user experiences, such as sign-up, sign-in, and profile editing, you can use user flows in Azure
Active Directory B2C (Azure AD B2C ). The information in this tutorial helps you to learn how to customize the
user interface (UI) of these experiences using your own HTML and CSS files.
In this article, you learn how to:
Create UI customization files
Update the user flow to use the files
Test the customized UI
If you don't have an Azure subscription, create a free account before you begin.
Prerequisites
Create a user flow to enable users to sign up and sign in to your application.
7. Click Save.
Create the customization files
To customize the UI of the sign-up experience, you start by creating a simple HTML and CSS file. You can
configure your HTML any way you want, but it must have a div element with an identifier of api . For example,
<div id="api"></div> . Azure AD B2C injects elements into the api container when the page is displayed.
1. In a local folder, create the following file and make sure that you change your-storage-account to the name
of the storage account and your-container to the name of the container that you created. For example,
https://store1.blob.core.windows.net/b2c/style.css .
<!DOCTYPE html>
<html>
<head>
<title>My B2C Application</title>
<link rel="stylesheet" href="https://your-storage-account.blob.core.windows.net/your-
container/style.css">
</head>
<body>
<h1>My B2C Application</h1>
<div id="api"></div>
</body>
</html>
The page can be designed any way that you want, but the api div element is required for any HTML
customization file that you create.
2. Save the file as custom -ui.html.
3. Create the following simple CSS that centers all elements on the sign-up or sign-in page including the
elements that Azure AD B2C injects.
h1 {
color: blue;
text-align: center;
}
.intro h2 {
text-align: center;
}
.entry {
width: 300px ;
margin-left: auto ;
margin-right: auto ;
}
.divider h2 {
text-align: center;
}
.create {
width: 300px ;
margin-left: auto ;
margin-right: auto ;
}
4. Copy the URL for the file that you uploaded to use later in the tutorial.
5. Repeat step 3 and 4 for the style.css file.
You should see a page similar to the following example with the elements centered based on the CSS file
that you created:
Next steps
In this article, you learned how to:
Create UI customization files
Update the user flow to use the files
Test the customized UI
Language customization in Azure Active Directory B2C
Tutorial: Enable authentication in a web application
using Azure Active Directory B2C
12/10/2019 • 5 minutes to read • Edit Online
This tutorial shows you how to use Azure Active Directory B2C (Azure AD B2C ) to sign in and sign up users in an
ASP.NET web application. Azure AD B2C enables your applications to authenticate to social accounts, enterprise
accounts, and Azure Active Directory accounts using open standard protocols.
In this tutorial, you learn how to:
Update the application in Azure AD B2C
Configure the sample to use the application
Sign up using the user flow
If you don't have an Azure subscription, create a free account before you begin.
Prerequisites
Create user flows to enable user experiences in your application.
Install Visual Studio 2019 with the ASP.NET and web development workload.
Next steps
In this tutorial, you learned how to:
Update the application in Azure AD B2C
Configure the sample to use the application
Sign up using the user flow
Now move on to the next tutorial to enable the To-Do List feature of the web application. In it, you register a web
API application in your own Azure AD B2C tenant, and then modify the code sample to use your tenant for API
authentication.
Tutorial: Use Azure Active Directory B2C to protect an ASP.NET web API >
Tutorial: Authenticate users in a native desktop client
using Azure Active Directory B2C
12/9/2019 • 5 minutes to read • Edit Online
This tutorial shows you how to use Azure Active Directory B2C (Azure AD B2C ) to sign in and sign up users in an
Windows Presentation Foundation (WPF ) desktop application. Azure AD B2C enables your applications to
authenticate to social accounts, enterprise accounts, and Azure Active Directory accounts using open standard
protocols.
In this tutorial, you learn how to:
Add the native client application
Configure the sample to use the application
Sign up using the user flow
If you don't have an Azure subscription, create a free account before you begin.
Prerequisites
Create user flows to enable user experiences in your application.
Install Visual Studio 2019 with .NET desktop development and ASP.NET and web development
workloads.
To update the application to work with your Azure AD B2C tenant and invoke its user flows instead of those in the
default demo tenant:
1. Open the active-directory-b2c-wpf solution ( active-directory-b2c-wpf.sln ) in Visual Studio.
2. In the active-directory-b2c-wpf project, open the App.xaml.cs file and find the following variable
definitions. Replace {your-tenant-name} with your Azure AD B2C tenant name and {application-ID} with
the application ID that you recorded earlier.
3. Update the policy name variables with the names of the user flows that you created as part of the
prerequisites. For example:
If you select the Call API button, an error message is displayed. You encounter the error because, in its current
state, the application is attempting to access an API protected by the demo tenant, fabrikamb2c.onmicrosoft.com .
Since your access token is valid only for your Azure AD B2C tenant, the API call is therefore unauthorized.
Continue to the next tutorial to register a protected web API in your own tenant and enable the Call API
functionality.
Next steps
In this tutorial, you learned how to:
Add the native client application
Configure the sample to use the application
Sign up using the user flow
Next, to enable the Call API button functionality, grant the WPF desktop application access to a web API
registered in your own Azure AD B2C tenant:
Tutorial: Grant access to a Node.js web API from a desktop app >
Tutorial: Enable authentication in a single-page
application using Azure Active Directory B2C (Azure
AD B2C)
12/9/2019 • 5 minutes to read • Edit Online
This tutorial shows you how to use Azure Active Directory B2C (Azure AD B2C ) to sign in and sign up users in a
single-page application (SPA). Azure AD B2C enables your applications to authenticate to social accounts,
enterprise accounts, and Azure Active Directory accounts using open standard protocols.
In this tutorial, you learn how to:
Update the application in Azure AD B2C
Configure the sample to use the application
Sign up using the user flow
If you don't have an Azure subscription, create a free account before you begin.
Prerequisites
You need the following Azure AD B2C resources in place before continuing with the steps in this tutorial:
Azure AD B2C tenant
Application registered in your tenant
User flows created in your tenant
Additionally, you need the following in your local development environment:
Code editor, for example Visual Studio Code or Visual Studio 2019
.NET Core SDK 2.2 or later
Node.js
var msalConfig = {
auth: {
clientId: "00000000-0000-0000-0000-000000000000", //This is your client ID
authority: "https://fabrikamb2c.b2clogin.com/fabrikamb2c.onmicrosoft.com/b2c_1_susi", //This is
your tenant info
validateAuthority: false
},
cache: {
cacheLocation: "localStorage",
storeAuthStateInCookie: true
}
};
The name of the user flow used in this tutorial is B2C_1_signupsignin1. If you're using a different user flow
name, specify that name in the authority value.
cd active-directory-b2c-javascript-msal-singlepageapp
The console window displays the port number of the locally running Node.js server:
Listening on port 6420...
The sample supports sign-up, sign-in, profile editing, and password reset. This tutorial highlights how a user signs
up using an email address.
Sign up using an email address
WARNING
After sign-up or sign-in, you might see an insufficient permissions error. Due to the code sample's current implementation,
this error is expected. This issue will be resolved in a future version of the code sample, at which time this warning will be
removed.
1. Select Login to initiate the B2C_1_signupsignin1 user flow you specified in an earlier step.
2. Azure AD B2C presents a sign-in page with a sign-up link. Since you don't yet have an account, select the
Sign up now link.
3. The sign-up workflow presents a page to collect and verify the user's identity using an email address. The
sign-up workflow also collects the user's password and the requested attributes defined in the user flow.
Use a valid email address and validate using the verification code. Set a password. Enter values for the
requested attributes.
ServerError: AADB2C90205: This application does not have sufficient permissions against this web resource to
perform the operation.
Correlation ID: ce15bbcc-0000-0000-0000-494a52e95cd7
Timestamp: 2019-07-20 22:17:27Z
You receive this error because the web application is attempting to access a web API protected by the demo
directory, fabrikamb2c. Because your access token is valid only for your Azure AD directory, the API call is
unauthorized.
To fix this error, continue on to the next tutorial in the series (see Next steps) to create a protected web API for your
directory.
Next steps
In this article, you learned how to:
Update the application in Azure AD B2C
Configure the sample to use the application
Sign up using the user flow
Now move on to the next tutorial in the series to grant access to a protected web API from the SPA:
Tutorial: Grant access to an ASP.NET Core web API from an SPA using Azure AD B2C >
Tutorial: Grant access to an ASP.NET web API using
Azure Active Directory B2C
12/9/2019 • 7 minutes to read • Edit Online
This tutorial shows you how to call a protected web API resource in Azure Active Directory B2C (Azure AD B2C )
from an ASP.NET web application.
In this tutorial, you learn how to:
Add a web API application
Configure scopes for a web API
Grant permissions to the web API
Configure the sample to use the application
If you don't have an Azure subscription, create a free account before you begin.
Prerequisites
Complete the steps and prerequisites in Tutorial: Enable authenticate in a web application using Azure Active
Directory B2C.
Configure scopes
Scopes provide a way to govern access to protected resources. Scopes are used by the web API to implement
scope-based access control. For example, users of the web API could have both read and write access, or users of
the web API might have only read access. In this tutorial, you use scopes to define read and write permissions for
the web API.
Applications
App registrations (Preview )
1. Select Applications.
2. Select the webapi1 application to open its Properties page.
3. Select Published scopes. Published scopes can be used to grant a client application certain permissions to the
web API.
4. For SCOPE, enter demo.read , and for DESCRIPTION, enter Read access to the web API .
5. For SCOPE, enter demo.write , and for DESCRIPTION, enter Write access to the web API .
6. Select Save.
Grant permissions
To call a protected web API from an application, you need to grant your application permissions to the API. In the
prerequisite tutorial, you created a web application in Azure AD B2C named webapp1. You use this application to
call the web API.
Applications
App registrations (Preview )
1. Select Applications, and then select the web application that should have access to the API. For example,
webapp1.
2. Select API access, and then select Add.
3. In the Select API dropdown, select the API to which web application should be granted access. For example,
webapi1.
4. In the Select Scopes dropdown, select the scopes that you defined earlier. For example, demo.read and
demo.write.
5. Select OK.
Your application is registered to call the protected web API. A user authenticates with Azure AD B2C to use the
application. The application obtains an authorization grant from Azure AD B2C to access the protected web API.
4. Configure the URI of the API. This is the URI the web application uses to make the API request. Also,
configure the requested permissions.
3. Set the client ID to the Application ID of your registered web API application, webapi1.
4. Update the user flow setting with the name of your sign-up and sign-in user flow, B2C_1_signupsignin1.
5. Configure the scopes setting to match those you created in the portal.
Next steps
In this tutorial, you learned how to:
Add a web API application
Configure scopes for a web API
Grant permissions to the web API
Configure the sample to use the application
Tutorial: Add identity providers to your applications in Azure Active Directory B2C
Tutorial: Grant access to a Node.js web API from a
desktop app using Azure Active Directory B2C
12/9/2019 • 7 minutes to read • Edit Online
This tutorial shows you how to call a Node.js web API protected by Azure Active Directory B2C (Azure AD B2C )
from a Windows Presentation Foundation (WPF ) desktop app, also protected by Azure AD B2C.
In this tutorial, you learn how to:
Add a web API application
Configure scopes for a web API
Grant permissions to the web API
Update the sample to use the application
Prerequisites
Complete the steps and prerequisites in Tutorial: Authenticate users in a native desktop client.
Configure scopes
Scopes provide a way to govern access to protected resources. Scopes are used by the web API to implement
scope-based access control. For example, some users could have both read and write access, whereas other users
might have read-only permissions. In this tutorial, you define read and write permissions for the web API.
Applications
App registrations (Preview )
1. Select Applications.
2. Select the webapi1 application to open its Properties page.
3. Select Published scopes. Published scopes can be used to grant a client application certain permissions to the
web API.
4. For SCOPE, enter demo.read , and for DESCRIPTION, enter Read access to the web API .
5. For SCOPE, enter demo.write , and for DESCRIPTION, enter Write access to the web API .
6. Select Save.
Record the value under SCOPES for the demo.read scope to use in a later step when you configure the desktop
application. The full scope value is similar to https://contosob2c.onmicrosoft.com/api/demo.read .
Grant permissions
To call a protected web API from a native client application, you need to grant the registered native client
application permissions to the web API you registered in Azure AD B2C.
In the prerequisite tutorial, you registered a native client application named nativeapp1. The following steps
configure that native application registration with the API scopes you exposed for webapi1 in the previous section.
This allows the desktop application to obtain an access token from Azure AD B2C that the web API can use to
verify and provide scoped access to its resources. You configure and run both the desktop application and web API
code samples later in the tutorial.
Applications
App registrations (Preview )
1. Select Applications, and then select nativeapp1.
2. Select API access, and then select Add.
3. In the Select API dropdown, select webapi1.
4. In the Select Scopes dropdown, select the scopes that you defined earlier. For example, demo.read and
demo.write.
5. Select OK.
A user authenticates with Azure AD B2C to use the WPF desktop application. The desktop application obtains an
authorization grant from Azure AD B2C to access the protected web API.
The Node.js web API sample uses the Passport.js library to enable Azure AD B2C to protect calls to the API.
1. Open the index.js file.
2. Update these variable definitions with the following values. Change <web-API-application-ID> to the
Application (client) ID of the web API you registered earlier (webapi1). Change <your-b2c-tenant> to the
name of your Azure AD B2C tenant.
3. Since you're running the API locally, update the path in the route for the GET method to / instead of the
demo app's location of /hello :
app.get("/",
node index.js
Your desktop application, protected by Azure AD B2C, is calling the locally running web API that is also protected
by Azure AD B2C.
Next steps
In this tutorial, you learned how to:
Add a web API application
Configure scopes for a web API
Grant permissions to the web API
Update the sample to use the application
Tutorial: Add identity providers to your applications in Azure Active Directory B2C
Tutorial: Grant access to an ASP.NET Core web API
from a single-page application using Azure Active
Directory B2C
12/9/2019 • 9 minutes to read • Edit Online
This tutorial shows you how to call an Azure Active Directory B2C (Azure AD B2C )-protected ASP.NET Core web
API resource from a single-page application.
In this tutorial, you learn how to:
Add a web API application
Configure scopes for a web API
Grant permissions to the web API
Configure the sample to use the application
Prerequisites
Complete the steps and prerequisites in Tutorial: Enable authentication in a single-page application using Azure
Active Directory B2C.
Visual Studio 2019 or later, or Visual Studio Code
.NET Core 2.2 or later
Node.js
Configure scopes
Scopes provide a way to govern access to protected resources. Scopes are used by the web API to implement
scope-based access control. For example, some users could have both read and write access, whereas other users
might have read-only permissions. In this tutorial, you define both read and write permissions for the web API.
Applications
App registrations (Preview )
1. Select Applications.
2. Select the webapi1 application to open its Properties page.
3. Select Published scopes. Published scopes can be used to grant a client application certain permissions to the
web API.
4. For SCOPE, enter demo.read , and for DESCRIPTION, enter Read access to the web API .
5. For SCOPE, enter demo.write , and for DESCRIPTION, enter Write access to the web API .
6. Select Save.
Record the value under SCOPES for the demo.read scope to use in a later step when you configure the single-
page application. The full scope value is similar to https://contosob2c.onmicrosoft.com/api/demo.read .
Grant permissions
To call a protected web API from another application, you need to grant that application permissions to the web
API.
In the prerequisite tutorial, you created a web application named webapp1. In this tutorial, you configure that
application to call the web API you created in a previous section, webapi1.
Applications
App registrations (Preview )
1. Select Applications, and then select the web application that should have access to the API. For example,
webapp1.
2. Select API access, and then select Add.
3. In the Select API dropdown, select the API to which web application should be granted access. For example,
webapi1.
4. In the Select Scopes dropdown, select the scopes that you defined earlier. For example, demo.read and
demo.write.
5. Select OK.
Your single-page web application is registered to call the protected web API. A user authenticates with Azure AD
B2C to use the single-page application. The single-page app obtains an authorization grant from Azure AD B2C to
access the protected web API.
"AzureAdB2C": {
"Tenant": "<your-tenant-name>.onmicrosoft.com",
"ClientId": "<webapi-application-ID>",
"Policy": "B2C_1_signupsignin1",
"ScopeRead": "demo.read",
"ScopeWrite": "demo.write"
},
Enable CORS
To allow your single-page application to call the ASP.NET Core web API, you need to enable CORS in the web API.
1. In Startup.cs, add CORS to the ConfigureServices() method.
2. Also within the ConfigureServices() method, set the jwtOptions.Authority value to the following token
issuer URI.
Replace <your-tenant-name> with the name of your B2C tenant.
jwtOptions.Authority = $"https://<your-tenant-
name>.b2clogin.com/{Configuration["AzureAdB2C:Tenant"]}/{Configuration["AzureAdB2C:Policy"]}/v2.0";
4. (Visual Studio only) Under Properties in the Solution Explorer, open the launchSettings.json file, then find
the iisExpress block.
5. (Visual Studio only) Update the applicationURL value with the port number you specified when you
registered the webapi1 application in an earlier step. For example:
"iisExpress": {
"applicationUrl": "http://localhost:5000/",
"sslPort": 0
}
$ dotnet run
Hosting environment: Production
Content root path: /home/user/active-directory-b2c-dotnetcore-webapi/B2C-WebApi
Now listening on: http://localhost:5000
Application started. Press Ctrl+C to shut down.
The console window displays the port number of where the application is hosted.
Next steps
In this tutorial, you learned how to:
Add a web API application
Configure scopes for a web API
Grant permissions to the web API
Configure the sample to use the application
Now that you've seen an SPA request a resource from a protected web API, gain a deeper understanding of how
these application types interact with each other and with Azure AD B2C.
Application types that can be used in Active Directory B2C >
Azure Active Directory B2C code samples
6/4/2019 • 2 minutes to read • Edit Online
The following tables provide links to samples for applications including iOS, Android, .NET, and Node.js.
ios-native-appauth A sample that shows how you can use a third party library to
build an iOS application in Objective-C that authenticates
Microsoft identity users to our Azure AD B2C identity service.
android-native-appauth A sample that shows how you can use a third party library to
build an Android application that authenticates Microsoft
identity users to our B2C identity service and calls a web API
using OAuth 2.0 access tokens.
dotnet-webapp-and-webapi A combined sample for a .NET web application that calls a .NET
Web API, both secured using Azure AD B2C.
dotnetcore-webapp An ASP.NET Core web application that can sign in a user using
Azure AD B2C, get an access token using MSAL.NET and call
an API.
openidconnect-nodejs A Node.js app that provides a quick and easy way to set up a
Web application with Express using OpenID Connect.
javascript-nodejs-webapp A node.js server that provides a quick and easy way to set up
a REST API service using the OAuth2 protocol.
SAMPLE DESCRIPTION
javascript-nodejs-webapi A small node.js Web API for Azure AD B2C that shows how to
protect your web api and accept B2C access tokens using
passport.js.
Azure Active Directory B2C (Azure AD B2C ) supports authentication for a variety of modern application
architectures. All of them are based on the industry standard protocols OAuth 2.0 or OpenID Connect. This article
describes the types of applications that you can build, independent of the language or platform you prefer. It also
helps you understand the high-level scenarios before you start building applications.
Every application that uses Azure AD B2C must be registered in your Azure AD B2C tenant by using the Azure
portal. The application registration process collects and assigns values, such as:
An Application ID that uniquely identifies your application.
A Reply URL that can be used to direct responses back to your application.
Each request that is sent to Azure AD B2C specifies a user flow (a built-in policy) or a custom policy that
controls the behavior of Azure AD B2C. Both policy types enable you to create a highly customizable set of user
experiences.
The interaction of every application follows a similar high-level pattern:
1. The application directs the user to the v2.0 endpoint to execute a policy.
2. The user completes the policy according to the policy definition.
3. The application receives a security token from the v2.0 endpoint.
4. The application uses the security token to access protected information or a protected resource.
5. The resource server validates the security token to verify that access can be granted.
6. The application periodically refreshes the security token.
These steps can differ slightly based on the type of application you're building.
Web applications
For web applications (including .NET, PHP, Java, Ruby, Python, and Node.js) that are hosted on a server and
accessed through a browser, Azure AD B2C supports OpenID Connect for all user experiences. In the Azure AD
B2C implementation of OpenID Connect, your web application initiates user experiences by issuing authentication
requests to Azure AD. The result of the request is an id_token . This security token represents the user's identity. It
also provides information about the user in the form of claims:
Learn more about the types of tokens and claims available to an application in the Azure AD B2C token reference.
In a web application, each execution of a policy takes these high-level steps:
1. The user browses to the web application.
2. The web application redirects the user to Azure AD B2C indicating the policy to execute.
3. The user completes policy.
4. Azure AD B2C returns an id_token to the browser.
5. The id_token is posted to the redirect URI.
6. The id_token is validated and a session cookie is set.
7. A secure page is returned to the user.
Validation of the id_token by using a public signing key that is received from Azure AD is sufficient to verify the
identity of the user. This process also sets a session cookie that can be used to identify the user on subsequent
page requests.
To see this scenario in action, try one of the web application sign-in code samples in our Getting started section.
In addition to facilitating simple sign-in, a web server application might also need to access a back-end web
service. In this case, the web application can perform a slightly different OpenID Connect flow and acquire tokens
by using authorization codes and refresh tokens. This scenario is depicted in the following Web APIs section.
Web APIs
You can use Azure AD B2C to secure web services such as your application's RESTful web API. Web APIs can use
OAuth 2.0 to secure their data, by authenticating incoming HTTP requests using tokens. The caller of a web API
appends a token in the authorization header of an HTTP request:
The web API can then use the token to verify the API caller's identity and to extract information about the caller
from claims that are encoded in the token. Learn more about the types of tokens and claims available to an app in
the Azure AD B2C token reference.
A web API can receive tokens from many types of clients, including web applications, desktop and mobile
applications, single page applications, server-side daemons, and other web APIs. Here's an example of the
complete flow for a web application that calls a web API:
1. The web application executes a policy and the user completes the user experience.
2. Azure AD B2C returns an (OpenID Connect) id_token and an authorization code to the browser.
3. The browser posts the id_token and authorization code to the redirect URI.
4. The web server validates the id_token and sets a session cookie.
5. The web server asks Azure AD B2C for an access_token by providing it with the authorization code,
application client ID, and client credentials.
6. The access_token and refresh_token are returned to the web server.
7. The web API is called with the access_token in an authorization header.
8. The web API validates the token.
9. Secure data is returned to the web application.
To learn more about authorization codes, refresh tokens, and the steps for getting tokens, read about the OAuth
2.0 protocol.
To learn how to secure a web API by using Azure AD B2C, check out the web API tutorials in our Getting started
section.
Current limitations
Unsupported application types
Daemons/server-side applications
Applications that contain long-running processes or that operate without the presence of a user also need a way
to access secured resources such as web APIs. These applications can authenticate and get tokens by using the
application's identity (rather than a user's delegated identity) and by using the OAuth 2.0 client credentials flow.
Client credential flow is not the same as on-behalf-flow and on-behalf-flow should not be used for server-to-
server authentication.
Although client credential flow is not currently supported by Azure AD B2C, you can set up client credential flow
using Azure AD. An Azure AD B2C tenant shares some functionality with Azure AD enterprise tenants. The client
credential flow is supported using the Azure AD functionality of the Azure AD B2C tenant.
To set up client credential flow, see Azure Active Directory v2.0 and the OAuth 2.0 client credentials flow. A
successful authentication results in the receipt of a token formatted so that it can be used by Azure AD as
described in Azure AD token reference.
Web API chains (on-behalf-of flow)
Many architectures include a web API that needs to call another downstream web API, where both are secured by
Azure AD B2C. This scenario is common in native clients that have a Web API back-end and calls a Microsoft
online service such as the Microsoft Graph API or Azure AD Graph API.
This chained web API scenario can be supported by using the OAuth 2.0 JWT bearer credential grant, also known
as the on-behalf-of flow. However, the on-behalf-of flow is not currently implemented in the Azure AD B2C.
Faulted apps
Do not edit Azure AD B2C applications in these ways:
On other application management portals such as the Application Registration Portal.
Using Graph API or PowerShell.
If you edit the Azure AD B2C application outside of the Azure portal, it becomes a faulted application and is no
longer usable with Azure AD B2C. Delete the application and create it again.
To delete the application, go to the Application Registration Portal and delete the application there. In order for the
application to be visible, you need to be the owner of the application (and not just an admin of the tenant).
Next steps
Find out more about the built-in policies provided by User flows in Azure Active Directory B2C.
Azure AD B2C: Authentication protocols
7/11/2019 • 4 minutes to read • Edit Online
Azure Active Directory B2C (Azure AD B2C ) provides identity as a service for your apps by supporting two
industry standard protocols: OpenID Connect and OAuth 2.0. The service is standards-compliant, but any two
implementations of these protocols can have subtle differences.
The information in this guide is useful if you write your code by directly sending and handling HTTP requests,
rather than by using an open source library. We recommend that you read this page before you dive into the
details of each specific protocol. But if you're already familiar with Azure AD B2C, you can go straight to the
protocol reference guides.
The basics
Every app that uses Azure AD B2C needs to be registered in your B2C directory in the Azure portal. The app
registration process collects and assigns a few values to your app:
An Application ID that uniquely identifies your app.
A Redirect URI or package identifier that can be used to direct responses back to your app.
A few other scenario-specific values. For more information, learn how to register your application.
After you register your app, it communicates with Azure Active Directory (Azure AD ) by sending requests to the
endpoint:
https://{tenant}.b2clogin.com/{tenant}.onmicrosoft.com/oauth2/v2.0/authorize
https://{tenant}.b2clogin.com/{tenant}.onmicrosoft.com/oauth2/v2.0/token
In nearly all OAuth and OpenID Connect flows, four parties are involved in the exchange:
The authorization server is the Azure AD endpoint. It securely handles anything related to user
information and access. It also handles the trust relationships between the parties in a flow. It is
responsible for verifying the user's identity, granting and revoking access to resources, and issuing tokens.
It is also known as the identity provider.
The resource owner is typically the end user. It is the party that owns the data, and it has the power to
allow third parties to access that data or resource.
The OAuth client is your app. It's identified by its Application ID. It's usually the party that end users
interact with. It also requests tokens from the authorization server. The resource owner must grant the
client permission to access the resource.
The resource server is where the resource or data resides. It trusts the authorization server to securely
authenticate and authorize the OAuth client. It also uses bearer access tokens to ensure that access to a
resource can be granted.
Tokens
The Azure AD B2C implementation of OAuth 2.0 and OpenID Connect makes extensive use of bearer tokens,
including bearer tokens that are represented as JSON web tokens (JWTs). A bearer token is a lightweight security
token that grants the "bearer" access to a protected resource.
The bearer is any party that can present the token. Azure AD must first authenticate a party before it can receive
a bearer token. But 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.
Some security tokens have built-in mechanisms that prevent unauthorized parties from using them, but bearer
tokens do not have this mechanism. They must be transported in a secure channel, such as a transport layer
security (HTTPS ).
If a bearer token is transmitted outside a secure channel, a malicious party can use a man-in-the-middle attack to
acquire the token and use it to gain unauthorized access to a protected resource. The same security principles
apply when bearer tokens are stored or cached for later use. Always ensure that your app transmits and stores
bearer tokens in a secure manner.
For additional bearer token security considerations, see RFC 6750 Section 5.
More information about the different types of tokens that are used in Azure AD B2C are available in the Azure
AD token reference.
Protocols
When you're ready to review some example requests, you can start with one of the following tutorials. Each
corresponds to a particular authentication scenario. If you need help determining which flow is right for you,
check out the types of apps you can build by using Azure AD B2C.
Build mobile and native applications by using OAuth 2.0
Build web apps by using OpenID Connect
Build single-page apps using the OAuth 2.0 implicit flow
Web sign-in with OpenID Connect in Azure Active
Directory B2C
10/24/2019 • 15 minutes to read • Edit Online
OpenID Connect is an authentication protocol, built on top of OAuth 2.0, that can be used to securely sign users in
to web applications. By using the Azure Active Directory B2C (Azure AD B2C ) implementation of OpenID
Connect, you can outsource sign-up, sign-in, and other identity management experiences in your web applications
to Azure Active Directory (Azure AD ). This guide shows you how to do so in a language-independent manner. It
describes how to send and receive HTTP messages without using any of our open-source libraries.
OpenID Connect extends the OAuth 2.0 authorization protocol for use as an authentication protocol. This
authentication protocol allows you to perform single sign-on. It introduces the concept of an ID token, which
allows the client to verify the identity of the user and obtain basic profile information about the user.
Because it extends OAuth 2.0, it also enables applications to securely acquire access tokens. You can use access
tokens to access resources that are secured by an authorization server. OpenID Connect is recommended if you're
building a web application that's hosted on a server and accessed through a browser. If you want to add identity
management to your mobile or desktop applications using Azure AD B2C, you should use OAuth 2.0 rather than
OpenID Connect. For more information about tokens, see the Overview of tokens in Azure Active Directory B2C
Azure AD B2C extends the standard OpenID Connect protocol to do more than simple authentication and
authorization. It introduces the user flow parameter, which enables you to use OpenID Connect to add user
experiences to your application, such as sign-up, sign-in, and profile management.
In this request, the client indicates the permissions that it needs to acquire from the user in the scope parameter,
and specifies the user flow to run. To get a feel for how the request works, try pasting the request into a browser
and running it. Replace {tenant} with the name of your tenant. Replace 90c0fe63-bcf2-44d5-8fb7-b8bbc0b29dc6
with the app ID of the application you've previously registered in your tenant. Also change the policy name (
{policy} ) to the policy name that you have in your tenant, for example b2c_1_sign_in .
GET https://{tenant}.b2clogin.com/{tenant}.onmicrosoft.com/{policy}/oauth2/v2.0/authorize?
client_id=90c0fe63-bcf2-44d5-8fb7-b8bbc0b29dc6
&response_type=code+id_token
&redirect_uri=https%3A%2F%2Faadb2cplayground.azurewebsites.net%2F
&response_mode=form_post
&scope=openid%20offline_access
&state=arbitrary_data_you_can_receive_in_the_response
&nonce=12345
At this point, the user is asked to complete the workflow. The user might have to enter their username and
password, sign in with a social identity, or sign up for the directory. There could be any other number of steps
depending on how the user flow is defined.
After the user completes the user flow, a response is returned to your application at the indicated redirect_uri
parameter, by using the method that's specified in the response_mode parameter. The response is the same for
each of the preceding cases, independent of the user flow.
A successful response using response_mode=fragment would look like:
GET https://aadb2cplayground.azurewebsites.net/#
id_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik5HVEZ2ZEstZnl0aEV1Q...
&code=AwABAAAAvPM1KaPlrEqdFSBzjqfTGBCmLdgfSTLEMPGYuNHSUYBrq...
&state=arbitrary_data_you_can_receive_in_the_response
PARAMETER DESCRIPTION
id_token The ID token that the application requested. You can use the
ID token to verify the user's identity and begin a session with
the user.
Error responses can also be sent to the redirect_uri parameter so that the application can handle them
appropriately:
GET https://aadb2cplayground.azurewebsites.net/#
error=access_denied
&error_description=the+user+canceled+the+authentication
&state=arbitrary_data_you_can_receive_in_the_response
PARAMETER DESCRIPTION
error A code that can be used to classify the types of errors that
occur.
error_description A specific error message that can help identify the root cause
of an authentication error.
https://fabrikamb2c.b2clogin.com/fabrikamb2c.onmicrosoft.com/b2c_1_sign_in/v2.0/.well-known/openid-
configuration
One of the properties of this configuration document is jwks_uri , whose value for the same user flow would be:
https://fabrikamb2c.b2clogin.com/fabrikamb2c.onmicrosoft.com/b2c_1_sign_in/discovery/v2.0/keys
To determine which user flow was used in signing an ID token (and from where to get the metadata), you have
two options. First, the user flow name is included in the acr claim in the ID token. Your other option is to encode
the user flow in the value of the state parameter when you issue the request, and then decode it to determine
which user flow was used. Either method is valid.
After you've acquired the metadata document from the OpenID Connect metadata endpoint, you can use the RSA
256 public keys to validate the signature of the ID token. There might be multiple keys listed at this endpoint, each
identified by a kid claim. The header of the ID token also contains a kid claim, which indicates which of these
keys was used to sign the ID token.
To verify the tokens from Azure AD B2C, you need to generate the public key using the exponent(e) and
modulus(n). You need to determine how to do this in your respective programming language accordingly. The
official documentation on Public Key generation with the RSA protocol can be found here:
https://tools.ietf.org/html/rfc3447#section-3.1
After you've validated the signature of the ID token, there are several claims that you need to verify. For instance:
Validate the nonce claim to prevent token replay attacks. Its value should be what you specified in the sign-in
request.
Validate the aud claim to ensure that the ID token was issued for your application. Its value should be the
application ID of your application.
Validate the iat and exp claims to make sure that the ID token hasn't expired.
There are also several more validations that you should perform. The validations are described in detail in the
OpenID Connect Core Spec. You might also want to validate additional claims, depending on your scenario. Some
common validations include:
Ensuring that the user/organization has signed up for the application.
Ensuring that the user has proper authorization/privileges.
Ensuring that a certain strength of authentication has occurred, such as Azure Multi-Factor Authentication.
After you validate the ID token, you can begin a session with the user. You can use the claims in the ID token to
obtain information about the user in your application. Uses for this information include display, records, and
authorization.
Get a token
If you need your web application to only run user flows, you can skip the next few sections. These sections are
applicable only to web applications that need to make authenticated calls to a web API and are also protected by
Azure AD B2C.
You can redeem the authorization code that you acquired (by using response_type=code+id_token ) for a token to
the desired resource by sending a POST request to the /token endpoint. In Azure AD B2C, you can request
access tokens for other APIs as usual by specifying their scope(s) in the request.
You can also request an access token for your app's own back-end Web API by convention of using the app's
client ID as the requested scope (which will result in an access token with that client ID as the "audience"):
grant_type=authorization_code&client_id=90c0fe63-bcf2-44d5-8fb7-b8bbc0b29dc6&scope=90c0fe63-bcf2-44d5-8fb7-
b8bbc0b29dc6
offline_access&code=AwABAAAAvPM1KaPlrEqdFSBzjqfTGBCmLdgfSTLEMPGYuNHSUYBrq...&redirect_uri=urn:ietf:wg:oauth:2.
0:oob
{
"not_before": "1442340812",
"token_type": "Bearer",
"access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik5HVEZ2ZEstZnl0aEV1Q...",
"scope": "90c0fe63-bcf2-44d5-8fb7-b8bbc0b29dc6 offline_access",
"expires_in": "3600",
"refresh_token": "AAQfQmvuDy8WtUv-sd0TBwWVQs1rC-Lfxa_NDkLqpg50Cxp5Dxj0VPF1mx2Z...",
}
PARAMETER DESCRIPTION
not_before The time at which the token is considered valid, in epoch time.
token_type The token type value. Bearer is the only type that is
supported.
expires_in The length of time that the access token is valid (in seconds).
refresh_token An OAuth 2.0 refresh token. The application can use this
token to acquire additional tokens after the current token
expires. Refresh tokens can be used to retain access to
resources for extended periods of time. The scope
offline_access must have been used in both the
authorization and token requests in order to receive a refresh
token.
{
"error": "access_denied",
"error_description": "The user revoked access to the app.",
}
PARAMETER DESCRIPTION
error A code that can be used to classify types of errors that occur.
GET /tasks
Host: mytaskwebapi.com
Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik5HVEZ2ZEstZnl0aEV1Q...
grant_type=refresh_token&client_id=90c0fe63-bcf2-44d5-8fb7-b8bbc0b29dc6&scope=openid
offline_access&refresh_token=AwABAAAAvPM1KaPlrEqdFSBzjqfTGBCmLdgfSTLEMPGYuNHSUYBrq...&redirect_uri=urn:ietf:wg
:oauth:2.0:oob
PARAMETER REQUIRED DESCRIPTION
PARAMETER DESCRIPTION
not_before The time at which the token is considered valid, in epoch time.
token_type The token type value. Bearer is the only type that is
supported.
expires_in The length of time that the access token is valid (in seconds).
refresh_token An OAuth 2.0 refresh token. The application can use this
token to acquire additional tokens after the current token
expires. Refresh tokens can be used to retain access to
resources for extended periods of time.
{
"error": "access_denied",
"error_description": "The user revoked access to the app.",
}
PARAMETER DESCRIPTION
error A code that can be used to classify types of errors that occur.
GET https://{tenant}.b2clogin.com/{tenant}.onmicrosoft.com/{policy}/oauth2/v2.0/logout?
post_logout_redirect_uri=https%3A%2F%2Faadb2cplayground.azurewebsites.net%2F
PARAMETER REQUIRED DESCRIPTION
You can use the OAuth 2.0 authorization code grant in apps installed on a device to gain access to protected
resources, such as web APIs. By using the Azure Active Directory B2C (Azure AD B2C ) implementation of OAuth
2.0, you can add sign-up, sign-in, and other identity management tasks to your mobile and desktop apps. This
article is language-independent. In the article, we describe how to send and receive HTTP messages without
using any open-source libraries.
The OAuth 2.0 authorization code flow is described in section 4.1 of the OAuth 2.0 specification. You can use it
for authentication and authorization in most application types, including web applications and natively installed
applications. You can use the OAuth 2.0 authorization code flow to securely acquire access tokens and refresh
tokens for your applications, which can be used to access resources that are secured by an authorization server.
The refresh token allows the client to acquire new access (and refresh) tokens once the access token expires,
typically after one hour.
This article focuses on the public clients OAuth 2.0 authorization code flow. A public client is any client
application that cannot be trusted to securely maintain the integrity of a secret password. This includes mobile
apps, desktop applications, and essentially any application that runs on a device and needs to get access tokens.
NOTE
To add identity management to a web app by using Azure AD B2C, use OpenID Connect instead of OAuth 2.0.
Azure AD B2C extends the standard OAuth 2.0 flows to do more than simple authentication and authorization. It
introduces the user flow. With user flows, you can use OAuth 2.0 to add user experiences to your application,
such as sign-up, sign-in, and profile management. Identity providers that use the OAuth 2.0 protocol include
Amazon, Azure Active Directory, Facebook, GitHub, Google, and LinkedIn.
To try the HTTP requests in this article:
1. Replace {tenant} with the name of your Azure AD B2C tenant.
2. Replace 90c0fe63-bcf2-44d5-8fb7-b8bbc0b29dc6 with the app ID of an application you've previously registered
in your Azure AD B2C tenant.
3. Replace {policy} with the name of a policy you've created in your tenant, for example b2c_1_sign_in .
At this point, the user is asked to complete the user flow's workflow. This might involve the user entering their
username and password, signing in with a social identity, signing up for the directory, or any other number of
steps. User actions depend on how the user flow is defined.
After the user completes the user flow, Azure AD returns a response to your app at the value you used for
redirect_uri . It uses the method specified in the response_mode parameter. The response is exactly the same for
each of the user action scenarios, independent of the user flow that was executed.
A successful response that uses response_mode=query looks like this:
GET urn:ietf:wg:oauth:2.0:oob?
code=AwABAAAAvPM1KaPlrEqdFSBzjqfTGBCmLdgfSTLEMPGYuNHSUYBrq... // the authorization_code, truncated
&state=arbitrary_data_you_can_receive_in_the_response // the value provided in the request
PARAMETER DESCRIPTION
code The authorization code that the app requested. The app can
use the authorization code to request an access token for a
target resource. Authorization codes are very short-lived.
Typically, they expire after about 10 minutes.
state See the full description in the table in the preceding section.
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 responses also can be sent to the redirect URI so that the app can handle them appropriately:
GET urn:ietf:wg:oauth:2.0:oob?
error=access_denied
&error_description=The+user+has+cancelled+entering+self-asserted+information
&state=arbitrary_data_you_can_receive_in_the_response
PARAMETER DESCRIPTION
error An error code string that you can use to classify the types of
errors that occur. You also can use the string to react to
errors.
error_description A specific error message that can help you identify the root
cause of an authentication error.
2. Get a token
Now that you've acquired an authorization code, you can redeem the code for a token to the intended resource
by sending a POST request to the /token endpoint. In Azure AD B2C, you can request access tokens for other
API's as usual by specifying their scope(s) in the request.
You can also request an access token for your app's own back-end Web API by convention of using the app's
client ID as the requested scope (which will result in an access token with that client ID as the "audience"):
grant_type=authorization_code&client_id=90c0fe63-bcf2-44d5-8fb7-b8bbc0b29dc6&scope=90c0fe63-bcf2-44d5-8fb7-
b8bbc0b29dc6
offline_access&code=AwABAAAAvPM1KaPlrEqdFSBzjqfTGBCmLdgfSTLEMPGYuNHSUYBrq...&redirect_uri=urn:ietf:wg:oauth:
2.0:oob
{
"not_before": "1442340812",
"token_type": "Bearer",
"access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik5HVEZ2ZEstZnl0aEV1Q...",
"scope": "90c0fe63-bcf2-44d5-8fb7-b8bbc0b29dc6 offline_access",
"expires_in": "3600",
"refresh_token": "AAQfQmvuDy8WtUv-sd0TBwWVQs1rC-Lfxa_NDkLqpg50Cxp5Dxj0VPF1mx2Z...",
}
PARAMETER DESCRIPTION
token_type The token type value. The only type that Azure AD supports
is Bearer.
access_token The signed JSON Web Token (JWT) that you requested.
scope The scopes that the token is valid for. You also can use
scopes to cache tokens for later use.
expires_in The length of time that the token is valid (in seconds).
PARAMETER DESCRIPTION
refresh_token An OAuth 2.0 refresh token. The app can use this token to
acquire additional tokens after the current token expires.
Refresh tokens are long-lived. You can use them to retain
access to resources for extended periods of time. For more
information, see the Azure AD B2C token reference.
{
"error": "access_denied",
"error_description": "The user revoked access to the app.",
}
PARAMETER DESCRIPTION
error An error code string that you can use to classify the types of
errors that occur. You also can use the string to react to
errors.
error_description A specific error message that can help you identify the root
cause of an authentication error.
GET /tasks
Host: mytaskwebapi.com
Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik5HVEZ2ZEstZnl0aEV1Q...
grant_type=refresh_token&client_id=90c0fe63-bcf2-44d5-8fb7-b8bbc0b29dc6&scope=90c0fe63-bcf2-44d5-8fb7-
b8bbc0b29dc6
offline_access&refresh_token=AwABAAAAvPM1KaPlrEqdFSBzjqfTGBCmLdgfSTLEMPGYuNHSUYBrq...&redirect_uri=urn:ietf:
wg:oauth:2.0:oob
{
"not_before": "1442340812",
"token_type": "Bearer",
"access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik5HVEZ2ZEstZnl0aEV1Q...",
"scope": "90c0fe63-bcf2-44d5-8fb7-b8bbc0b29dc6 offline_access",
"expires_in": "3600",
"refresh_token": "AAQfQmvuDy8WtUv-sd0TBwWVQs1rC-Lfxa_NDkLqpg50Cxp5Dxj0VPF1mx2Z...",
}
PARAMETER DESCRIPTION
token_type The token type value. The only type that Azure AD supports
is Bearer.
scope The scopes that the token is valid for. You also can use the
scopes to cache tokens for later use.
expires_in The length of time that the token is valid (in seconds).
refresh_token An OAuth 2.0 refresh token. The app can use this token to
acquire additional tokens after the current token expires.
Refresh tokens are long-lived, and can be used to retain
access to resources for extended periods of time. For more
information, see the Azure AD B2C token reference.
{
"error": "access_denied",
"error_description": "The user revoked access to the app.",
}
PARAMETER DESCRIPTION
error An error code string that you can use to classify types of
errors that occur. You also can use the string to react to
errors.
error_description A specific error message that can help you identify the root
cause of an authentication error.
Many modern applications have a single-page app front end that is written primarily in JavaScript. Often, the app
is written by using a framework like React, Angular, or Vue.js. Single-page apps and other JavaScript apps that run
primarily in a browser have some additional challenges for authentication:
The security characteristics of these apps are different from traditional server-based web applications.
Many authorization servers and identity providers do not support cross-origin resource sharing (CORS )
requests.
Full-page browser redirects away from the app can be invasive to the user experience.
To support these applications, Azure Active Directory B2C (Azure AD B2C ) uses the OAuth 2.0 implicit flow. The
OAuth 2.0 authorization implicit grant flow is described in section 4.2 of the OAuth 2.0 specification. In implicit
flow, the app receives tokens directly from the Azure Active Directory (Azure AD ) authorize endpoint, without any
server-to-server exchange. All authentication logic and session handling is done entirely in the JavaScript client
with either a page redirect or a pop-up box.
Azure AD B2C extends the standard OAuth 2.0 implicit flow to more than simple authentication and authorization.
Azure AD B2C introduces the policy parameter. With the policy parameter, you can use OAuth 2.0 to add policies
to your app, such as sign-up, sign-in, and profile management user flows. In the example HTTP requests in this
article, {tenant}.onmicrosoft.com is used as an example. Replace {tenant} with the name of your tenant if you
have one and have also created a user flow.
The implicit sign-in flow looks something like the following figure. Each step is described in detail later in the
article.
Send authentication requests
When your web application needs to authenticate the user and run a user flow, it can direct the user to the
/authorize endpoint. The user takes action depending on the user flow.
In this request, the client indicates the permissions that it needs to acquire from the user in the scope parameter
and the user flow to run. To get a feel for how the request works, try pasting the request into a browser and
running it. Replace {tenant} with the name of your Azure AD B2C tenant. Replace
90c0fe63-bcf2-44d5-8fb7-b8bbc0b29dc6 with the app ID of the application you've previously registered in your
tenant. Replace {policy} with the name of a policy you've created in your tenant, for example b2c_1_sign_in .
GET https://{tenant}.b2clogin.com/{tenant}.onmicrosoft.com/{policy}/oauth2/v2.0/authorize?
client_id=90c0fe63-bcf2-44d5-8fb7-b8bbc0b29dc6
&response_type=id_token+token
&redirect_uri=https%3A%2F%2Faadb2cplayground.azurewebsites.net%2F
&response_mode=fragment
&scope=openid%20offline_access
&state=arbitrary_data_you_can_receive_in_the_response
&nonce=12345
At this point, the user is asked to complete the policy's workflow. The user might have to enter their username and
password, sign in with a social identity, sign up for the directory, or any other number of steps. User actions
depend on how the user flow is defined.
After the user completes the user flow, Azure AD returns a response to your app at the value you used for
redirect_uri . It uses the method specified in the response_mode parameter. The response is exactly the same for
each of the user action scenarios, independent of the user flow that was executed.
Successful response
A successful response that uses response_mode=fragment and response_type=id_token+token looks like the
following, with line breaks for legibility:
GET https://aadb2cplayground.azurewebsites.net/#
access_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik5HVEZ2ZEstZnl0aEV1Q...
&token_type=Bearer
&expires_in=3599
&scope="90c0fe63-bcf2-44d5-8fb7-b8bbc0b29dc6 offline_access",
&id_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik5HVEZ2ZEstZnl0aEV1Q...
&state=arbitrary_data_you_sent_earlier
PARAMETER DESCRIPTION
token_type The token type value. The only type that Azure AD supports is
Bearer.
expires_in The length of time that the access token is valid (in seconds).
scope The scopes that the token is valid for. You also can use scopes
to cache tokens for later use.
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. For more information about ID tokens and their
contents, see the Azure AD B2C token reference.
PARAMETER DESCRIPTION
Error response
Error responses also can be sent to the redirect URI so that the app can handle them appropriately:
GET https://aadb2cplayground.azurewebsites.net/#
error=access_denied
&error_description=the+user+canceled+the+authentication
&state=arbitrary_data_you_can_receive_in_the_response
PARAMETER DESCRIPTION
error_description A specific error message that can help you identify the root
cause of an authentication error.
https://fabrikamb2c.b2clogin.com/fabrikamb2c.onmicrosoft.com/b2c_1_sign_in/v2.0/.well-known/openid-
configuration
One of the properties of this configuration document is the jwks_uri . The value for the same user flow would be:
https://fabrikamb2c.b2clogin.com/fabrikamb2c.onmicrosoft.com/b2c_1_sign_in/discovery/v2.0/keys
To determine which user flow was used to sign an ID token (and where to fetch the metadata from), you have two
options. First, the user flow name is included in the acr claim in id_token . For information about how to parse
the claims from an ID token, see the Azure AD B2C token reference. Your other option is to encode the user flow in
the value of the state parameter when you issue the request. Then, decode the state parameter to determine
which user flow was used. Either method is valid.
After you've acquired the metadata document from the OpenID Connect metadata endpoint, you can use the
RSA-256 public keys (located at this endpoint) to validate the signature of the ID token. There might be multiple
keys listed at this endpoint at any given time, each identified by a kid . The header of id_token also contains a
kid claim. It indicates which of these keys was used to sign the ID token. For more information, including learning
about validating tokens, see the Azure AD B2C token reference.
After you validate the signature of the ID token, several claims require verification. For example:
Validate the nonce claim to prevent token replay attacks. Its value should be what you specified in the sign-in
request.
Validate the aud claim to ensure that the ID token was issued for your app. Its value should be the application
ID of your app.
Validate the iat and exp claims to ensure that the ID token has not expired.
Several more validations that you should perform are described in detail in the OpenID Connect Core Spec. You
might also want to validate additional claims, depending on your scenario. Some common validations include:
Ensuring that the user or organization has signed up for the app.
Ensuring that the user has proper authorization and privileges.
Ensuring that a certain strength of authentication has occurred, such as by using Azure Multi-Factor
Authentication.
For more information about the claims in an ID token, see the Azure AD B2C token reference.
After you have validated the ID token, you can begin a session with the user. In your app, use the claims in the ID
token to obtain information about the user. This information can be used for display, records, authorization, and so
on.
https://{tenant}.b2clogin.com/{tenant}.onmicrosoft.com/{policy}/oauth2/v2.0/authorize?
client_id=90c0fe63-bcf2-44d5-8fb7-b8bbc0b29dc6
&response_type=token
&redirect_uri=https%3A%2F%2Faadb2cplayground.azurewebsites.net%2F
&scope=https%3A%2F%2Fapi.contoso.com%2Ftasks.read
&response_mode=fragment
&state=arbitrary_data_you_can_receive_in_the_response
&nonce=12345
&prompt=none
PARAMETER REQUIRED? DESCRIPTION
By setting the prompt=none parameter, this request either succeeds or fails immediately, and returns to your
application. A successful response is sent to your app at the indicated redirect URI, by using the method specified
in the response_mode parameter.
Successful response
A successful response by using response_mode=fragment looks like this example:
GET https://aadb2cplayground.azurewebsites.net/#
access_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik5HVEZ2ZEstZnl0aEV1Q...
&state=arbitrary_data_you_sent_earlier
&token_type=Bearer
&expires_in=3599
&scope=https%3A%2F%2Fapi.contoso.com%2Ftasks.read
PARAMETER DESCRIPTION
Error response
Error responses also can be sent to the redirect URI so that the app can handle them appropriately. For
prompt=none , an expected error looks like this example:
GET https://aadb2cplayground.azurewebsites.net/#
error=user_authentication_required
&error_description=the+request+could+not+be+completed+silently
PARAMETER DESCRIPTION
error_description A specific error message that can help you identify the root
cause of an authentication error.
If you receive this error in the iframe request, the user must interactively sign in again to retrieve a new token.
Refresh tokens
ID tokens and access tokens both expire after a short period of time. Your app must be prepared to refresh these
tokens periodically. To refresh either type of token, perform the same hidden iframe request we used in an earlier
example, by using the prompt=none parameter to control Azure AD steps. To receive a new id_token value, be sure
to use response_type=id_token and scope=openid , and a nonce parameter.
GET https://{tenant}.b2clogin.com/{tenant}.onmicrosoft.com/{policy}/oauth2/v2.0/logout?
post_logout_redirect_uri=https%3A%2F%2Faadb2cplayground.azurewebsites.net%2F
PARAMETER REQUIRED DESCRIPTION
NOTE
Directing the user to the end_session_endpoint clears some of the user's single sign-on state with Azure AD B2C.
However, it doesn't sign the user out of the user's social identity provider session. If the user selects the same identity
provider during a subsequent sign-in, the user is re-authenticated, without entering their credentials. If a user wants to sign
out of your Azure AD B2C application, it does not necessarily mean they want to completely sign out of their Facebook
account, for example. However, for local accounts, the user's session will be ended properly.
Next steps
Code sample: hello.js with Azure AD B2C
Single-page application built on hello.js with Azure AD B2C (GitHub)
This sample on GitHub is intended to help get you started with Azure AD B2C in a simple web application built on
hello.js and using pop-up-style authentication.
Overview of tokens in Azure Active Directory B2C
8/26/2019 • 12 minutes to read • Edit Online
NOTE
In Azure Active Directory B2C, custom policies are designed primarily to address complex scenarios. For most scenarios,
we recommend that you use built-in user flows.
Azure Active Directory B2C (Azure AD B2C ) emits several types of security tokens as it processes each
authentication flow. This document describes the format, security characteristics, and contents of each type of
token.
Token types
Azure AD B2C supports the OAuth 2.0 and OpenID Connect protocols, which makes use of tokens for
authentication and secure access to resources. All tokens used in Azure AD B2C are JSON web tokens (JWTs)
that contain assertions of information about the bearer and the subject of the token.
The following tokens are used in communication with Azure AD B2C:
ID token - A JWT that contains claims that you can use to identify users in your application. This token is
securely sent in HTTP requests for communication between two components of the same application or
service. You can use the claims in an ID token as you see fit. They are commonly used to display account
information or to make access control decisions in an application. ID tokens are signed, but they are not
encrypted. When your application or API receives an ID token, it must validate the signature to prove that
the token is authentic. Your application or API must also validate a few claims in the token to prove that it's
valid. Depending on the scenario requirements, the claims validated by an application can vary, but your
application must perform some common claim validations in every scenario.
Access token - A JWT that contains claims that you can use to identify the granted permissions to your
APIs. Access tokens are signed, but they aren't encrypted. Access tokens are used to provide access to
APIs and resource servers. When your API receives an access token, it must validate the signature to
prove that the token is authentic. Your API must also validate a few claims in the token to prove that it is
valid. Depending on the scenario requirements, the claims validated by an application can vary, but your
application must perform some common claim validations in every scenario.
Refresh token - Refresh tokens are used to acquire new ID tokens and access tokens in an OAuth 2.0 flow.
They provide your application with long-term access to resources on behalf of users without requiring
interaction with those users. Refresh tokens are opaque to your application. They are issued by Azure AD
B2C and can be inspected and interpreted only by Azure AD B2C. They are long-lived, but your
application shouldn't be written with the expectation that a refresh token will last for a specific period of
time. Refresh tokens can be invalidated at any moment for a variety of reasons. The only way for your
application to know if a refresh token is valid is to attempt to redeem it by making a token request to
Azure AD B2C. When you redeem a refresh token for a new token, you receive a new refresh token in the
token response. Save the new refresh token. It replaces the refresh token that you previously used in the
request. This action helps guarantee that your refresh tokens remain valid for as long as possible.
Endpoints
A registered application receives tokens and communicates with Azure AD B2C by sending requests to these
endpoints:
https://{tenant}.b2clogin.com/{tenant}.onmicrosoft.com/oauth2/v2.0/authorize
https://{tenant}.b2clogin.com/{tenant}.onmicrosoft.com/oauth2/v2.0/token
Security tokens that your application receives from Azure AD B2C can come from the /authorize or /token
endpoints. When ID tokens are acquired from the /authorize endpoint, it's done using the implicit flow,
which is often used for users signing in to JavaScript-based web applications. When ID tokens are acquired
from the /token endpoint, it's done using the authorization code flow, which keeps the token hidden from
the browser.
Claims
When you use Azure AD B2C, you have fine-grained control over the content of your tokens. You can
configure user flows and custom policies to send certain sets of user data in claims that are required for your
application. These claims can include standard properties such as displayName and emailAddress. Your
applications can use these claims to securely authenticate users and requests.
The claims in ID tokens are not returned in any particular order. New claims can be introduced in ID tokens at
any time. Your application shouldn't break as new claims are introduced. You can also include custom user
attributes in your claims.
The following table lists the claims that you can expect in ID tokens and access tokens issued by Azure AD
B2C.
Trust framework policy tfp b2c_1_signupsignin1 The name of the policy that
was used to acquire the ID
token.
Configuration
The following properties are used to manage lifetimes of security tokens emitted by Azure AD B2C:
Access & ID token lifetimes (minutes) - The lifetime of the OAuth 2.0 bearer token used to gain
access to a protected resource. The default is 60 minutes. The minimum (inclusive) is 5 minutes. The
maximum (inclusive) is 1440 minutes.
Refresh token lifetime (days) - The maximum time period before which a refresh token can be used
to acquire a new access or ID token. The time period also covers acquiring a new refresh token if your
application has been granted the offline_access scope. The default is 14 days. The minimum
(inclusive) is one day. The maximum (inclusive) is 90 days.
Refresh token sliding window lifetime (days) - After this time period elapses the user is forced to
reauthenticate, irrespective of the validity period of the most recent refresh token acquired by the
application. It can only be provided if the switch is set to Bounded. It needs to be greater than or equal
to the Refresh token lifetime (days) value. If the switch is set to Unbounded, you cannot provide a
specific value. The default is 90 days. The minimum (inclusive) is one day. The maximum (inclusive) is
365 days.
The following use cases are enabled using these properties:
Allow a user to stay signed in to a mobile application indefinitely, as long as the user is continually active
on the application. You can set Refresh token sliding window lifetime (days) to Unbounded in your
sign-in user flow.
Meet your industry's security and compliance requirements by setting the appropriate access token
lifetimes.
These settings are not available for password reset user flows.
Compatibility
The following properties are used to manage token compatibility:
Issuer (iss) claim - This property identifies the Azure AD B2C tenant that issued the token. The
default value is https://<domain>/{B2C tenant GUID}/v2.0/ . The value of
https://<domain>/tfp/{B2C tenant GUID}/{Policy ID}/v2.0/ includes IDs for both the Azure AD B2C
tenant and the user flow that was used in the token request. If your application or library needs Azure
AD B2C to be compliant with the OpenID Connect Discovery 1.0 spec, use this value.
Subject (sub) claim - This property identifies the entity for which the token asserts information. The
default value is ObjectID, which populates the sub claim in the token with the object ID of the user.
The value of Not supported is only provided for backward-compatibility. It's recommended that you
switch to ObjectID as soon as you are able to.
Claim representing policy ID - This property identifies the claim type into which the policy name
used in the token request is populated. The default value is tfp . The value of acr is only provided for
backward-compatibility.
Pass-through
When a user journey starts, Azure AD B2C receives an access token from an identity provider. Azure AD B2C
uses that token to retrieve information about the user. You enable a claim in your user flow or define a claim
in your custom policy to pass the token through to the applications that you register in Azure AD B2C. Your
application must be using a v2 user flow to take advantage of passing the token as a claim.
Azure AD B2C currently only supports passing the access token of OAuth 2.0 identity providers, which
include Facebook and Google. For all other identity providers, the claim is returned blank.
Validation
To validate a token, your application should check both the signature and claims of the token. Many open-
source libraries are available for validating JWTs, depending on your preferred language. It's recommended
that you explore those options rather than implement your own validation logic.
Validate signature
A JWT contains three segments, a header, a body, and a signature. The signature segment can be used to
validate the authenticity of the token so that it can be trusted by your application. Azure AD B2C tokens are
signed by using industry-standard asymmetric encryption algorithms, such as RSA 256.
The header of the token contains information about the key and encryption method used to sign the token:
{
"typ": "JWT",
"alg": "RS256",
"kid": "GvnPApfWMdLRi8PDmisFn7bprKg"
}
The value of the alg claim is the algorithm that was used to sign the token. The value of the kid claim is the
public key that was used to sign the token. At any given time, Azure AD B2C can sign a token by using any
one of a set of public-private key pairs. Azure AD B2C rotates the possible set of keys periodically. Your
application should be written to handle those key changes automatically. A reasonable frequency to check for
updates to the public keys used by Azure AD B2C is every 24 hours.
Azure AD B2C has an OpenID Connect metadata endpoint. Using this endpoint, applications can request
information about Azure AD B2C at runtime. This information includes endpoints, token contents, and token
signing keys. Your Azure AD B2C tenant contains a JSON metadata document for each policy. The metadata
document is a JSON object that contains several useful pieces of information. The metadata contains
jwks_uri, which gives the location of the set of public keys that are used to sign tokens. That location is
provided here, but it's best to fetch the location dynamically by using the metadata document and parsing
jwks_uri:
https://contoso.b2clogin.com/contoso.onmicrosoft.com/discovery/v2.0/keys?p=b2c_1_signupsignin1
The JSON document located at this URL contains all the public key information in use at a particular
moment. Your app can use the kid claim in the JWT header to select the public key in the JSON document
that is used to sign a particular token. It can then perform signature validation by using the correct public key
and the indicated algorithm.
The metadata document for the B2C_1_signupsignin1 policy in the contoso.onmicrosoft.com tenant is located
at:
https://contoso.b2clogin.com/contoso.onmicrosoft.com/v2.0/.well-known/openid-configuration?
p=b2c_1_signupsignin1
To determine which policy was used to sign a token (and where to go to request the metadata), you have two
options. First, the policy name is included in the acr claim in the token. You can parse claims out of the body
of the JWT by base-64 decoding the body and deserializing the JSON string that results. The acr claim is
the name of the policy that was used to issue the token. The other option is to encode the policy in the value
of the state parameter when you issue the request, and then decode it to determine which policy was used.
Either method is valid.
A description of how to perform signature validation is outside the scope of this document. Many open-
source libraries are available to help you validate a token.
Validate claims
When your applications or API receives an ID token, it should also perform several checks against the claims
in the ID token. The following claims should be checked:
audience - Verifies that the ID token was intended to be given to your application.
not before and expiration time - Verifies that the ID token hasn't expired.
issuer - Verifies that the token was issued to your application by Azure AD B2C.
nonce - A strategy for token replay attack mitigation.
For a full list of validations your application should perform, refer to the OpenID Connect specification.
Next steps
Learn more about how to use access tokens.
Request an access token in Azure Active Directory
B2C
9/17/2019 • 3 minutes to read • Edit Online
An access token contains claims that you can use in Azure Active Directory B2C (Azure AD B2C ) to identify the
granted permissions to your APIs. When calling a resource server, an access token must be present in the HTTP
request. An access token is denoted as access_token in the responses from Azure AD B2C.
This article shows you how to request an access token for a web application and web API. For more information
about tokens in Azure AD B2C, see the overview of tokens in Azure Active Directory B2C.
NOTE
Web API chains (On-Behalf-Of) is not supported by Azure AD B2C. - Many architectures include a web API that needs
to call another downstream web API, both secured by Azure AD B2C. This scenario is common in clients that have a web API
back end, which in turn calls a another service. This chained web API scenario can be supported by using the OAuth 2.0 JWT
Bearer Credential grant, otherwise known as the On-Behalf-Of flow. However, the On-Behalf-Of flow is not currently
implemented in Azure AD B2C.
Prerequisites
Create a user flow to enable users to sign up and sign in to your application.
If you haven't already done so, add a web API application to your Azure Active Directory B2C tenant.
Scopes
Scopes provide a way to manage permissions to protected resources. When an access token is requested, the
client application needs to specify the desired permissions in the scope parameter of the request. For example, to
specify the Scope Value of read for the API that has the App ID URI of https://contoso.onmicrosoft.com/api ,
the scope would be https://contoso.onmicrosoft.com/api/read .
Scopes are used by the web API to implement scope-based access control. For example, users of the web API
could have both read and write access, or users of the web API might have only read access. To acquire multiple
permissions in the same request, you can add multiple entries in the single scope parameter of the request,
separated by spaces.
The following example shows scopes decoded in a URL:
scope=https%3A%2F%2Fcontoso.onmicrosoft.com%2Fapi%2Fread%20openid%20offline_access
If you request more scopes than what is granted for your client application, the call succeeds if at least one
permission is granted. The scp claim in the resulting access token is populated with only the permissions that were
successfully granted. The OpenID Connect standard specifies several special scope values. The following scopes
represent the permission to access the user’s profile:
openid - Requests an ID token.
offline_access - Requests a refresh token using Auth Code flows.
If the response_type parameter in an /authorize request includes token , the scope parameter must include at
least one resource scope other than openid and offline_access that will be granted. Otherwise, the /authorize
request fails.
Request a token
To request an access token, you need an authorization code. Below is an example of a request to the /authorize
endpoint for an authorization code. Custom domains are not supported for use with access tokens. Use your
tenant-name.onmicrosoft.com domain in the request URL.
In the following example, you replace these values:
<tenant-name> - The name of your Azure AD B2C tenant.
<policy-name> - The name of your custom policy or user flow.
<application-ID> - The application identifier of the web application that you registered to support the user
flow.
<redirect-uri> - The Redirect URI that you entered when you registered the client application.
GET https://<tenant-name>.b2clogin.com/tfp/<tenant-name>.onmicrosoft.com/<policy-name>/oauth2/v2.0/authorize?
client_id=<application-ID>
&nonce=anyRandomValue
&redirect_uri=https://jwt.ms
&scope=https://tenant-name>.onmicrosoft.com/api/read
&response_type=code
The response with the authorization code should be similar to this example:
https://jwt.ms/?code=eyJraWQiOiJjcGltY29yZV8wOTI1MjAxNSIsInZlciI6IjEuMC...
After successfully receiving the authorization code, you can use it to request an access token:
grant_type=authorization_code
&client_id=<application-ID>
&scope=https://<tenant-name>.onmicrosoft.com/api/read
&code=eyJraWQiOiJjcGltY29yZV8wOTI1MjAxNSIsInZlciI6IjEuMC...
&redirect_uri=https://jwt.ms
&client_secret=2hMG2-_:y12n10vwH...
{
"access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6Ilg1ZVhrN...",
"token_type": "Bearer",
"not_before": 1549647431,
"expires_in": 3600,
"expires_on": 1549651031,
"resource": "f2a76e08-93f2-4350-833c-965c02483b11",
"profile_info": "eyJ2ZXIiOiIxLjAiLCJ0aWQiOiJjNjRhNGY3ZC0zMDkxLTRjNzMtYTcyMi1hM2YwNjk0Z..."
}
When using https://jwt.ms to examine the access token that was returned, you should see something similar to the
following example:
{
"typ": "JWT",
"alg": "RS256",
"kid": "X5eXk4xyojNFum1kl2Ytv8dl..."
}.{
"iss": "https://contoso0926tenant.b2clogin.com/c64a4f7d-3091-4c73-a7.../v2.0/",
"exp": 1549651031,
"nbf": 1549647431,
"aud": "f2a76e08-93f2-4350-833c-965...",
"oid": "1558f87f-452b-4757-bcd1-883...",
"sub": "1558f87f-452b-4757-bcd1-883...",
"name": "David",
"tfp": "B2C_1_signupsignin1",
"nonce": "anyRandomValue",
"scp": "read",
"azp": "38307aee-303c-4fff-8087-d8d2...",
"ver": "1.0",
"iat": 1549647431
}.[Signature]
Next steps
Learn about how to configure tokens in Azure AD B2C
User flows in Azure Active Directory B2C
9/17/2019 • 3 minutes to read • Edit Online
The extensible policy framework of Azure Active Directory B2C (Azure AD B2C ) is the core strength
of the service. Policies fully describe identity experiences such as sign-up, sign-in, or profile editing. To
help you set up the most common identity tasks, the Azure AD B2C portal includes predefined,
configurable policies called user flows.
https://contosob2c.b2clogin.com/contosob2c.onmicrosoft.com/oauth2/v2.0/authorize?
client_id=2d4d11a2-f814-46a7-890a-274a72a7309e // Your registered Application ID
&redirect_uri=https%3A%2F%2Flocalhost%3A44321%2F // Your registered Reply URL, url encoded
&response_mode=form_post // 'query', 'form_post' or 'fragment'
&response_type=id_token
&scope=openid
&nonce=dummy
&state=12345 // Any value provided by your application
&p=b2c_1_siup // Your sign-up user flow
https://contosob2c.b2clogin.com/contosob2c.onmicrosoft.com/oauth2/v2.0/authorize?
client_id=2d4d11a2-f814-46a7-890a-274a72a7309e // Your registered Application ID
&redirect_uri=https%3A%2F%2Flocalhost%3A44321%2F // Your registered Reply URL, url encoded
&response_mode=form_post // 'query', 'form_post' or 'fragment'
&response_type=id_token
&scope=openid
&nonce=dummy
&state=12345 // Any value provided by your application
&p=b2c_1_siin // Your sign-in user flow
Next steps
To create the recommended user flows, follow the instructions in Tutorial: Create a user flow.
Custom policies in Azure Active Directory B2C
9/17/2019 • 3 minutes to read • Edit Online
NOTE
In Azure Active Directory B2C, custom policies are designed primarily to address complex scenarios. For most scenarios,
we recommend that you use built-in user flows.
Custom policies are configuration files that define the behavior of your Azure Active Directory B2C (Azure AD
B2C ) tenant. User flows are predefined in the Azure AD B2C portal for the most common identity tasks.
Custom policies can be fully edited by an identity developer to complete many different tasks.
Target users All application developers with or Identity pros, systems integrators,
without identity expertise. consultants, and in-house identity
teams. They are comfortable with
OpenID Connect flows and
understand identity providers and
claims-based authentication.
Configuration method Azure portal with a user-friendly user- Directly editing XML files and then
interface (UI). uploading to the Azure portal.
Token and session management Custom token and multiple session Same
options.
Identity Providers Predefined local or social provider and Standards-based OIDC, OAUTH, and
most OIDC identity providers, such as SAML. Authentication is also possible
federation with Azure Active Directory by using integration with REST APIs.
tenants.
USER FLOWS CUSTOM POLICIES
Identity Tasks Sign-up or sign-in with local or many Complete the same tasks as user flows
social accounts. using custom identity providers or use
custom scopes.
Self-service password reset.
Provision a user account in another
Profile edit. system at the time of registration.
Policy files
These three types of policy files are used:
Base file - contains most of the definitions. It is recommended that you make a minimum number of
changes to this file to help with troubleshooting, and long-term maintenance of your policies.
Extensions file - holds the unique configuration changes for your tenant.
Relying Party (RP ) file - The single task-focused file that is invoked directly by the application or service
(also, known as a Relying Party). Each unique task requires its own RP and depending on branding
requirements, the number might be "total of applications x total number of use cases."
User flows in Azure AD B2C follow the three-file pattern depicted above, but the developer only sees the RP
file, while the Azure portal makes changes in the background to the extensions file.
Next steps
Get started with custom policies
Overview of user accounts in Azure Active Directory
B2C
11/5/2019 • 4 minutes to read • Edit Online
In Azure Active Directory B2C (Azure AD B2C ), there are several types of accounts that can be created. Azure
Active Directory, Active Directory B2B, and Active Directory B2C share in the types of user accounts that can be
used.
The following types of accounts are available:
Work account - A work account can access resources in a tenant, and with an administrator role, can manage
tenants.
Guest account - A guest account can only be a Microsoft account or an Azure Active Directory user that can
be used to access applications or manage tenants.
Consumer account - A consumer account is used by a user of the applications you've registered with Azure
AD B2C. Consumer accounts can be created by:
The user going through a sign-up user flow in an Azure AD B2C application
Using Azure AD Graph API
Using the Azure portal
Work account
A work account is created the same way for all tenants based on Azure AD. To create a work account, you can use
the information in Quickstart: Add new users to Azure Active Directory. A work account is created using the New
user choice in the Azure portal.
When you add a new work account, you need to consider the following configuration settings:
Name and User name - The Name property contains the given and surname of the user. The User name
is the identifier that the user enters to sign in. The user name includes the full domain. The domain name
portion of the user name must either be the initial default domain name your-domain.onmicrosoft.com, or a
verified, non-federated custom domain name such as contoso.com.
Profile - The account is set up with a profile of user data. You have the opportunity to enter a first name,
last name, job title, and department name. You can edit the profile after the account is created.
Groups - Use a group to perform management tasks such as assigning licenses or permissions to a number
of users or devices at once. You can put the new account into an existing group in your tenant.
Directory role - You need to specify the level of access that the user account has to resources in your
tenant. The following permission levels are available:
User - Users can access assigned resources but cannot manage most tenant resources.
Global administrator - Global administrators have full control over all tenant resources.
Limited administrator - Select the administrative role or roles for the user. For more information about
the roles that can be selected, see Assigning administrator roles in Azure Active Directory.
Create a work account
You can use the following information to create a new work account:
Azure portal
Microsoft Graph
Update a user profile
You can use the following information to update the profile of a user:
Azure portal
Microsoft Graph
Reset a password for a user
You can use the following information to reset the password of a user:
Azure portal
Microsoft Graph
Guest user
You can invite external users to your tenant as a guest user. A typical scenario for inviting a guest user to your
Azure AD B2C tenant is to share administration responsibilities. For an example of using a guest account, see
Properties of an Azure Active Directory B2B collaboration user.
When you invite a guest user to your tenant, you provide the email address of the recipient and a message
describing the invitation. The invitation link takes the user to the consent page where the Get Started button is
selected and the review of permissions is accepted. If an inbox isn't attached to the email address, the user can
navigate to the consent page by going to a Microsoft page using the invited credentials. The user is then forced to
redeem the invitation the same way as clicking on the link in the email. For example:
https://myapps.microsoft.com/B2CTENANTNAME .
You can also use the Microsoft Graph API to invite a guest user.
Consumer user
The consumer user can sign in to applications secured by Azure AD B2C, but cannot access Azure resources such
as the Azure portal. The consumer user can use a local account or federated accounts, such as Facebook or Twitter.
A consumer account is created by using a sign-up or sign-in user flow, using the Azure AD Graph API, or by using
the Azure portal.
You can specify the data that is collected when a consumer user account is created by using custom user attributes.
For more information, see Define custom attributes in Azure Active Directory B2C.
You can use the information in the Create consumer user accounts section of Use the Azure AD Graph API to
create an Azure AD B2C consumer account. You can also use the information in the Update consumer user
accounts section in the same article to manage the properties of the account.
Migrate consumer user accounts
You might have a need to migrate existing consumer user accounts from any identity provider to Azure AD B2C.
For more information, see User Migration or Migrate users with social identities.
Tutorial: Register an application in Azure Active
Directory B2C
12/9/2019 • 4 minutes to read • Edit Online
Before your applications can interact with Azure Active Directory B2C (Azure AD B2C ), they must be registered
in a tenant that you manage. This tutorial shows you how to register a web application using the Azure portal.
In this article, you learn how to:
Register a web application
Create a client secret
If you don't have an Azure subscription, create a free account before you begin.
Prerequisites
If you haven't already created your own Azure AD B2C Tenant, create one now. You can use an existing Azure AD
B2C tenant.
Next steps
In this article, you learned how to:
Register a web application
Create a client secret
Next, learn how to create user flows to enable your users to sign up, sign in, and manage their profiles.
Create user flows in Azure Active Directory B2C >
Register a SAML application in Azure AD B2C
12/13/2019 • 10 minutes to read • Edit Online
In this article, you learn how to configure Azure Active Directory B2C (Azure AD B2C ) to act as a Security
Assertion Markup Language (SAML ) identity provider (IdP ) to your applications.
NOTE
This feature is in public preview.
Scenario overview
Organizations that use Azure AD B2C as their customer identity and access management solution might require
interaction with identity providers or applications that are configured to authenticate using the SAML protocol.
Azure AD B2C achieves SAML interoperability in one of two ways:
By acting as an identity provider (IdP ) and achieving single-sign-on (SSO ) with SAML -based service providers
(your applications)
By acting as a service provider (SP ) and interacting with SAML -based identity providers like Salesforce and
ADFS
My application expects a SAML Azure AD B2C acts as the identity This article.
assertion to complete an provider (IdP)
authentication. Azure AD B2C acts as a SAML IdP to
the applications.
My users need single-sign-on with a Azure AD B2C acts as the service Set up sign-in with ADFS as a
SAML-compliant identity provider like provider (SP) SAML IdP using custom policies
ADFS, Salesforce, or Shibboleth. Azure AD B2C acts as a service provider Set up sign-in with a Salesforce
when connecting to the SAML identity SAML provider using custom
provider. It's a federation proxy between policies
your application and the SAML identity
provider.
Prerequisites
Complete the steps in Get started with custom policies in Azure AD B2C. You need the SocialAndLocalAccounts
custom policy from the custom policy starter pack discussed in the article.
Basic understanding of the Security Assertion Markup Language (SAML ) protocol.
A web application configured as a SAML service provider (SP ). For this tutorial, you can use a SAML test
application that we provide.
1. Set up certificates
To build a trust relationship between your service provider and Azure AD B2C, you need to provide X509
certificates and their private keys.
Service provider certificates
Certificate with a private key stored in your Web App. This certificate is used to by your service provider
to sign the SAML request sent to Azure AD B2C. Azure AD B2C reads the public key from the service
provider metadata to validate the signature.
(Optional) Certificate with a private key stored in your Web App. Azure AD B2C reads the public key
from the service provider metadata to encrypt the SAML assertion. The service provider then uses the
private key to decrypt the assertion.
Azure AD B2C certificates
Certificate with a private key in Azure AD B2C. This certificate is used by Azure AD B2C to sign the
SAML response sent to your service provider. Your service provider reads the Azure AD B2C metadata
public key to validate the signature of the SAML response.
You can use a certificate issued by a public certificate authority or, for this tutorial, a self-signed certificate.
1.1 Prepare a self-signed certificate
If you don't already have a certificate, you can use a self-signed certificate for this tutorial. On Windows, you can
use PowerShell's New -SelfSignedCertificate cmdlet to generate a certificate.
1. Execute this PowerShell command to generate a self-signed certificate. Modify the -Subject argument as
appropriate for your application and Azure AD B2C tenant name. You can also adjust the -NotAfter date to
specify a different expiration for the certificate.
New-SelfSignedCertificate `
-KeyExportPolicy Exportable `
-Subject "CN=yourappname.yourtenant.onmicrosoft.com" `
-KeyAlgorithm RSA `
-KeyLength 2048 `
-KeyUsage DigitalSignature `
-NotAfter (Get-Date).AddMonths(12) `
-CertStoreLocation "Cert:\CurrentUser\My"
2. Open Manage user certificates > Current User > Personal > Certificates >
yourappname.yourtenant.onmicrosoft.com
3. Select the certificate > Action > All Tasks > Export
4. Select Yes > Next > Yes, export the private key > Next
5. Accept the defaults for Export File Format
6. Provide a password for the certificate
1.2 Upload the certificate
Next, upload the SAML assertion and response signing certificate to Azure AD B2C.
1. Sign in to the Azure portal and browse to your Azure AD B2C tenant.
2. Select Settings > Identity Experience Framework > Policy Keys.
3. Select Add, and then select Options > Upload.
4. Enter a Name, for example SamlIdpCert. The prefix B2C_1A_ is automatically added to the name of your key.
5. Upload your certificate using the upload file control.
6. Enter the certificate's password.
7. Select Create.
8. Verify that the key appears as expected. For example, B2C_1A_SamlIdpCert.
<!-- Session management technical profile for SAML based tokens -->
<TechnicalProfile Id="SM-Saml">
<DisplayName>Session Management Provider</DisplayName>
<Protocol Name="Proprietary" Handler="Web.TPEngine.SSO.SamlSSOSessionProvider, Web.TPEngine,
Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"/>
</TechnicalProfile>
</TechnicalProfiles>
</ClaimsProvider>
<TrustFrameworkPolicy
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns="http://schemas.microsoft.com/online/cpim/schemas/2013/06"
PolicySchemaVersion="0.3.0.0"
TenantId="tenant-name.onmicrosoft.com"
PolicyId="B2C_1A_signup_signin_saml"
PublicPolicyUri="http://tenant-name.onmicrosoft.com/B2C_1A_signup_signin_saml">
4. Add following XML snippet just before the <RelyingParty> element. This XML overwrites orchestration step
number 7 of the SignUpOrSignIn user journey. If you customized your user journey by adding or removing
orchestration steps, make sure the number (in the order element) is aligned with the one specified in the
user journey for the token issuer step.
<UserJourneys>
<UserJourney Id="SignUpOrSignIn">
<OrchestrationSteps>
<OrchestrationStep Order="7" Type="SendClaims"
CpimIssuerTechnicalProfileReferenceId="Saml2AssertionIssuer"/>
</OrchestrationSteps>
</UserJourney>
</UserJourneys>
5. Replace the entire <TechnicalProfile> element in the <RelyingParty> element with the following technical
profile XML.
<TechnicalProfile Id="PolicyProfile">
<DisplayName>PolicyProfile</DisplayName>
<Protocol Name="SAML2"/>
<OutputClaims>
<OutputClaim ClaimTypeReferenceId="displayName" />
<OutputClaim ClaimTypeReferenceId="givenName" />
<OutputClaim ClaimTypeReferenceId="surname" />
<OutputClaim ClaimTypeReferenceId="email" DefaultValue="" />
<OutputClaim ClaimTypeReferenceId="identityProvider" DefaultValue="" />
<OutputClaim ClaimTypeReferenceId="objectId" PartnerClaimType="objectId"/>
</OutputClaims>
<SubjectNamingInfo ClaimType="objectId" ExcludeAsClaim="true"/>
</TechnicalProfile>
Your final relying party policy file should look like the following:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<TrustFrameworkPolicy
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns="http://schemas.microsoft.com/online/cpim/schemas/2013/06"
PolicySchemaVersion="0.3.0.0"
TenantId="contoso.onmicrosoft.com"
PolicyId="B2C_1A_signup_signin_saml"
PublicPolicyUri="http://contoso.onmicrosoft.com/B2C_1A_signup_signin_saml">
<BasePolicy>
<TenantId>contoso.onmicrosoft.com</TenantId>
<PolicyId>B2C_1A_TrustFrameworkExtensions</PolicyId>
</BasePolicy>
<UserJourneys>
<UserJourney Id="SignUpOrSignIn">
<OrchestrationSteps>
<OrchestrationStep Order="7" Type="SendClaims"
CpimIssuerTechnicalProfileReferenceId="Saml2AssertionIssuer"/>
</OrchestrationSteps>
</UserJourney>
</UserJourneys>
<RelyingParty>
<DefaultUserJourney ReferenceId="SignUpOrSignIn" />
<TechnicalProfile Id="PolicyProfile">
<DisplayName>PolicyProfile</DisplayName>
<Protocol Name="SAML2"/>
<OutputClaims>
<OutputClaim ClaimTypeReferenceId="displayName" />
<OutputClaim ClaimTypeReferenceId="givenName" />
<OutputClaim ClaimTypeReferenceId="surname" />
<OutputClaim ClaimTypeReferenceId="email" DefaultValue="" />
<OutputClaim ClaimTypeReferenceId="identityProvider" DefaultValue="" />
<OutputClaim ClaimTypeReferenceId="objectId" PartnerClaimType="objectId"/>
</OutputClaims>
<SubjectNamingInfo ClaimType="objectId" ExcludeAsClaim="true"/>
</TechnicalProfile>
</RelyingParty>
</TrustFrameworkPolicy>
Your custom policy and Azure AD B2C tenant are now ready. Next, create an application registration in Azure AD
B2C.
"samlMetadataUrl":"https://samltestapp2.azurewebsites.net/Metadata",
ReplyUrlWithType (Optional)
If you do not provide a metadata URI, you can explicitly specify the reply URL. This optional property represents
the AssertionConsumerServiceUrl ( SingleSignOnService URL in the service provider metadata) and the
BindingType is assumed to be HTTP POST .
If you choose to configure the reply URL and logout URL in the application manifest without using the service
provider metadata, Azure AD B2C will not validate the SAML request signature, nor encrypt the SAML response.
For this tutorial, in which you use the SAML test application, set the url property of replyUrlsWithType to the
value shown in the following JSON snippet.
"replyUrlsWithType":[
{
"url":"https://samltestapp2.azurewebsites.net/SP/AssertionConsumer",
"type":"Web"
}
],
LogoutUrl (Optional)
This optional property represents the Logout URL ( SingleLogoutService URL in the relying party metadata), and
the BindingType for this is assumed to be HttpDirect .
For this tutorial which uses the SAML test application, leave logoutUrl set to
https://samltestapp2.azurewebsites.net/logout :
"logoutUrl": "https://samltestapp2.azurewebsites.net/logout",
Issuer: https://tenant-name.onmicrosoft.com/policy-name
Login Url/SAML endpoint/SAML Url: Check the value in the metadata file
Certificate: This is B2C_1A_SamlIdpCert, but without the private key. To get the public key of the certificate:
1. Go to the metadata URL specified above.
2. Copy the value in the <X509Certificate> element.
3. Paste it into a text file.
4. Save the text file as a .cer file.
5.1 Test with the SAML Test App (optional)
To complete this tutorial using our SAML Test Application:
Update the tenant name
Update policy name, for example B2C_1A_signup_signin_saml
Specify this issuer URI: https://contoso.onmicrosoft.com/app-name
Select Login and you should be presented with an end user sign-in screen. Upon sign-in, a SAML assertion is
issued back to the sample application.
Sample policy
We provide a complete sample policy that you can use for testing with the SAML Test App.
1. Download the SAML -SP -initiated login sample policy
2. Update TenantId to match your tenant name, for example contoso.b2clogin.com
3. Keep the policy name of B2C_1A_SAML2_signup_signin
Register web API resources in your tenant so that they can accept and respond to requests by client applications
that present an access token. This article shows you how to register a web API in Azure Active Directory B2C
(Azure AD B2C ).
To register an application in your Azure AD B2C tenant, you can use the current Applications experience, or our
new unified App registrations (Preview) experience. Learn more about the new experience.
Applications
App registrations (Preview )
1. Sign in to the Azure portal.
2. Make sure you're using the directory that contains your Azure AD B2C tenant. Select the Directory +
subscription filter in the top menu and choose the directory that contains your tenant.
3. Choose All services in the top-left corner of the Azure portal, and then search for and select Azure AD B2C.
4. Select Applications, and then select Add.
5. Enter a name for the application. For example, webapi1.
6. For Include web app/ web API and Allow implicit flow, select Yes.
7. For Reply URL, enter an endpoint where Azure AD B2C should return any tokens that your application
requests. In your production application, you might set the reply URL to a value such as
https://localhost:44332 . For testing purposes, set the reply URL to https://jwt.ms .
8. For App ID URI, enter the identifier used for your web API. The full identifier URI including the domain is
generated for you. For example, https://contosotenant.onmicrosoft.com/api .
9. Click Create.
10. On the properties page, record the application ID that you'll use when you configure the web application.
Configure scopes
Scopes provide a way to govern access to protected resources. Scopes are used by the web API to implement
scope-based access control. For example, users of the web API could have both read and write access, or users of
the web API might have only read access. In this tutorial, you use scopes to define read and write permissions for
the web API.
Applications
App registrations (Preview )
1. Select Applications.
2. Select the webapi1 application to open its Properties page.
3. Select Published scopes. Published scopes can be used to grant a client application certain permissions to the
web API.
4. For SCOPE, enter demo.read , and for DESCRIPTION, enter Read access to the web API .
5. For SCOPE, enter demo.write , and for DESCRIPTION, enter Write access to the web API .
6. Select Save.
Grant permissions
To call a protected web API from an application, you need to grant your application permissions to the API. For
example, in Tutorial: Register an application in Azure Active Directory B2C, a web application named webapp1 is
registered in Azure AD B2C. You can use this application to call the web API.
Applications
App registrations (Preview )
1. Select Applications, and then select the web application that should have access to the API. For example,
webapp1.
2. Select API access, and then select Add.
3. In the Select API dropdown, select the API to which web application should be granted access. For example,
webapi1.
4. In the Select Scopes dropdown, select the scopes that you defined earlier. For example, demo.read and
demo.write.
5. Select OK.
Your application is registered to call the protected web API. A user authenticates with Azure AD B2C to use the
application. The application obtains an authorization grant from Azure AD B2C to access the protected web API.
Add a native client application to your Azure Active
Directory B2C tenant
11/4/2019 • 2 minutes to read • Edit Online
Native client resources need to be registered in your tenant before your application can communicate with Azure
Active Directory B2C.
To register an application in your Azure AD B2C tenant, you can use the current Applications experience, or our
new unified App registrations (Preview) experience. Learn more about the new experience.
Applications
App registrations (Preview )
1. Sign in to the Azure portal.
2. Select the Directory + subscription filter in the top menu, and then select the directory that contains your
Azure AD B2C tenant.
3. In the left menu, select Azure AD B2C. Or, select All services and search for and select Azure AD B2C.
4. Select Applications, and then select Add.
5. Enter a name for the application. For example, nativeapp1.
6. For Native client, select Yes.
7. Enter a Custom Redirect URI with a unique scheme. For example,
com.onmicrosoft.contosob2c.exampleapp://oauth/redirect . There are two important considerations when
choosing a redirect URI:
Unique: The scheme of the redirect URI must be unique for every application. In the example
com.onmicrosoft.contosob2c.exampleapp://oauth/redirect , com.onmicrosoft.contosob2c.exampleapp is the
scheme. This pattern should be followed. If two applications share the same scheme, the user is given a
choice to choose an application. If the user chooses incorrectly, the sign-in fails.
Complete: The redirect URI must have a both a scheme and a path. The path must contain at least one
forward slash after the domain. For example, //oauth/ works while //oauth fails. Don't include special
characters in the URI, for example, underscores.
8. Select Create.
Azure AD B2C: Sign-in using an iOS application
12/9/2019 • 6 minutes to read • Edit Online
The Microsoft identity platform uses open standards such as OAuth2 and OpenID Connect. Using an open
standard protocol offers more developer choice when selecting a library to integrate with our services. We've
provided this walkthrough and others like it to aid developers with writing applications that connect to the
Microsoft Identity platform. Most libraries that implement the RFC6749 OAuth2 spec are able to connect to the
Microsoft Identity platform.
WARNING
Microsoft does not provide fixes for third-party libraries and has not done a review of those libraries. This sample is using a
third-party library called AppAuth that has been tested for compatibility in basic scenarios with the Azure AD B2C. Issues and
feature requests should be directed to the library's open-source project. For more information, see this article.
If you're new to OAuth2 or OpenID Connect, much of this sample configuration may not make much sense to you.
We recommend you look at a brief overview of the protocol we've documented here.
Create an application
Next, register an application in your Azure AD B2C tenant. This gives Azure AD the information it needs to
communicate securely with your app.
To register an application in your Azure AD B2C tenant, you can use the current Applications experience, or our
new unified App registrations (Preview) experience. Learn more about the new experience.
Applications
App registrations (Preview )
1. Sign in to the Azure portal.
2. Select the Directory + subscription filter in the top menu, and then select the directory that contains your
Azure AD B2C tenant.
3. In the left menu, select Azure AD B2C. Or, select All services and search for and select Azure AD B2C.
4. Select Applications, and then select Add.
5. Enter a name for the application. For example, nativeapp1.
6. For Native client, select Yes.
7. Enter a Custom Redirect URI with a unique scheme. For example,
com.onmicrosoft.contosob2c.exampleapp://oauth/redirect . There are two important considerations when
choosing a redirect URI:
Unique: The scheme of the redirect URI must be unique for every application. In the example
com.onmicrosoft.contosob2c.exampleapp://oauth/redirect , com.onmicrosoft.contosob2c.exampleapp is the
scheme. This pattern should be followed. If two applications share the same scheme, the user is given a
choice to choose an application. If the user chooses incorrectly, the sign-in fails.
Complete: The redirect URI must have a both a scheme and a path. The path must contain at least one
forward slash after the domain. For example, //oauth/ works while //oauth fails. Don't include special
characters in the URI, for example, underscores.
8. Select Create.
Record the Application (client) ID for use in a later step.
Also record your custom redirect URI for use in a later step. For example,
com.onmicrosoft.contosob2c.exampleapp://oauth/redirect .
Configuration
You can configure communication with Azure AD B2C by specifying both the authorization endpoint and token
endpoint URIs. To generate these URIs, you need the following information:
Tenant ID (for example, contoso.onmicrosoft.com)
User flow name (for example, B2C_1_SignUpIn)
The token endpoint URI can be generated by replacing the Tenant_ID and the Policy_Name in the following URL:
The authorization endpoint URI can be generated by replacing the Tenant_ID and the Policy_Name in the following
URL:
static NSString *const authorizationEndpoint =
@"https://<Tenant_name>.b2clogin.com/te/<Tenant_ID>/<Policy_Name>/oauth2/v2.0/authorize";
OIDServiceConfiguration *configuration =
[[OIDServiceConfiguration alloc] initWithAuthorizationEndpoint:authorizationEndpoint
tokenEndpoint:tokenEndpoint];
// now we are ready to perform the auth request...
Authorizing
After configuring or retrieving an authorization service configuration, an authorization request can be constructed.
To create the request, you need the following information:
Client ID (APPLICATION ID ) that you recorded earlier. For example, 00000000-0000-0000-0000-000000000000 .
Custom Redirect URI that you recorded earlier. For example,
com.onmicrosoft.contosob2c.exampleapp://oauth/redirect .
Both items should have been saved when you were registering your app.
OIDAuthorizationRequest *request =
[[OIDAuthorizationRequest alloc] initWithConfiguration:configuration
clientId:kClientId
scopes:@[OIDScopeOpenID, OIDScopeProfile]
redirectURL:[NSURL URLWithString:kRedirectUri]
responseType:OIDResponseTypeCode
additionalParameters:nil];
To set up your application to handle the redirect to the URI with the custom scheme, you need to update the list of
'URL Schemes' in your Info.pList:
Open Info.pList.
Hover over a row like 'Bundle OS Type Code' and click the + symbol.
Rename the new row 'URL types'.
Click the arrow to the left of 'URL types' to open the tree.
Click the arrow to the left of 'Item 0' to open the tree.
Rename first item underneath Item 0 to 'URL Schemes'.
Click the arrow to the left of 'URL Schemes' to open the tree.
In the 'Value' column, there is a blank field to the left of 'Item 0' underneath 'URL Schemes'. Set the value to
your application's unique scheme. The value must match the scheme used in redirectURL when creating the
OIDAuthorizationRequest object. In the sample, the scheme 'com.onmicrosoft.fabrikamb2c.exampleapp' is used.
Refer to the AppAuth guide on how to complete the rest of the process. If you need to quickly get started with a
working app, check out the sample. Follow the steps in the README.md to enter your own Azure AD B2C
configuration.
We are always open to feedback and suggestions! If you have any difficulties with this article, or have
recommendations for improving this content, we would appreciate your feedback at the bottom of the page. For
feature requests, add them to UserVoice.
Sign-in using an Android application in Azure Active
Directory B2C
12/9/2019 • 6 minutes to read • Edit Online
The Microsoft identity platform uses open standards such as OAuth2 and OpenID Connect. These standards allow
you to leverage any library you wish to integrate with Azure Active Directory B2C. To help you use other libraries,
you can use a walkthrough like this one to demonstrate how to configure 3rd party libraries to connect to the
Microsoft identity platform. Most libraries that implement the RFC6749 OAuth2 spec can connect to the Microsoft
Identity platform.
WARNING
Microsoft does not provide fixes for 3rd party libraries and has not done a review of those libraries. This sample is using a 3rd
party library called AppAuth that has been tested for compatibility in basic scenarios with the Azure AD B2C. Issues and
feature requests should be directed to the library's open-source project. Please see this article for more information.
If you're new to OAuth2 or OpenID Connect much of this sample configuration may not make much sense to you.
We recommend you look at a brief overview of the protocol we've documented here.
Create an application
Next, register an application in your Azure AD B2C tenant. This gives Azure AD the information it needs to
communicate securely with your app.
To register an application in your Azure AD B2C tenant, you can use the current Applications experience, or our
new unified App registrations (Preview) experience. Learn more about the new experience.
Applications
App registrations (Preview )
1. Sign in to the Azure portal.
2. Select the Directory + subscription filter in the top menu, and then select the directory that contains your
Azure AD B2C tenant.
3. In the left menu, select Azure AD B2C. Or, select All services and search for and select Azure AD B2C.
4. Select Applications, and then select Add.
5. Enter a name for the application. For example, nativeapp1.
6. For Native client, select Yes.
7. Enter a Custom Redirect URI with a unique scheme. For example,
com.onmicrosoft.contosob2c.exampleapp://oauth/redirect . There are two important considerations when
choosing a redirect URI:
Unique: The scheme of the redirect URI must be unique for every application. In the example
com.onmicrosoft.contosob2c.exampleapp://oauth/redirect , com.onmicrosoft.contosob2c.exampleapp is the
scheme. This pattern should be followed. If two applications share the same scheme, the user is given a
choice to choose an application. If the user chooses incorrectly, the sign-in fails.
Complete: The redirect URI must have a both a scheme and a path. The path must contain at least one
forward slash after the domain. For example, //oauth/ works while //oauth fails. Don't include special
characters in the URI, for example, underscores.
8. Select Create.
Record the Application (client) ID for use in a later step.
Also record your custom redirect URI for use in a later step. For example,
com.onmicrosoft.contosob2c.exampleapp://oauth/redirect .
Configuration
You can configure communication with Azure AD B2C by either specifying the discovery URI or by specifying both
the authorization endpoint and token endpoint URIs. In either case, you will need the following information:
Tenant ID (e.g. contoso.onmicrosoft.com)
User flow name (e.g. B2C_1_SignUpIn)
If you choose to automatically discover the authorization and token endpoint URIs, you will need to fetch
information from the discovery URI. The discovery URI can be generated by replacing the Tenant_ID and the
Policy_Name in the following URL:
AuthorizationServiceConfiguration.fetchFromIssuer(
issuerUri,
new RetrieveConfigurationCallback() {
@Override public void onFetchConfigurationCompleted(
@Nullable AuthorizationServiceConfiguration serviceConfiguration,
@Nullable AuthorizationException ex) {
if (ex != null) {
Log.w(TAG, "Failed to retrieve configuration for " + issuerUri, ex);
} else {
// service configuration retrieved, proceed to authorization...
}
}
});
Instead of using discovery to obtain the authorization and token endpoint URIs, you can also specify them explicitly
by replacing the Tenant_ID and the Policy_Name in the URL's below:
AuthorizationServiceConfiguration config =
new AuthorizationServiceConfiguration(name, mAuthEndpoint, mTokenEndpoint);
Authorizing
After configuring or retrieving an authorization service configuration, an authorization request can be constructed.
To create the request, you will need the following information:
Client ID (APPLICATION ID ) that you recorded earlier. For example, 00000000-0000-0000-0000-000000000000 .
Custom Redirect URI that you recorded earlier. For example,
com.onmicrosoft.contosob2c.exampleapp://oauth/redirect .
Both items should have been saved when you were registering your app.
Please refer to the AppAuth guide on how to complete the rest of the process. If you need to quickly get started
with a working app, check out our sample. Follow the steps in the README.md to enter your own Azure AD B2C
configuration.
Tutorial: Create user flows in Azure Active Directory
B2C
9/17/2019 • 4 minutes to read • Edit Online
In your applications you may have user flows that enable users to sign up, sign in, or manage their profile. You
can create multiple user flows of different types in your Azure Active Directory B2C (Azure AD B2C ) tenant and
use them in your applications as needed. User flows can be reused across applications.
In this article, you learn how to:
Create a sign-up and sign-in user flow
Create a profile editing user flow
Create a password reset user flow
This tutorial shows you how to create some recommended user flows by using the Azure portal. If you're
looking for information about how to set up a resource owner password credentials (ROPC ) flow in your
application, see Configure the resource owner password credentials flow in Azure AD B2C.
If you don't have an Azure subscription, create a free account before you begin.
Prerequisites
Register your applications that are part of the user flows you want to create.
5. On the Recommended tab, select the Sign up and sign in user flow.
6. Enter a Name for the user flow. For example, signupsignin1.
7. For Identity providers, select Email signup.
8. For User attributes and claims, choose the claims and attributes that you want to collect and send from
the user during sign-up. For example, select Show more, and then choose attributes and claims for
Country/Region, Display Name, and Postal Code. Click OK.
9. Click Create to add the user flow. A prefix of B2C_1 is automatically appended to the name.
Test the user flow
1. Select the user flow you created to open its overview page, then select Run user flow.
2. For Application, select the web application named webapp1 that you previously registered. The Reply
URL should show https://jwt.ms .
3. Click Run user flow, and then select Sign up now.
4. Enter a valid email address, click Send verification code, enter the verification code that you receive,
then select Verify code.
5. Enter a new password and confirm the password.
6. Select your country and region, enter the name that you want displayed, enter a postal code, and then
click Create. The token is returned to https://jwt.ms and should be displayed to you.
7. You can now run the user flow again and you should be able to sign in with the account that you created.
The returned token includes the claims that you selected of country/region, name, and postal code.
Next steps
In this article, you learned how to:
Create a sign-up and sign-in user flow
Create a profile editing user flow
Create a password reset user flow
Next, learn about adding identity providers to your applications to enable user sign-in with providers like Azure
AD, Amazon, Facebook, GitHub, LinkedIn, Microsoft, or Twitter.
Add identity providers to your applications >
Configure the resource owner password credentials
flow in Azure AD B2C
12/9/2019 • 4 minutes to read • Edit Online
The resource owner password credentials (ROPC ) flow is an OAuth standard authentication flow where the
application, also known as the relying party, exchanges valid credentials such as userid and password for an ID
token, access token, and a refresh token.
NOTE
This feature is in public preview.
In Azure Active Directory B2C (Azure AD B2C ), the following options are supported:
Native Client: User interaction during authentication happens when code runs on a user-side device. The
device can be a mobile application that's running in a native operating system, such as Android and iOS.
Public client flow: Only user credentials, gathered by an application, are sent in the API call. The credentials of
the application are not sent.
Add new claims: The ID token contents can be changed to add new claims.
The following flows are not supported:
Server-to-server: The identity protection system needs a reliable IP address gathered from the caller (the
native client) as part of the interaction. In a server-side API call, only the server’s IP address is used. If a
dynamic threshold of failed authentications is exceeded, the identity protection system may identify a repeated
IP address as an attacker.
Confidential client flow: The application client ID is validated, but the application secret is not validated.
KEY VALUE
username leadiocl@outlook.com
password Passxword1
grant_type password
client_id <bef2222d56-552f-4a5b-b90a-1988a7d634c3>
Client_id is the value that you previously noted as the application ID. Offline_access is optional if you want to
receive a refresh token. The username and password that you use must be credentials from an existing user in
your Azure AD B2C tenant.
The actual POST request looks like the following:
POST /yourtenant.onmicrosoft.com/oauth2/v2.0/token?p=B2C_1_ROPC_Auth HTTP/1.1
Host: yourtenant.b2clogin.com
Content-Type: application/x-www-form-urlencoded
username=leadiocl%40trashmail.ws&password=Passxword1&grant_type=password&scope=openid+bef22d56-552f-4a5b-b90a-
1988a7d634ce+offline_access&client_id=bef22d56-552f-4a5b-b90a-1988a7d634ce&response_type=token+id_token
{
"access_token":
"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6Ik9YQjNhdTNScWhUQWN6R0RWZDM5djNpTmlyTWhqN2wxMjIySnh6TmgwRlkifQ.ey
Jpc3MiOiJodHRwczovL3RlLmNwaW0ud2luZG93cy5uZXQvZjA2YzJmZTgtNzA5Zi00MDMwLTg1ZGMtMzhhNGJmZDllODJkL3YyLjAvIiwiZXhw
IjoxNTEzMTMwMDc4LCJuYmYiOjE1MTMxMjY0NzgsImF1ZCI6ImJlZjIyZDU2LTU1MmYtNGE1Yi1iOTBhLTE5ODhhN2Q2MzRjZSIsIm9pZCI6Ij
NjM2I5NjljLThjNDktNGUxMS1hNGVmLWZkYjJmMzkyZjA0OSIsInN1YiI6Ik5vdCBzdXBwb3J0ZWQgY3VycmVudGx5LiBVc2Ugb2lkIGNsYWlt
LiIsImF6cCI6ImJlZjIyZDU2LTU1MmYtNGE1Yi1iOTBhLTE5ODhhN2Q2MzRjZSIsInZlciI6IjEuMCIsImlhdCI6MTUxMzEyNjQ3OH0.MSEThY
ZxCS4SevBw3-3ecnVLUkucFkehH-gH-P7SFcJ-
MhsBeQEpMF1Rzu_R9kUqV3qEWKAPYCNdZ3_P4Dd3a63iG6m9TnO1Vt5SKTETuhVx3Xl5LYeA1i3Slt9Y7LIicn59hGKRZ8ddrQzkqj69j723oo
y01amrXvF6zNOudh0acseszt7fbzzofyagKPerxaeTH0NgyOinLwXu0eNj_6RtF9gBfgwVidRy9OzXUJnqm1GdrS61XUqiIUtv4H04jYxDem7e
k6E4jsH809uSXT0iD5_4C5bDHrpO1N6pXSasmVR9GM1XgfXA_IRLFU4Nd26CzGl1NjbhLnvli2qY4A",
"token_type": "Bearer",
"expires_in": "3600",
"refresh_token":
"eyJraWQiOiJacW9pQlp2TW5pYVc2MUY0TnlfR3REVk1EVFBLbUJLb0FUcWQ1ZWFja1hBIiwidmVyIjoiMS4wIiwiemlwIjoiRGVmbGF0ZSIsI
nNlciI6IjEuMCJ9.aJ_2UW14dh4saWTQ0jLJ7ByQs5JzIeW_AU9Q_RVFgrrnYiPhikEc68ilvWWo8B20KTRB_s7oy_Eoh5LACsqU6Oz0Mjnh0-
DxgrMblUOTAQ9dbfAT5WoLZiCBJIz4YT5OUA_RAGjhBUkqGwdWEumDExQnXIjRSeaUBmWCQHPPguV1_5wSj8aW2zIzYIMbofvpjwIATlbIZwJ7
ufnLypRuq_MDbZhJkegDw10KI4MHJlJ40Ip8mCOe0XeJIDpfefiJ6WQpUq4zl06NO7j8kvDoVq9WALJIao7LYk_x9UIT-
3d0W0eDBHGSRcNgtMYpymaN9ltx6djcEesXNn4CFnWG3g.y6KKeA9EcsW9zW-
g.TrTSgn4WBt18gezegxihBla9SLSTC3YfDROQsL9K4yX4400FKlTlf-2l9CnpGTEdWXVi7sIMHCl8S4oUiXd-
rvY2mn_NfDrbbVJfgKp1j7Nnq9FFyeJEFcP_FtUXgsNTG9iwfzWox04B1d845qNRWiS9N8BhAAAIdz5N0ChHuOxsVOC0Y_Ly3DNe-
JQyXcq964M6-jp3cgi4UqMxT837L6pLY5Ih_iPsSfyHzstsFeqyUIktnzt1MpTlyW-_GDyFK1S-
SyV8PPQ7phgFouw2jho1iboHX70RlDGYyVmP1CfQzKE_zWxj3rgaCZvYMWN8fUenoiatzhvWkUM7dhqKGjofPeL8rOMkhl6afLLjObzhUg3PZF
cMR6guLjQdEwQFufWxGjfpvaHycZSKeWu6-
7dF8Hy_nyMLLdBpUkdrXPob_5gRiaH72KvncSIFvJLqhY3NgXO05Fy87PORjggXwYkhWh4FgQZBIYD6h0CSk2nfFjR9uD9EKiBBWSBZj814S_J
dw6HESFtn91thpvU3hi3qNOi1m41gg1vt5Kh35A5AyDY1J7a9i_lN4B7e_pknXlVX6Z-
Z2BYZvwAU7KLKsy5a99p9FX0lg6QweDzhukXrB4wgfKvVRTo.mjk92wMk-zUSrzuuuXPVeg",
"id_token":
"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6Ik9YQjNhdTNScWhUQWN6R0RWZDM5djNpTmlyTWhqN2wxMjIySnh6TmgwRlkifQ.ey
JleHAiOjE1MTMxMzAwNzgsIm5iZiI6MTUxMzEyNjQ3OCwidmVyIjoiMS4wIiwiaXNzIjoiaHR0cHM6Ly90ZS5jcGltLndpbmRvd3MubmV0L2Yw
NmMyZmU4LTcwOWYtNDAzMC04NWRjLTM4YTRiZmQ5ZTgyZC92Mi4wLyIsInN1YiI6Ik5vdCBzdXBwb3J0ZWQgY3VycmVudGx5LiBVc2Ugb2lkIG
NsYWltLiIsImF1ZCI6ImJlZjIyZDU2LTU1MmYtNGE1Yi1iOTBhLTE5ODhhN2Q2MzRjZSIsImFjciI6ImIyY18xYV9yZXNvdXJjZW93bmVydjIi
LCJpYXQiOjE1MTMxMjY0NzgsImF1dGhfdGltZSI6MTUxMzEyNjQ3OCwib2lkIjoiM2MzYjk2OWMtOGM0OS00ZTExLWE0ZWYtZmRiMmYzOTJmMD
Q5IiwiYXRfaGFzaCI6Ikd6QUNCTVJtcklwYm9OdkFtNHhMWEEifQ.iAJg13cgySsdH3cmoEPGZB_g-
4O8KWvGr6W5VzRXtkrlLoKB1pl4hL6f_0xOrxnQwj2sUgW-wjsCVzMc_dkHSwd9QFZ4EYJEJbi1LMGk2lW-PgjsbwHPDU1mz-
SR1PeqqJgvOqrzXo0YHXr-e07M4v4Tko-i_OYcrdJzj4Bkv7ZZilsSj62lNig4HkxTIWi5Ec2gD79bPKzgCtIww1KRnwmrlnCOrMFYNj-
0T3lTDcXAQog63MOacf7OuRVUC5k_IdseigeMSscrYrNrH28s3r0JoqDhNUTewuw1jx0X6gdqQWZKOLJ7OF_EJMP-
BkRTixBGK5eW2YeUUEVQxsFlUg"
}
KEY VALUE
grant_type refresh_token
response_type id_token
KEY VALUE
client_id <bef2222d56-552f-4a5b-b90a-1988a7d634c3>
resource <bef2222d56-552f-4a5b-b90a-1988a7d634c3>
refresh_token eyJraWQiOiJacW9pQlp2TW5pYVc2MUY0TnlfR3...
Client_id and resource are the values that you previously noted as the application ID. Refresh_token is the token
that you received in the authentication call mentioned previously.
A successful response looks like the following example:
{
"access_token":
"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6Ilg1ZVhrNHh5b2pORnVtMWtsMll0djhkbE5QNC1jNTdkTzZRR1RWQndhTmsifQ.ey
Jpc3MiOiJodHRwczovL2xvZ2luLm1pY3Jvc29mdG9ubGluZS5jb20vNTE2ZmMwNjUtZmYzNi00YjkzLWFhNWEtZDZlZWRhN2NiYWM4L3YyLjAv
IiwiZXhwIjoxNTMzNjc2NTkwLCJuYmYiOjE1MzM2NzI5OTAsImF1ZCI6IjljNTA2MThjLWY5NTEtNDlhNS1iZmU1LWQ3ODA4NTEyMWMzYSIsIm
lkcCI6IkxvY2FsQWNjb3VudCIsInN1YiI6ImJmZDgwODBjLTBjNDAtNDNjYS05ZTI3LTUyZTAyNzIyNWYyMSIsIm5hbWUiOiJEYXZpZE11Iiwi
ZW1haWxzIjpbImRhdmlkd20xMDMwQGhvdG1haWwuY29tIl0sInRmcCI6IkIyQ18xX1JPUENfQXV0aCIsImF6cCI6IjljNTA2MThjLWY5NTEtND
lhNS1iZmU1LWQ3ODA4NTEyMWMzYSIsInZlciI6IjEuMCIsImlhdCI6MTUzMzY3Mjk5MH0.RULWeBR8--s5cCGG6XOi8m-
AGyCaASx9W5B3tNUQjbVkHnGdo2_OUrnVoOZ1PTcrc1b0PQM2kVWi7NpYn57ifnqL_feTJPDbj9FJ8BmyxULdoECWxSM6KHsOPWZOIg5y1lNwN
_IQ2HNF6UaDyYf1ZIM-jHr-uSfUnQXyWRnGDwNKX7TQbFmFk4oFMbPxTE7ioWAmxSnroiiB4__P9D0rUM1vf_qfzemf2ErIWSF9rGtCNBG-
BvJlr3ZMCxIhRiIWNM2bVY0i3Nprzj0V8_FM6q8U19bvg9yDEzUcbe_1PMqzP3IrXW9N1XvQHupsOj8Keb7SmpgY1GG091X6wBCypw",
"id_token":
"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6Ilg1ZVhrNHh5b2pORnVtMWtsMll0djhkbE5QNC1jNTdkTzZRR1RWQndhTmsifQ.ey
JleHAiOjE1MzM2NzY1OTAsIm5iZiI6MTUzMzY3Mjk5MCwidmVyIjoiMS4wIiwiaXNzIjoiaHR0cHM6Ly9sb2dpbi5taWNyb3NvZnRvbmxpbmUu
Y29tLzUxNmZjMDY1LWZmMzYtNGI5My1hYTVhLWQ2ZWVkYTdjYmFjOC92Mi4wLyIsInN1YiI6ImJmZDgwODBjLTBjNDAtNDNjYS05ZTI3LTUyZT
AyNzIyNWYyMSIsImF1ZCI6IjljNTA2MThjLWY5NTEtNDlhNS1iZmU1LWQ3ODA4NTEyMWMzYSIsImlhdCI6MTUzMzY3Mjk5MCwiYXV0aF90aW1l
IjoxNTMzNjcyOTkwLCJpZHAiOiJMb2NhbEFjY291bnQiLCJuYW1lIjoiRGF2aWRNdSIsImVtYWlscyI6WyJkYXZpZHdtMTAzMEBob3RtYWlsLm
NvbSJdLCJ0ZnAiOiJCMkNfMV9ST1BDX0F1dGgiLCJhdF9oYXNoIjoiYW5hZ3QtX1NveUtBQV9UNFBLaHN4dyJ9.bPzpUFh94XFHXC_yR6qH_Un
f6_hN-9-BjDXOzrdb1AuoU6-
owQ3fWDxNBUbYEPALid3sgm4qhJ6BROFKryD8aWfrNyaErnYZwZ6rliHk4foa3JsbDgM3yNGPL0hzOFpC4Y9QhUjNgQOxvnQLtqbHVNonSvBc7
VVPAjBDza44GowmvLORfJ1qkTjdrFM75HlLVeQch8cUNf-Ova77JdG5WHgYgqRhAq1OhV68YgEpQkARyz77zbAz9zZEHZZlgsli8UV6C-
CPcmoHbwS-85mLzF9nLxhzjgIXJwckB6I7lvTpfuRtaqZIb3pMYeHZJaxaNLDvq9Qe4N-danXABg1B2w",
"token_type": "Bearer",
"not_before": 1533672990,
"expires_in": 3600,
"expires_on": 1533676590,
"resource": "bef2222d56-552f-4a5b-b90a-1988a7d634c3",
"id_token_expires_in": 3600,
"profile_info":
"eyJ2ZXIiOiIxLjAiLCJ0aWQiOiI1MTZmYzA2NS1mZjM2LTRiOTMtYWE1YS1kNmVlZGE3Y2JhYzgiLCJzdWIiOm51bGwsIm5hbWUiOiJEYXZpZ
E11IiwicHJlZmVycmVkX3VzZXJuYW1lIjpudWxsLCJpZHAiOiJMb2NhbEFjY291bnQifQ",
"refresh_token":
"eyJraWQiOiJjcGltY29yZV8wOTI1MjAxNSIsInZlciI6IjEuMCIsInppcCI6IkRlZmxhdGUiLCJzZXIiOiIxLjAifQ..8oC4Q6aKdr35yMWm.
p43lns-cfWNFbtmrhvtssQXCItb3E9aSLafZJ6nKnnpXGQ-ZapOOyH7hPK7AN_RT7NMsQwNdy0Fyv_hOMrFbMPZNvHSa91RsQIvBZ73-
CVy0HNF0grSezjCATg4NVHfricuQVegEmZKFOoNP6TaMC2kIlEi3rhrrO8VE3ZFQ3Jjo6j91BJaE9ybb02HWOoKqlzHiazwQyUHujw_R0TyXaQ
CI_gtLARr5QUXm7hlAfHhxR9uewQKlRbeuMH8nCMLSMASCJyzfeSJTjXmA0F0VrXozrqzOJdyy0EETPR7oA48MJ9l6C2sy2ZELkqpOM3xhbhV-
Re7nM09b8DeWuCw7VNTcQc9DKnIHDR-H5U2Tc-
lMJQadgUNZv7KGSRGTyprWb7wF7FEPnRNID5PCDV_N_yoQpI7VvJO_NotXEgHFo7OHs5Gsgwpl5mrDtymYzIMM7onTflOlu46em_qltji7xcWN
OuHq4AeOlcY9ZythZgJH7livljReTwyX8QuUwpomXVEUGDc5pAnvgSozxnUbM7AlwfUeJZRT45P7L7683RSqChdNxiQk0sXUECqxnFxMAz4VUz
ld2yFe-pzvxFF4_feQjBEmSCAvekpvJUrEticEs4QzByV5UZ2ZCKccijFTg4doACiCo_z13JTm47mxm-5jUhXOQqiL69oxztk.KqI-
z2LlC77lvwqmeFtdGQ",
"refresh_token_expires_in": 1209600
}
NOTE
When creating users via Graph API, the application needs to have "openid", "offline_access", and "profile" permissions from
Microsoft Graph.
Implement with your preferred native SDK or use App-Auth
The Azure AD B2C implementation meets OAuth 2.0 standards for public client resource owner password
credentials and should be compatible with most client SDKs. We have tested this flow extensively, in production,
with AppAuth for iOS and AppAuth for Android. For the latest information, see Native App SDK for OAuth 2.0
and OpenID Connect implementing modern best practices.
Download working samples that have been configured for use with Azure AD B2C from GitHub, for Android and
for iOS.
Set up self-service password reset for your customers
10/3/2019 • 2 minutes to read • Edit Online
With the self-service password reset feature, your customers who have signed up for local accounts can reset their
passwords on their own. This significantly reduces the burden on your support staff, especially if your application
has millions of customers using it on a regular basis. Currently, using a verified email address is the only supported
recovery method.
NOTE
This article applies to self-service password reset used in the context of the V1 Sign in user flow, which uses Local Account
SignIn as the identity provider. If you need fully customizable password reset user flows invoked from your app, see this
article.
By default, your directory doesn't have self-service password reset turned on. Use the following steps to turn it on:
1. Sign in to the Azure portal as the Subscription Administrator. This is the same work or school account or the
same Microsoft account that you used to create your directory.
2. Open Azure Active Directory (in the navigation bar on the left side).
3. Scroll down on the options blade and select Password reset.
4. Set Self service password reset enabled to All.
5. Click Save at the top of the page. You're done!
To test, use the "Run now" feature on any sign-in user flow that has local accounts as an identity provider. On the
local account sign-in page (where you enter an email address and password, or a username and password), click
Can't access your account? to verify the customer experience.
NOTE
The self-service password reset pages can be customized by using the company branding feature.
Customize the user interface in Azure Active
Directory B2C
12/9/2019 • 6 minutes to read • Edit Online
Branding and customizing the user interface that Azure Active Directory B2C (Azure AD B2C ) displays to your
customers helps provide a seamless user experience in your application. These experiences include signing up,
signing in, profile editing, and password resetting. This article introduces the methods of user interface (UI)
customization for both user flows and custom policies.
When you choose a template, the selected layout is applied to all pages in your user flow, and the URI for each
page is visible in the Custom page URI field.
<!DOCTYPE html>
<html>
<head>
<title>!Add your title here!</title>
<link rel="stylesheet" href="https://mystore1.blob.core.windows.net/b2c/style.css">
</head>
<body>
<h1>My B2C Application</h1>
<div id="api"></div> <!-- Leave this element empty because Azure AD B2C will insert content here.
-->
</body>
</html>
Use CSS to style the UI elements that Azure AD B2C inserts into your page. The following example shows
a simple CSS file that also includes settings for the sign-up injected HTML elements:
h1 {
color: blue;
text-align: center;
}
.intro h2 {
text-align: center;
}
.entry {
width: 400px ;
margin-left: auto ;
margin-right: auto ;
}
.divider h2 {
text-align: center;
}
.create {
width: 400px ;
margin-left: auto ;
margin-right: auto ;
}
Host your content on an HTTPS endpoint (with CORS allowed). Both GET and OPTIONS request methods
must be enabled when configuring CORS.
Create or edit a user flow or custom policy to use the content that you created.
HTML fragments from Azure AD B2C
The following table lists the HTML fragments that Azure AD B2C merges into the <div id="api"></div> element
located in your content.
Identity provider selection Contains a list of buttons for identity providers that the
customer can choose from during sign-up or sign-in. These
buttons include social identity providers such as Facebook,
Google, or local accounts (based on email address or user
name).
Local account sign-up Contains a form for local account sign-up based on an email
address or a user name. The form can contain different input
controls such as text input box, password entry box, radio
button, single-select drop-down boxes, and multi-select check
boxes.
Social account sign-up May appear when signing up using an existing account from a
social identity provider such as Facebook or Google. It's used
when additional information must be collected from the
customer using a sign-up form.
Unified sign-up or sign-in Handles both sign-up and sign-in of customers who can use
social identity providers such as Facebook, Google, or local
accounts.
Multi-factor authentication Customers can verify their phone numbers (using text or
voice) during sign-up or sign-in.
Localize content
You localize your HTML content by enabling language customization in your Azure AD B2C tenant. Enabling this
feature allows Azure AD B2C to forward the OpenID Connect parameter ui-locales to your endpoint. Your
content server can use this parameter to provide language-specific HTML pages.
Content can be pulled from different places based on the locale that's used. In your CORS -enabled endpoint, you
set up a folder structure to host content for specific languages. You'll call the right one if you use the wildcard value
{Culture:RFC5646} .
https://contoso.blob.core.windows.net/{Culture:RFC5646}/myHTML/unified.html
https://contoso.blob.core.windows.net/fr/myHTML/unified.html
Examples
You can find several sample template files in the B2C -AzureBlobStorage-Client repository on GitHub.
The sample HTML and CSS files in the templates are located in the /sample_templates directory.
Next steps
If you're using user flows, you can start customizing your UI with the tutorial:
Customize the user interface of your applications in Azure Active Directory B2C.
If you're using custom policies, you can start customizing the UI with the article:
Customize the user interface of your application using a custom policy in Azure Active Directory B2C.
JavaScript and page layout versions in Azure Active
Directory B2C
12/9/2019 • 2 minutes to read • Edit Online
NOTE
This feature is in public preview.
Azure AD B2C provides a set of packaged content containing HTML, CSS, and JavaScript for the user interface
elements in your user flows and custom policies. To enable JavaScript for your applications, you must add an
element to your custom policy or enable it in the portal for user flows, select a page layout, and use b2clogin.com
in your requests.
If you intend to enable JavaScript client-side code, you’ll want to be sure the elements you’re basing your
JavaScript on are immutable. Otherwise, any changes could cause unexpected behavior on your user pages. To
prevent these issues, you can enforce the use of a page layout and specify a page layout version. Doing this
ensures that all the content definitions that you’ve based your JavaScript on are immutable. Even if you don’t
intend to enable JavaScript, you can specify a page layout version for your pages.
User flows
In the user flow Properties, you can enable JavaScript, which also enforces the use of a page layout. You can then
set the page layout version for the user flow as described in the next section.
Next steps
For information about the different page layout versions, see the Version change log section of Select a page
layout in Azure Active Directory B2C using custom policies.
You can find examples of JavaScript usage in JavaScript samples for use in Azure Active Directory B2C.
Language customization in Azure Active Directory
B2C
11/7/2019 • 7 minutes to read • Edit Online
Language customization in Azure Active Directory B2C (Azure AD B2C ) allows your user flow to accommodate
different languages to suit your customer needs. Microsoft provides the translations for 36 languages, but you can
also provide your own translations for any language. Even if your experience is provided for only a single
language, you can customize any text on the pages.
NOTE
If you're using custom user attributes, you need to provide your own translations. For more information, see Customize
your strings.
1. Ensure that your user flow has language customization enabled from previous instructions.
2. On the Languages page for the user flow, select a language that you want to support.
3. In the properties pane, change Enabled to Yes.
4. Select Save at the top of the properties pane.
NOTE
If a ui_locales parameter is not provided, the page is translated to the customer's browser language only if it is enabled.
IMPORTANT
If you need to override a string, make sure to set the Override value to true . If the value isn't changed, the entry is
ignored.
{
"LocalizedStrings": [...],
"LocalizedCollections": [{
"ElementType":"ClaimType",
"ElementId":"<UserAttribute>",
"TargetCollection":"Restriction",
"Override": true,
"Items":[
{
"Name":"<Response1>",
"Value":"<Value1>"
},
{
"Name":"<Response2>",
"Value":"<Value2>"
}
]
}]
}
ElementId is the user attribute that this LocalizedCollections attribute is a response to.
Name is the value that's shown to the user.
Value is what is returned in the claim when this option is selected.
https://wingtiptoysb2c.blob.core.windows.net/{Culture:RFC5646}/wingtip/unified.html
You can load the page in fr . When the page pulls HTML and CSS content, it's pulling from:
https://wingtiptoysb2c.blob.core.windows.net/fr/wingtip/unified.html
IMPORTANT
You need to either enable the custom languages or upload overrides for it before you can save.
Additional information
Page UI customization labels as overrides
When you enable language customization, your previous edits for labels using page UI customization are
persisted in a JSON file for English (en). You can continue to change your labels and other strings by uploading
language resources in language customization.
Up-to -date translations
Microsoft is committed to providing the most up-to-date translations for your use. Microsoft continuously
improves translations and keeps them in compliance for you. Microsoft will identify bugs and changes in global
terminology and make updates that will work seamlessly in your user flow.
Support for right-to -left languages
Microsoft currently doesn't provide support for right-to-left languages. You can accomplish this by using custom
locales and using CSS to change the way the strings are displayed. If you need this feature, please vote for it on
Azure Feedback.
Social identity provider translations
Microsoft provides the ui_locales OIDC parameter to social logins. But some social identity providers, including
Facebook and Google, don't honor them.
Browser behavior
Chrome and Firefox both request for their set language. If it's a supported language, it's displayed before the
default. Microsoft Edge currently does not request a language and goes straight to the default language.
Supported languages
Azure AD B2C includes support for the following languages. User flow languages are provided by Azure AD B2C.
The multi-factor authentication (MFA) notification languages are provided by Azure MFA.
Arabic ar
Bulgarian bg
Bangla bn
Catalan ca
Czech cs
Danish da
German de
Greek el
English en
Spanish es
Estonian et
Basque eu
Finnish fi
French fr
Galician gl
Gujarati gu
Hebrew he
Hindi hi
Croatian hr
LANGUAGE LANGUAGE CODE USER FLOWS MFA NOTIFICATIONS
Hungarian hu
Indonesian id
Italian it
Japanese ja
Kazakh kk
Kannada kn
Korean ko
Lithuanian lt
Latvian lv
Malayalam ml
Marathi mr
Malay ms
Norwegian Bokmal nb
Dutch nl
Norwegian no
Punjabi pa
Polish pl
Romanian ro
Russian ru
Slovak sk
Slovenian sl
Swedish sv
Tamil ta
Telugu te
Thai th
Turkish tr
Ukrainian uk
Vietnamese vi
Azure Active Directory B2C (Azure AD B2C ) supports changing the complexity requirements for passwords
supplied by an end user when creating an account. By default, Azure AD B2C uses Strong passwords. Azure AD
B2C also supports configuration options to control the complexity of passwords that customers can use.
NOTE
Requiring 4 of 4 can result in end-user frustration. Some studies have shown that this requirement does not
improve password entropy. See NIST Password Guidelines
Disable email verification during customer sign-up in
Azure Active Directory B2C
12/9/2019 • 2 minutes to read • Edit Online
By default, Azure Active Directory B2C (Azure AD B2C ) verifies your customer's email address for local accounts
(accounts for users who sign up with email address or username). Azure AD B2C ensures valid email addresses by
requiring customers to verify them during the sign-up process. It also prevents a malicious actors from using
automated processes to generate fraudulent accounts in your applications.
Some application developers prefer to skip email verification during the sign-up process and instead have
customers verify their email address later. To support this, Azure AD B2C can be configured to disable email
verification. Doing so creates a smoother sign-up process and gives developers the flexibility to differentiate
customers that have verified their email address from customers that have not.
Follow these steps to disable email verification:
1. Sign in to the Azure portal
2. Use the Directory + subscription filter in the top menu to select the directory that contains your Azure AD
B2C tenant.
3. In the left menu, select Azure AD B2C. Or, select All services and search for and select Azure AD B2C.
4. Select User flows.
5. Select the user flow for which you want to disable email verification. For example, B2C_1_signinsignup.
6. Select Page layouts.
7. Select Local account sign-up page.
8. Under User attributes, select Email Address.
9. In the REQUIRES VERIFICATION drop down, select No.
10. Select Save. Email verification is now disabled for this user flow.
WARNING
Disabling email verification in the sign-up process may lead to spam. If you disable the default Azure AD B2C-provided email
verification, we recommend that you implement a replacement verification system.
Enable multi-factor authentication in Azure Active
Directory B2C
9/17/2019 • 2 minutes to read • Edit Online
Azure Active Directory B2C (Azure AD B2C ) integrates directly with Azure Multi-Factor Authentication so that
you can add a second layer of security to sign-up and sign-in experiences in your applications. You enable multi-
factor authentication without writing a single line of code. If you already created sign up and sign-in user flows,
you can still enable multi-factor authentication.
This feature helps applications handle scenarios such as the following:
You don't require multi-factor authentication to access one application, but you do require it to access another.
For example, the customer can sign into an auto insurance application with a social or local account, but must
verify the phone number before accessing the home insurance application registered in the same directory.
You don't require multi-factor authentication to access an application in general, but you do require it to access
the sensitive portions within it. For example, the customer can sign in to a banking application with a social or
local account and check the account balance, but must verify the phone number before attempting a wire
transfer.
To use an Azure Active Directory (Azure AD ) as an identity provider in Azure AD B2C, you need to create an
application that represents it. This article shows you how to enable sign-in for users from a specific Azure AD
organization using a user flow in Azure AD B2C.
https://your-B2C-tenant-name.b2clogin.com/your-B2C-tenant-name.onmicrosoft.com/oauth2/authresp
https://login.microsoftonline.com/your-AD-tenant-domain/.well-known/openid-configuration
NOTE
This feature is in public preview.
NOTE
This feature is in public preview.
Create a QQ application
To use a QQ account as an identity provider in Azure Active Directory B2C (Azure AD B2C ), you need to create an
application in your tenant that represents it. If you don't already have a QQ account, you can sign up at
https://ssl.zc.qq.com/en/index.html?type=1&ptlang=1033.
Register for the QQ developer program
1. Sign in to the QQ developer portal with your QQ account credentials.
2. After signing in, go to https://open.qq.com/reg to register yourself as a developer.
3. Select 个人 (individual developer).
4. Enter the required information and select 下一步 (next step).
5. Complete the email verification process. You will need to wait a few days to be approved after registering as a
developer.
Register a QQ application
1. Go to https://connect.qq.com/index.html.
2. Select 应 用管理 (app management).
3. Select 创 建 应 用 (create app) and enter the required information.
4. Enter https://your-tenant-name.b2clogin.com/your-tenant-name}.onmicrosoft.com/oauth2/authresp in 授 权 回 调 域
(callback URL ). For example, if your tenant_name is contoso, set the URL to be
https://contoso.b2clogin.com/contoso.onmicrosoft.com/oauth2/authresp .
5. Select 创 建 应 用 (create app).
6. On the confirmation page, select 应 用管理 (app management) to return to the app management page.
7. Select 查 看 (view ) next to the app you created.
8. Select 修改 (edit).
9. Copy the APP ID and APP KEY. You need both of these values to add the identity provider to your tenant.
Create an application
To use Twitter as an identity provider in Azure AD B2C, you need to create a Twitter application. If you don't
already have a Twitter account, you can sign up at https://twitter.com/signup.
1. Sign in to the Twitter Developers website with your Twitter account credentials.
2. Select Create an app.
3. Enter an App name and an Application description.
4. In Website URL, enter https://your-tenant.b2clogin.com . Replace your-tenant with the name of your tenant.
For example, https://contosob2c.b2clogin.com.
5. For the Callback URL, enter
https://your-tenant.b2clogin.com/your-tenant.onmicrosoft.com/your-user-flow-Id/oauth1/authresp . Replace
your-tenant with the name of your tenant name and your-user-flow-Id with the identifier of your user flow.
For example, b2c_1A_signup_signin_twitter . You need to use all lowercase letters when entering your tenant
name and user flow id even if they are defined with uppercase letters in Azure AD B2C.
6. At the bottom of the page, read and accept the terms, and then select Create.
7. On the App details page, select Edit > Edit details, check the box for Enable Sign in with Twitter, and then
select Save.
8. Select Keys and tokens and record the Consumer API Key and the Consumer API secret key values to be
used later.
NOTE
This feature is in public preview.
NOTE
This feature is in public preview.
OpenID Connect is an authentication protocol built on top of OAuth 2.0 that can be used for secure user sign-in.
Most identity providers that use this protocol are supported in Azure AD B2C. This article explains how you can
add custom OpenID Connect identity providers into your user flows.
NOTE
The client secret is optional. However, you must enter a client secret if you'd like to use the authorization code flow, which
uses the secret to exchange the code for the token.
Scope
Scope defines the information and permissions you are looking to gather from your custom identity provider.
OpenID Connect requests must contain the openid scope value in order to receive the ID token from the identity
provider. Without the ID token, users are not able to sign in to Azure AD B2C using the custom identity provider.
Other scopes can be appended separated by space. Refer to the custom identity provider's documentation to see
what other scopes may be available.
Response type
The response type describes what kind of information is sent back in the initial call to the authorization_endpoint
of the custom identity provider. The following response types can be used:
code : As per the authorization code flow, a code will be returned back to Azure AD B2C. Azure AD B2C
proceeds to call the token_endpoint to exchange the code for the token.
id_token : An ID token is returned back to Azure AD B2C from the custom identity provider.
Response mode
The response mode defines the method that should be used to send the data back from the custom identity
provider to Azure AD B2C. The following response modes can be used:
form_post : This response mode is recommended for best security. The response is transmitted via the HTTP
POST method, with the code or token being encoded in the body using the application/x-www-form-urlencoded
format.
query : The code or token is returned as a query parameter.
Domain hint
The domain hint can be used to skip directly to the sign in page of the specified identity provider, instead of having
the user make a selection among the list of available identity providers. To allow this kind of behavior, enter a value
for the domain hint. To jump to the custom identity provider, append the parameter
domain_hint=<domain hint value> to the end of your request when calling Azure AD B2C for sign in.
Claims mapping
After the custom identity provider sends an ID token back to Azure AD B2C, Azure AD B2C needs to be able to
map the claims from the received token to the claims that Azure AD B2C recognizes and uses. For each of the
following mappings, refer to the documentation of the custom identity provider to understand the claims that are
returned back in the identity provider's tokens:
User ID: Enter the claim that provides the unique identifier for the signed-in user.
Display Name: Enter the claim that provides the display name or full name for the user.
Given Name: Enter the claim that provides the first name of the user.
Surname: Enter the claim that provides the last name of the user.
Email: Enter the claim that provides the email address of the user.
Configure tokens in Azure Active Directory B2C
9/17/2019 • 2 minutes to read • Edit Online
In this article, you learn how to configure the lifetime and compatibility of a token in Azure Active Directory B2C
(Azure AD B2C ).
Prerequisites
Create a user flow to enable users to sign up and sign in to your application.
8. Click Save.
Next steps
Learn more about how to use access tokens.
Configure session behavior in Azure Active Directory
B2C
9/17/2019 • 2 minutes to read • Edit Online
This feature gives you fine-grained control, on a per-user flow basis, of:
Lifetimes of web application sessions managed by Azure AD B2C.
Single sign-on (SSO ) behavior across multiple apps and user flows in your Azure AD B2C tenant.
These settings are not available for password reset user flows.
Azure AD B2C supports the OpenID Connect authentication protocol for enabling secure sign-in to web
applications. You can use the following properties to manage web application sessions:
8. Click Save.
Enable Age Gating in Azure Active Directory B2C
9/17/2019 • 3 minutes to read • Edit Online
IMPORTANT
This feature is in public preview. Do not use feature for production applications.
Age gating in Azure Active Directory B2C (Azure AD B2C ) enables you to identify minors that want to use your
application. You can choose to block the minor from signing into the application. Users can also go back to the
application and identify their age group and their parental consent status. Azure AD B2C can block minors without
parental consent. Azure AD B2C can also be set up to allow the application to decide what to do with minors.
After you enable age gating in your user flow, users are asked when they were born and what country/region they
live in. If a user signs in that hasn't previously entered the information, they'll need to enter it the next time they
sign in. The rules are applied every time a user signs in.
Azure AD B2C uses the information that the user enters to identify whether they're a minor. The ageGroup field is
then updated in their account. The value can be null , Undefined , Minor , Adult , and NotAdult . The ageGroup
and consentProvidedForMinor fields are then used to calculate the value of legalAgeGroupClassification.
Age gating involves two age values: the age that someone is no longer considered a minor, and the age at which a
minor must have parental consent. The following table lists the age rules that are used for defining a minor and a
minor requiring consent.
AT Austria 14 18
BE Belgium 14 18
BG Bulgaria 16 18
BH Bahrain None 21
CM Cameroon None 21
CY Cyprus 16 18
CZ Czech Republic 16 18
DE Germany 16 18
DK Denmark 16 18
EE Estonia 16 18
COUNTRY/REGION COUNTRY/REGION NAME MINOR CONSENT AGE MINOR AGE
EG Egypt None 21
ES Spain 13 18
FR France 16 18
GB United Kingdom 13 18
GR Greece 16 18
HR Croatia 16 18
HU Hungary 16 18
IE Ireland 13 18
IT Italy 16 18
KR Korea, Republic of 14 18
LT Lithuania 16 18
LU Luxembourg 16 18
LV Latvia 16 18
MT Malta 16 18
NA Namibia None 21
NL Netherlands 16 18
PL Poland 13 18
PT Portugal 16 18
RO Romania 16 18
SE Sweden 13 18
SG Singapore None 21
SI Slovenia 16 18
SK Slovakia 16 18
TD Chad None 21
TH Thailand None 20
COUNTRY/REGION COUNTRY/REGION NAME MINOR CONSENT AGE MINOR AGE
TW Taiwan None 20
US United States 13 18
Every customer-facing application has unique requirements for the information that needs to be collected. Your
Azure Active Directory B2C (Azure AD B2C ) tenant comes with a built-in set of information stored in attributes,
such as Given Name, Surname, City, and Postal Code. With Azure AD B2C, you can extend the set of attributes
stored on each customer account.
You can create custom attributes in the Azure portal and use them in your sign-up user flows, sign-up or sign-in
user flows, or profile editing user flows. You can also read and write these attributes by using the Azure AD Graph
API. Custom attributes in Azure AD B2C use Azure AD Graph API Directory Schema Extensions.
NOTE
Support for newer Microsoft Graph API for querying Azure AD B2C tenant is still under development.
A user flow in Azure Active Directory B2C (Azure AD B2C ) provides users of your application an opportunity to
sign up or sign in with an identity provider. When the journey starts, Azure AD B2C receives an access token from
the identity provider. Azure AD B2C uses that token to retrieve information about the user. You enable a claim in
your user flow to pass the token through to the applications that you register in Azure AD B2C.
Azure AD B2C currently only supports passing the access token of OAuth 2.0 identity providers, which include
Facebook and Google. For all other identity providers, the claim is returned blank.
Prerequisites
Your application must be using a v2 user flow.
Your user flow is configured with an OAuth 2.0 identity provider.
Next steps
Learn more in the overview of Azure AD B2C tokens.
Get started with custom policies in Azure
Active Directory B2C
12/1/2019 • 8 minutes to read • Edit Online
NOTE
In Azure Active Directory B2C, custom policies are designed primarily to address complex scenarios. For most
scenarios, we recommend that you use built-in user flows.
Custom policies are configuration files that define the behavior of your Azure Active Directory B2C
(Azure AD B2C ) tenant. In this article, you create a custom policy that supports local account sign-up
or sign-in by using an email address and password. You also prepare your environment for adding
identity providers.
Prerequisites
If you don't have one already, create an Azure AD B2C tenant that is linked to your Azure
subscription.
Register your application in the tenant that you created so that it can communicate with Azure AD
B2C.
Complete the steps in Set up sign-up and sign-in with a Facebook account to configure a Facebook
application.
2. In all of the files in the SocialAndLocalAccounts directory, replace the string yourtenant with
the name of your Azure AD B2C tenant.
For example, if the name of your B2C tenant is contosotenant, all instances of
yourtenant.onmicrosoft.com become contosotenant.onmicrosoft.com .
TIP
If your XML editor supports validation, validate the files against the TrustFrameworkPolicy_0.3.0.0.xsd
XML schema that is located in the root directory of the starter pack. XML schema validation identifies errors
before uploading.
<TechnicalProfile Id="Facebook-OAUTH">
<Metadata>
<!--Replace the value of client_id in this technical profile with the Facebook app ID"-->
<Item Key="client_id">00000000000000</Item>
Next steps
Next, try adding Azure Active Directory (Azure AD ) as an identity provider. The base file used in this
getting started guide already contains some of the content that you need for adding other identity
providers like Azure AD.
For information about setting up Azure AD as and identity provider, see Set up sign-up and sign-in
with an Azure Active Directory account using Active Directory B2C custom policies.
Configure the resource owner password credentials
flow in Azure Active Directory B2C using a custom
policy
12/9/2019 • 7 minutes to read • Edit Online
NOTE
This feature is in public preview.
In Azure Active Directory B2C (Azure AD B2C ), the resource owner password credentials (ROPC ) flow is an OAuth
standard authentication flow. In this flow, an application, also known as the relying party, exchanges valid
credentials for tokens. The credentials include a user ID and password. The tokens returned are an ID token, access
token, and a refresh token.
The following options are supported in the ROPC flow:
Native Client - User interaction during authentication happens when code runs on a user-side device.
Public client flow - Only user credentials that are gathered by an application are sent in the API call. The
credentials of the application aren't sent.
Add new claims - The ID token contents can be changed to add new claims.
The following flows aren't supported:
Server-to-server - The identity protection system needs a reliable IP address gathered from the caller (the
native client) as part of the interaction. In a server-side API call, only the server’s IP address is used. If too many
sign-ins fail, the identity protection system may look at a repeated IP address as an attacker.
Single page application - A front-end application that is primarily written in JavaScript. Often, the application
is written by using a framework like AngularJS, Ember.js, or Durandal.
Confidential client flow - The application client ID is validated, but the application secret isn't.
Prerequisites
Complete the steps in Get started with custom policies in Azure Active Directory B2C.
Register an application
To register an application in your Azure AD B2C tenant, you can use the current Applications experience, or our
new unified App registrations (Preview) experience. Learn more about the new experience.
Applications
App registrations (Preview )
1. Sign in to the Azure portal.
2. Select the Directory + subscription filter in the top menu, and then select the directory that contains your
Azure AD B2C tenant.
3. In the left menu, select Azure AD B2C. Or, select All services and search for and select Azure AD B2C.
4. Select Applications, and then select Add.
5. Enter a name for the application. For example, ROPC_Auth_app.
6. For Native client, select Yes.
7. Leave the other values as they are, and then select Create.
8. Record the APPLICATION ID for use in a later step.
<ClaimsSchema>
<ClaimType Id="logonIdentifier">
<DisplayName>User name or email address that the user can use to sign in</DisplayName>
<DataType>string</DataType>
</ClaimType>
<ClaimType Id="resource">
<DisplayName>The resource parameter passes to the ROPC endpoint</DisplayName>
<DataType>string</DataType>
</ClaimType>
<ClaimType Id="refreshTokenIssuedOnDateTime">
<DisplayName>An internal parameter used to determine whether the user should be permitted to
authenticate again using their existing refresh token.</DisplayName>
<DataType>string</DataType>
</ClaimType>
<ClaimType Id="refreshTokensValidFromDateTime">
<DisplayName>An internal parameter used to determine whether the user should be permitted to
authenticate again using their existing refresh token.</DisplayName>
<DataType>string</DataType>
</ClaimType>
</ClaimsSchema>
3. After ClaimsSchema, add a ClaimsTransformations element and its child elements to the
BuildingBlocks element:
<ClaimsTransformations>
<ClaimsTransformation Id="CreateSubjectClaimFromObjectID" TransformationMethod="CreateStringClaim">
<InputParameters>
<InputParameter Id="value" DataType="string" Value="Not supported currently. Use oid claim." />
</InputParameters>
<OutputClaims>
<OutputClaim ClaimTypeReferenceId="sub" TransformationClaimType="createdClaim" />
</OutputClaims>
</ClaimsTransformation>
<ClaimsTransformation Id="AssertRefreshTokenIssuedLaterThanValidFromDate"
TransformationMethod="AssertDateTimeIsGreaterThan">
<InputClaims>
<InputClaim ClaimTypeReferenceId="refreshTokenIssuedOnDateTime"
TransformationClaimType="leftOperand" />
<InputClaim ClaimTypeReferenceId="refreshTokensValidFromDateTime"
TransformationClaimType="rightOperand" />
</InputClaims>
<InputParameters>
<InputParameter Id="AssertIfEqualTo" DataType="boolean" Value="false" />
<InputParameter Id="AssertIfRightOperandIsNotPresent" DataType="boolean" Value="true" />
</InputParameters>
</ClaimsTransformation>
</ClaimsTransformations>
4. Locate the ClaimsProvider element that has a DisplayName of Local Account SignIn and add following
technical profile:
<TechnicalProfile Id="ResourceOwnerPasswordCredentials-OAUTH2">
<DisplayName>Local Account SignIn</DisplayName>
<Protocol Name="OpenIdConnect" />
<Metadata>
<Item Key="UserMessageIfClaimsPrincipalDoesNotExist">We can't seem to find your account</Item>
<Item Key="UserMessageIfInvalidPassword">Your password is incorrect</Item>
<Item Key="UserMessageIfOldPasswordUsed">Looks like you used an old password</Item>
<Item Key="DiscoverMetadataByTokenIssuer">true</Item>
<Item Key="ValidTokenIssuerPrefixes">https://sts.windows.net/</Item>
<Item Key="METADATA">https://login.microsoftonline.com/{tenant}/.well-known/openid-
configuration</Item>
<Item Key="authorization_endpoint">https://login.microsoftonline.com/{tenant}/oauth2/token</Item>
<Item Key="response_types">id_token</Item>
<Item Key="response_mode">query</Item>
<Item Key="scope">email openid</Item>
</Metadata>
<InputClaims>
<InputClaim ClaimTypeReferenceId="logonIdentifier" PartnerClaimType="username" Required="true"
DefaultValue="{OIDC:Username}"/>
<InputClaim ClaimTypeReferenceId="password" Required="true" DefaultValue="{OIDC:Password}" />
<InputClaim ClaimTypeReferenceId="grant_type" DefaultValue="password" />
<InputClaim ClaimTypeReferenceId="scope" DefaultValue="openid" />
<InputClaim ClaimTypeReferenceId="nca" PartnerClaimType="nca" DefaultValue="1" />
<InputClaim ClaimTypeReferenceId="client_id" DefaultValue="00000000-0000-0000-0000-000000000000" />
<InputClaim ClaimTypeReferenceId="resource_id" PartnerClaimType="resource" DefaultValue="00000000-
0000-0000-0000-000000000000" />
</InputClaims>
<OutputClaims>
<OutputClaim ClaimTypeReferenceId="objectId" PartnerClaimType="oid" />
<OutputClaim ClaimTypeReferenceId="userPrincipalName" PartnerClaimType="upn" />
</OutputClaims>
<OutputClaimsTransformations>
<OutputClaimsTransformation ReferenceId="CreateSubjectClaimFromObjectID" />
</OutputClaimsTransformations>
<UseTechnicalProfileForSessionManagement ReferenceId="SM-Noop" />
</TechnicalProfile>
<ClaimsProvider>
<DisplayName>Session Management</DisplayName>
<TechnicalProfiles>
<TechnicalProfile Id="SM-RefreshTokenReadAndSetup">
<DisplayName>Trustframework Policy Engine Refresh Token Setup Technical Profile</DisplayName>
<Protocol Name="None" />
<OutputClaims>
<OutputClaim ClaimTypeReferenceId="objectId" />
<OutputClaim ClaimTypeReferenceId="refreshTokenIssuedOnDateTime" />
</OutputClaims>
</TechnicalProfile>
</TechnicalProfiles>
</ClaimsProvider>
<ClaimsProvider>
<DisplayName>Token Issuer</DisplayName>
<TechnicalProfiles>
<TechnicalProfile Id="JwtIssuer">
<Metadata>
<!-- Point to the redeem refresh token user journey-->
<Item Key="RefreshTokenUserJourneyId">ResourceOwnerPasswordCredentials-RedeemRefreshToken</Item>
</Metadata>
</TechnicalProfile>
</TechnicalProfiles>
</ClaimsProvider>
6. Add a UserJourneys element and its child elements to the TrustFrameworkPolicy element:
<UserJourney Id="ResourceOwnerPasswordCredentials">
<PreserveOriginalAssertion>false</PreserveOriginalAssertion>
<OrchestrationSteps>
<OrchestrationStep Order="1" Type="ClaimsExchange">
<ClaimsExchanges>
<ClaimsExchange Id="ResourceOwnerFlow"
TechnicalProfileReferenceId="ResourceOwnerPasswordCredentials-OAUTH2" />
</ClaimsExchanges>
</OrchestrationStep>
<OrchestrationStep Order="2" Type="ClaimsExchange">
<ClaimsExchanges>
<ClaimsExchange Id="AADUserReadWithObjectId" TechnicalProfileReferenceId="AAD-
UserReadUsingObjectId" />
</ClaimsExchanges>
</OrchestrationStep>
<OrchestrationStep Order="3" Type="SendClaims" CpimIssuerTechnicalProfileReferenceId="JwtIssuer" />
</OrchestrationSteps>
</UserJourney>
<UserJourney Id="ResourceOwnerPasswordCredentials-RedeemRefreshToken">
<PreserveOriginalAssertion>false</PreserveOriginalAssertion>
<OrchestrationSteps>
<OrchestrationStep Order="1" Type="ClaimsExchange">
<ClaimsExchanges>
<ClaimsExchange Id="RefreshTokenSetupExchange" TechnicalProfileReferenceId="SM-
RefreshTokenReadAndSetup" />
</ClaimsExchanges>
</OrchestrationStep>
<OrchestrationStep Order="2" Type="ClaimsExchange">
<ClaimsExchanges>
<ClaimsExchange Id="CheckRefreshTokenDateFromAadExchange" TechnicalProfileReferenceId="AAD-
UserReadUsingObjectId-CheckRefreshTokenDate" />
</ClaimsExchanges>
</OrchestrationStep>
<OrchestrationStep Order="3" Type="SendClaims" CpimIssuerTechnicalProfileReferenceId="JwtIssuer" />
</OrchestrationSteps>
</UserJourney>
7. On the Custom Policies page in your Azure AD B2C tenant, select Upload Policy.
8. Enable Overwrite the policy if it exists, and then browse to and select the TrustFrameworkExtensions.xml
file.
9. Click Upload.
5. On the Custom Policies page in your Azure AD B2C tenant, select Upload Policy.
6. Enable Overwrite the policy if it exists, and then browse to and select the ROPC_Auth.xml file.
7. Click Upload.
KEY VALUE
username user-account
password password1
grant_type password
client_id application-id
username=contosouser.outlook.com.ws&password=Passxword1&grant_type=password&scope=openid+bef22d56-552f-4a5b-
b90a-1988a7d634ce+offline_access&client_id=bef22d56-552f-4a5b-b90a-1988a7d634ce&response_type=token+id_token
KEY VALUE
grant_type refresh_token
response_type id_token
client_id application-id
resource application-id
refresh_token refresh-token
{
"access_token":
"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6Ilg1ZVhrNHh5b2pORnVtMWtsMll0djhkbE5QNC1jNTdkTzZRR1RWQndhT...",
"id_token":
"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6Ilg1ZVhrNHh5b2pORnVtMWtsMll0djhkbE5QNC1jNTdkTzZRR1RWQn...",
"token_type": "Bearer",
"not_before": 1533672990,
"expires_in": 3600,
"expires_on": 1533676590,
"resource": "bef2222d56-552f-4a5b-b90a-1988a7d634c3",
"id_token_expires_in": 3600,
"profile_info":
"eyJ2ZXIiOiIxLjAiLCJ0aWQiOiI1MTZmYzA2NS1mZjM2LTRiOTMtYWE1YS1kNmVlZGE3Y2JhYzgiLCJzdWIiOm51bGwsIm5hbWUiOiJEYXZpZE
11IiwicHJlZmVycmVkX3VzZXJuYW1lIjpudWxsLCJpZHAiOiJMb2NhbEFjY291bnQifQ",
"refresh_token":
"eyJraWQiOiJjcGltY29yZV8wOTI1MjAxNSIsInZlciI6IjEuMCIsInppcCI6IkRlZmxhdGUiLCJzZXIiOiIxLjAi...",
"refresh_token_expires_in": 1209600
}
Use a native SDK or App-Auth
Azure AD B2C meets OAuth 2.0 standards for public client resource owner password credentials and should be
compatible with most client SDKs. For the latest information, see Native App SDK for OAuth 2.0 and OpenID
Connect implementing modern best practices.
Next steps
See a full example of this scenario in the Azure Active Directory B2C custom policy starter pack.
Learn more about the tokens that are used by Azure Active Directory B2C in the Token reference.
Enable Keep me signed in (KMSI) in Azure Active
Directory B2C
8/29/2019 • 5 minutes to read • Edit Online
NOTE
In Azure Active Directory B2C, custom policies are designed primarily to address complex scenarios. For most scenarios, we
recommend that you use built-in user flows.
You can enable Keep Me Signed In (KMSI) functionality for users of your web and native applications that have
local accounts in your Azure Active Directory B2C (Azure AD B2C ) directory. This feature grants access to users
returning to your application without prompting them to reenter their username and password. This access is
revoked when a user signs out.
Users should not enable this option on public computers.
Prerequisites
An Azure AD B2C tenant that is configured to allow local account sign-in. KMSI is unsupported for external
identity provider accounts.
If you don't have a tenant, you can create one using the steps in Tutorial: Create an Azure Active Directory B2C
tenant.
<BuildingBlocks>
<ContentDefinitions>
<ContentDefinition Id="api.signuporsigninwithkmsi">
<LoadUri>~/tenant/default/unified.cshtml</LoadUri>
<RecoveryUri>~/common/default_page_error.html</RecoveryUri>
<DataUri>urn:com:microsoft:aad:b2c:elements:unifiedssp:1.1.0</DataUri>
<Metadata>
<Item Key="DisplayName">Signin and Signup</Item>
</Metadata>
</ContentDefinition>
</ContentDefinitions>
</BuildingBlocks>
<ClaimsProviders>
<ClaimsProvider>
<DisplayName>Local Account SignIn</DisplayName>
<TechnicalProfiles>
<TechnicalProfile Id="login-NonInteractive">
<Metadata>
<Item Key="client_id">ProxyIdentityExperienceFrameworkAppId</Item>
<Item Key="IdTokenAudience">IdentityExperienceFrameworkAppId</Item>
</Metadata>
<InputClaims>
<InputClaim ClaimTypeReferenceId="client_id"
DefaultValue="ProxyIdentityExperienceFrameworkAppID" />
<InputClaim ClaimTypeReferenceId="resource_id" PartnerClaimType="resource"
DefaultValue="IdentityExperienceFrameworkAppID" />
</InputClaims>
</TechnicalProfile>
</TechnicalProfiles>
</ClaimsProvider>
</ClaimsProviders>
2. Replace all values of ProxyIdentityExperienceFrameworkAppId with the application identifier of the Proxy
Identity Experience Framework application as described in Getting started.
3. Save the extensions file.
7. Save and upload the extension file and make sure that all validations succeed.
<UserJourneys>
<UserJourney Id="SignUpOrSignInWithKmsi">
<OrchestrationSteps>
<OrchestrationStep Order="1" Type="CombinedSignInAndSignUp"
ContentDefinitionReferenceId="api.signuporsigninwithkmsi">
<ClaimsProviderSelections>
<ClaimsProviderSelection ValidationClaimsExchangeId="LocalAccountSigninEmailExchange" />
</ClaimsProviderSelections>
<ClaimsExchanges>
<ClaimsExchange Id="LocalAccountSigninEmailExchange"
TechnicalProfileReferenceId="SelfAsserted-LocalAccountSignin-Email" />
</ClaimsExchanges>
</OrchestrationStep>
<OrchestrationStep Order="2" Type="ClaimsExchange">
<Preconditions>
<Precondition Type="ClaimsExist" ExecuteActionsIf="true">
<Value>objectId</Value>
<Action>SkipThisOrchestrationStep</Action>
</Precondition>
</Preconditions>
<ClaimsExchanges>
<ClaimsExchange Id="SignUpWithLogonEmailExchange"
TechnicalProfileReferenceId="LocalAccountSignUpWithLogonEmail" />
</ClaimsExchanges>
</OrchestrationStep>
<!-- This step reads any user attributes that we may not have received when in the token. -->
<OrchestrationStep Order="3" Type="ClaimsExchange">
<ClaimsExchanges>
<ClaimsExchange Id="AADUserReadWithObjectId" TechnicalProfileReferenceId="AAD-
UserReadUsingObjectId" />
</ClaimsExchanges>
</OrchestrationStep>
<OrchestrationStep Order="4" Type="SendClaims" CpimIssuerTechnicalProfileReferenceId="JwtIssuer"
/>
</OrchestrationSteps>
<ClientDefinition ReferenceId="DefaultWeb" />
</UserJourney>
</UserJourneys>
The value of SessionExpiryInSeconds represents the expiry time of an SSO session. This is used
internally by Azure AD B2C to check whether the session for KMSI is expired or not. The value of
KeepAliveInDays determines the Expires/Max-Age value of the SSO cookie in the web browser. Unlike
SessionExpiryInSeconds, KeepAliveInDays is used to prevent the browser from clearing the cookie
when it's closed. A user can silently sign in only if the SSO session cookie exists, which is controlled by
KeepAliveInDays, and isn't expired, which is controlled by SessionExpiryInSeconds.
If a user doesn't enable Keep me signed in on the sign-up and sign-in page, a session expires after the time
indicated by SessionExpiryInSeconds has passed or the browser is closed. If a user enables Keep me
signed in, the value of KeepAliveInDays overrides the value of SessionExpiryInSeconds and dictates
the session expiry time. Even if users close the browser and open it again, they can still silently sign-in as
long as it's within the time of KeepAliveInDays. It is recommended that you set the value of
SessionExpiryInSeconds to be a short period (1200 seconds), while the value of KeepAliveInDays can
be set to a relatively long period (7 days), as shown in the following example:
<RelyingParty>
<DefaultUserJourney ReferenceId="SignUpOrSignInWithKmsi" />
<UserJourneyBehaviors>
<SingleSignOn Scope="Tenant" KeepAliveInDays="7" />
<SessionExpiryType>Absolute</SessionExpiryType>
<SessionExpiryInSeconds>1200</SessionExpiryInSeconds>
</UserJourneyBehaviors>
<TechnicalProfile Id="PolicyProfile">
<DisplayName>PolicyProfile</DisplayName>
<Protocol Name="OpenIdConnect" />
<OutputClaims>
<OutputClaim ClaimTypeReferenceId="displayName" />
<OutputClaim ClaimTypeReferenceId="givenName" />
<OutputClaim ClaimTypeReferenceId="surname" />
<OutputClaim ClaimTypeReferenceId="email" />
<OutputClaim ClaimTypeReferenceId="objectId" PartnerClaimType="sub"/>
</OutputClaims>
<SubjectNamingInfo ClaimType="sub" />
</TechnicalProfile>
</RelyingParty>
NOTE
In Azure Active Directory B2C, custom policies are designed primarily to address complex scenarios. For most scenarios, we
recommend that you use built-in user flows.
In Azure Active Directory B2C (Azure AD B2C ), you can enable users who are signed in with a local account to
change their password without having to prove their authenticity by email verification. If the session expires by the
time the user gets to the password change flow, they're prompted to sign in again. This article shows you how to
configure password change in custom policies. It's also possible to configure self-service password reset for user
flows.
Prerequisites
Complete the steps in Get started with custom policies in Active Directory B2C.
<BuildingBlocks>
<ClaimsSchema>
<ClaimType Id="oldPassword">
<DisplayName>Old Password</DisplayName>
<DataType>string</DataType>
<UserHelpText>Enter password</UserHelpText>
<UserInputType>Password</UserInputType>
</ClaimType>
</ClaimsSchema>
</BuildingBlocks>
2. A ClaimsProvider element contains the technical profile that authenticates the user. Add the following claims
providers to the ClaimsProviders element:
<ClaimsProviders>
<ClaimsProvider>
<DisplayName>Local Account SignIn</DisplayName>
<TechnicalProfiles>
<TechnicalProfile Id="login-NonInteractive-PasswordChange">
<DisplayName>Local Account SignIn</DisplayName>
<Protocol Name="OpenIdConnect" />
<Metadata>
<Item Key="UserMessageIfClaimsPrincipalDoesNotExist">We can't seem to find your account</Item>
<Item Key="UserMessageIfInvalidPassword">Your password is incorrect</Item>
<Item Key="UserMessageIfOldPasswordUsed">Looks like you used an old password</Item>
<Item Key="ProviderName">https://sts.windows.net/</Item>
<Item Key="METADATA">https://login.microsoftonline.com/{tenant}/.well-known/openid-
configuration</Item>
<Item
<Item
Key="authorization_endpoint">https://login.microsoftonline.com/{tenant}/oauth2/token</Item>
<Item Key="response_types">id_token</Item>
<Item Key="response_mode">query</Item>
<Item Key="scope">email openid</Item>
<Item Key="UsePolicyInRedirectUri">false</Item>
<Item Key="HttpBinding">POST</Item>
<Item Key="client_id">ProxyIdentityExperienceFrameworkAppId</Item>
<Item Key="IdTokenAudience">IdentityExperienceFrameworkAppId</Item>
</Metadata>
<InputClaims>
<InputClaim ClaimTypeReferenceId="signInName" PartnerClaimType="username" Required="true" />
<InputClaim ClaimTypeReferenceId="oldPassword" PartnerClaimType="password" Required="true" />
<InputClaim ClaimTypeReferenceId="grant_type" DefaultValue="password" />
<InputClaim ClaimTypeReferenceId="scope" DefaultValue="openid" />
<InputClaim ClaimTypeReferenceId="nca" PartnerClaimType="nca" DefaultValue="1" />
<InputClaim ClaimTypeReferenceId="client_id"
DefaultValue="ProxyIdentityExperienceFrameworkAppID" />
<InputClaim ClaimTypeReferenceId="resource_id" PartnerClaimType="resource"
DefaultValue="IdentityExperienceFrameworkAppID" />
</InputClaims>
<OutputClaims>
<OutputClaim ClaimTypeReferenceId="objectId" PartnerClaimType="oid" />
<OutputClaim ClaimTypeReferenceId="tenantId" PartnerClaimType="tid" />
<OutputClaim ClaimTypeReferenceId="givenName" PartnerClaimType="given_name" />
<OutputClaim ClaimTypeReferenceId="surName" PartnerClaimType="family_name" />
<OutputClaim ClaimTypeReferenceId="displayName" PartnerClaimType="name" />
<OutputClaim ClaimTypeReferenceId="userPrincipalName" PartnerClaimType="upn" />
<OutputClaim ClaimTypeReferenceId="authenticationSource"
DefaultValue="localAccountAuthentication" />
</OutputClaims>
</TechnicalProfile>
</TechnicalProfiles>
</ClaimsProvider>
<ClaimsProvider>
<DisplayName>Local Account Password Change</DisplayName>
<TechnicalProfiles>
<TechnicalProfile Id="LocalAccountWritePasswordChangeUsingObjectId">
<DisplayName>Change password (username)</DisplayName>
<Protocol Name="Proprietary" Handler="Web.TPEngine.Providers.SelfAssertedAttributeProvider,
Web.TPEngine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
<Metadata>
<Item Key="ContentDefinitionReferenceId">api.selfasserted</Item>
</Metadata>
<CryptographicKeys>
<Key Id="issuer_secret" StorageReferenceId="B2C_1A_TokenSigningKeyContainer" />
</CryptographicKeys>
<InputClaims>
<InputClaim ClaimTypeReferenceId="objectId" />
</InputClaims>
<OutputClaims>
<OutputClaim ClaimTypeReferenceId="oldPassword" Required="true" />
<OutputClaim ClaimTypeReferenceId="newPassword" Required="true" />
<OutputClaim ClaimTypeReferenceId="reenterPassword" Required="true" />
</OutputClaims>
<ValidationTechnicalProfiles>
<ValidationTechnicalProfile ReferenceId="login-NonInteractive-PasswordChange" />
<ValidationTechnicalProfile ReferenceId="AAD-UserWritePasswordUsingObjectId" />
</ValidationTechnicalProfiles>
</TechnicalProfile>
</TechnicalProfiles>
</ClaimsProvider>
</ClaimsProviders>
<UserJourneys>
<UserJourney Id="PasswordChange">
<OrchestrationSteps>
<OrchestrationStep Order="1" Type="ClaimsProviderSelection"
ContentDefinitionReferenceId="api.idpselections">
<ClaimsProviderSelections>
<ClaimsProviderSelection TargetClaimsExchangeId="LocalAccountSigninEmailExchange" />
</ClaimsProviderSelections>
</OrchestrationStep>
<OrchestrationStep Order="2" Type="ClaimsExchange">
<ClaimsExchanges>
<ClaimsExchange Id="LocalAccountSigninEmailExchange"
TechnicalProfileReferenceId="SelfAsserted-LocalAccountSignin-Email" />
</ClaimsExchanges>
</OrchestrationStep>
<OrchestrationStep Order="3" Type="ClaimsExchange">
<ClaimsExchanges>
<ClaimsExchange Id="NewCredentials"
TechnicalProfileReferenceId="LocalAccountWritePasswordChangeUsingObjectId" />
</ClaimsExchanges>
</OrchestrationStep>
<OrchestrationStep Order="4" Type="SendClaims" CpimIssuerTechnicalProfileReferenceId="JwtIssuer"
/>
</OrchestrationSteps>
<ClientDefinition ReferenceId="DefaultWeb" />
</UserJourney>
</UserJourneys>
Next steps
Learn about how you can Configure password complexity using custom policies in Azure Active Directory B2C.
Add claims and customize user input using custom
policies in Azure Active Directory B2C
12/9/2019 • 4 minutes to read • Edit Online
NOTE
In Azure Active Directory B2C, custom policies are designed primarily to address complex scenarios. For most scenarios, we
recommend that you use built-in user flows.
In this article, you add a new user provided entry (a claim) to your sign-up user journey in Azure Active Directory
B2C (Azure AD B2C ). You configure the entry as a dropdown and define whether it's required.
Prerequisites
Complete the steps in the article Getting Started with Custom Policies. Test the sign-up or sign-in user journey to
sign up a new local account before proceeding.
Add claims
Gathering initial data from your users is achieved using the sign-up or sign-in user journey. Additional claims can
be gathered later by using a profile edit user journey. Anytime Azure AD B2C gathers information directly from the
user interactively, the Identity Experience Framework uses its self-asserted provider.
Define the claim
Let's ask the user for their city. Add the following element to the ClaimsSchema element in the
TrustFrameworkBase policy file:
<ClaimType Id="city">
<DisplayName>city</DisplayName>
<DataType>string</DataType>
<UserHelpText>Your city</UserHelpText>
<UserInputType>TextBox</UserInputType>
</ClaimType>
<ClaimType Id="city">
<DisplayName>city where you work</DisplayName>
<DataType>string</DataType>
<UserHelpText>Your city</UserHelpText>
<UserInputType>TextBox</UserInputType>
</ClaimType>
RadioSingleSelect
<ClaimType Id="city">
<DisplayName>city where you work</DisplayName>
<DataType>string</DataType>
<UserInputType>RadioSingleSelect</UserInputType>
<Restriction>
<Enumeration Text="Bellevue" Value="bellevue" SelectByDefault="false" />
<Enumeration Text="Redmond" Value="redmond" SelectByDefault="false" />
<Enumeration Text="Kirkland" Value="kirkland" SelectByDefault="false" />
</Restriction>
</ClaimType>
DropdownSingleSelect
<ClaimType Id="city">
<DisplayName>city where you work</DisplayName>
<DataType>string</DataType>
<UserInputType>DropdownSingleSelect</UserInputType>
<Restriction>
<Enumeration Text="Bellevue" Value="bellevue" SelectByDefault="false" />
<Enumeration Text="Redmond" Value="redmond" SelectByDefault="false" />
<Enumeration Text="Kirkland" Value="kirkland" SelectByDefault="false" />
</Restriction>
</ClaimType>
CheckboxMultiSelect
<ClaimType Id="city">
<DisplayName>Receive updates from which cities?</DisplayName>
<DataType>string</DataType>
<UserInputType>CheckboxMultiSelect</UserInputType>
<Restriction>
<Enumeration Text="Bellevue" Value="bellevue" SelectByDefault="false" />
<Enumeration Text="Redmond" Value="redmond" SelectByDefault="false" />
<Enumeration Text="Kirkland" Value="kirkland" SelectByDefault="false" />
</Restriction>
</ClaimType>
3. Add the <OutputClaim ClaimTypeReferenceId="city" /> claim to the technical profiles that read from the
directory when a user signs in.
<TechnicalProfile Id="AAD-UserReadUsingEmailAddress">
<Metadata>
<Item Key="Operation">Read</Item>
<Item Key="RaiseErrorIfClaimsPrincipalDoesNotExist">true</Item>
<Item Key="UserMessageIfClaimsPrincipalDoesNotExist">An account could not be found for the provided
user ID.</Item>
</Metadata>
<IncludeInSso>false</IncludeInSso>
<InputClaims>
<InputClaim ClaimTypeReferenceId="email" PartnerClaimType="signInNames" Required="true" />
</InputClaims>
<OutputClaims>
<!-- Required claims -->
<OutputClaim ClaimTypeReferenceId="objectId" />
<OutputClaim ClaimTypeReferenceId="authenticationSource" DefaultValue="localAccountAuthentication"
/>
<!-- Optional claims -->
<OutputClaim ClaimTypeReferenceId="userPrincipalName" />
<OutputClaim ClaimTypeReferenceId="displayName" />
<OutputClaim ClaimTypeReferenceId="otherMails" />
<OutputClaim ClaimTypeReferenceId="signInNames.emailAddress" />
<OutputClaim ClaimTypeReferenceId="city" />
</OutputClaims>
<IncludeTechnicalProfile ReferenceId="AAD-Common" />
</TechnicalProfile>
<TechnicalProfile Id="AAD-UserReadUsingObjectId">
<Metadata>
<Item Key="Operation">Read</Item>
<Item Key="RaiseErrorIfClaimsPrincipalDoesNotExist">true</Item>
</Metadata>
<IncludeInSso>false</IncludeInSso>
<InputClaims>
<InputClaim ClaimTypeReferenceId="objectId" Required="true" />
</InputClaims>
<OutputClaims>
<!-- Optional claims -->
<OutputClaim ClaimTypeReferenceId="signInNames.emailAddress" />
<OutputClaim ClaimTypeReferenceId="displayName" />
<OutputClaim ClaimTypeReferenceId="otherMails" />
<OutputClaim ClaimTypeReferenceId="givenName" />
<OutputClaim ClaimTypeReferenceId="city" />
</OutputClaims>
<IncludeTechnicalProfile ReferenceId="AAD-Common" />
</TechnicalProfile>
4. Add the <OutputClaim ClaimTypeReferenceId="city" /> claim to the SignUporSignIn.xml file so that this claim
is sent to the application in the token after a successful user journey.
<RelyingParty>
<DefaultUserJourney ReferenceId="SignUpOrSignIn" />
<TechnicalProfile Id="PolicyProfile">
<DisplayName>PolicyProfile</DisplayName>
<Protocol Name="OpenIdConnect" />
<OutputClaims>
<OutputClaim ClaimTypeReferenceId="displayName" />
<OutputClaim ClaimTypeReferenceId="givenName" />
<OutputClaim ClaimTypeReferenceId="surname" />
<OutputClaim ClaimTypeReferenceId="email" />
<OutputClaim ClaimTypeReferenceId="objectId" PartnerClaimType="sub"/>
<OutputClaim ClaimTypeReferenceId="identityProvider" />
<OutputClaim ClaimTypeReferenceId="city" />
</OutputClaims>
<SubjectNamingInfo ClaimType="sub" />
</TechnicalProfile>
</RelyingParty>
{
"exp": 1493596822,
"nbf": 1493593222,
"ver": "1.0",
"iss": "https://contoso.b2clogin.com/f06c2fe8-709f-4030-85dc-38a4bfd9e82d/v2.0/",
"sub": "9c2a3a9e-ac65-4e46-a12d-9557b63033a9",
"aud": "4e87c1dd-e5f5-4ac8-8368-bc6a98751b8b",
"acr": "b2c_1a_trustf_signup_signin",
"nonce": "defaultNonce",
"iat": 1493593222,
"auth_time": 1493593222,
"email": "joe@outlook.com",
"given_name": "Joe",
"family_name": "Ras",
"city": "Bellevue",
"name": "unknown"
}
Next steps
Learn how to Use custom attributes in a custom profile edit policy.
Customize the user interface of your application
using a custom policy in Azure Active Directory B2C
12/9/2019 • 8 minutes to read • Edit Online
NOTE
In Azure Active Directory B2C, custom policies are designed primarily to address complex scenarios. For most scenarios, we
recommend that you use built-in user flows.
After you complete this article, you'll have a sign-up and sign-in custom policy with your brand and appearance.
With Azure Active Directory B2C (Azure AD B2C ), you get nearly full control of the HTML and CSS content that's
presented to users. When you use a custom policy, you configure UI customization in XML instead of using
controls in the Azure portal.
Prerequisites
Complete the steps in Get started with custom policies. You should have a working custom policy for sign-up and
sign-in with local accounts.
Page UI customization
By using the page UI customization feature, you can customize the look and feel of any custom policy. You can
also maintain brand and visual consistency between your application and Azure AD B2C.
Here's how it works: Azure AD B2C runs code in your customer's browser and uses a modern approach called
Cross-Origin Resource Sharing (CORS ). First, you specify a URL in the custom policy with customized HTML
content. Azure AD B2C merges UI elements with the HTML content that's loaded from your URL and then
displays the page to the customer.
<!DOCTYPE html>
<html>
<head>
<title>My Product Brand Name</title>
</head>
<body>
<div id="api"></div>
</body>
</html>
2. Paste the copied snippet in a text editor, and then save the file as customize-ui.html.
NOTE
HTML form elements will be removed due to security restrictions if you use login.microsoftonline.com. Please use
b2clogin.com if you want to use HTML form elements in your custom HTML content. See Use b2clogin.com for other
benefits.
To host this HTML content in Blob storage, perform the following steps:
1. Sign in to the Azure portal.
2. On the Hub menu, select New > Storage > Storage account.
3. Select a Subscription for your storage account.
4. Create a Resource group or select an existing one.
5. Enter a unique Name for your storage account.
6. Select the Geographic location for your storage account.
7. Deployment model can remain Resource Manager.
8. Performance can remain Standard.
9. Change Account Kind to Blob storage.
10. Replication can remain RA -GRS.
11. Access tier can remain Hot.
12. Click Review + create to create the storage account. After the deployment is completed, the Storage account
page opens automatically.
Create a container
To create a public container in Blob storage, perform the following steps:
1. Under Blob service in the left-hand menu, select Blobs.
2. Click +Container.
3. For Name, enter root. This can be a name of your choosing, for example wingtiptoys, but we use root in this
example for simplicity.
4. For Public access level, select Blob, then OK.
5. Click root to open the new container.
6. Click Upload.
7. Click the folder icon next to Select a file.
8. Navigate to and select customize-ui.html which you created earlier in the Page UI customization section.
9. If you want to upload to a subfolder, expand Advanced and enter a folder name in Upload to folder.
10. Select Upload.
11. Select the customize-ui.html blob that you uploaded.
12. To the right of the URL text box, select the Copy to clipboard icon to copy the URL to your clipboard.
13. In web browser, navigate to the URL you copied to verify the blob you uploaded is accessible. If it is
inaccessible, for example if you encounter a ResourceNotFound error, make sure the container access type is set
to blob.
Configure CORS
Configure Blob storage for Cross-Origin Resource Sharing by performing the following steps:
1. In the menu, select CORS.
2. For Allowed origins, enter https://your-tenant-name.b2clogin.com . Replace your-tenant-name with the name
of your Azure AD B2C tenant. For example, https://fabrikam.b2clogin.com . You need to use all lowercase
letters when entering your tenant name.
3. For Allowed Methods, select both GET and OPTIONS .
4. For Allowed Headers, enter an asterisk (*).
5. For Exposed Headers, enter an asterisk (*).
6. For Max age, enter 200.
7. Click Save.
Test CORS
Validate that you're ready by performing the following steps:
1. Go to the www.test-cors.org website, and then paste the URL in the Remote URL box.
2. Click Send Request. If you receive an error, make sure that your CORS settings are correct. You might also
need to clear your browser cache or open an in-private browsing session by pressing Ctrl+Shift+P.
Reference
Sample templates
You can find sample templates for UI customization here:
selfasserted.html Use this file as a template for a social account sign-up page, a
local account sign-up page, or a local account sign-in page.
api.localaccountpasswordreset Forgot password page. This page contains a form that the
user must complete to initiate a password reset.
api.selfasserted.profileupdate Profile update page. This page contains a form that users
can use to update their profile. This page is similar to the
social account sign-up page, except for the password entry
fields.
Next steps
For more information about UI elements that can be customized, see reference guide for UI customization for
user flows.
Azure Active Directory B2C: Configure the UI with
dynamic content by using custom policies
12/9/2019 • 11 minutes to read • Edit Online
NOTE
In Azure Active Directory B2C, custom policies are designed primarily to address complex scenarios. For most scenarios, we
recommend that you use built-in user flows.
By using Azure Active Directory B2C (Azure AD B2C ) custom policies, you can send a parameter in a query string.
By passing the parameter to your HTML endpoint, you can dynamically change the page content. For example,
you can change the background image on the Azure AD B2C sign-up or sign-in page, based on a parameter that
you pass from your web or mobile application.
Prerequisites
This article focuses on how to customize the Azure AD B2C user interface with dynamic content by using custom
policies. To get started, see UI customization in a custom policy.
NOTE
The Azure AD B2C article, Configure UI customization in a custom policy, discusses the following fundamentals:
The page user interface (UI) customization feature.
Essential tools for testing the page UI customization feature by using our sample content.
The core UI elements of each page type.
Best practices for applying this feature.
2. In the Add New Item - Contoso.AADB2C.UI window, select Web > ASP.NET.
3. Select MVC View Page.
4. In the Name box, change the name to unified.cshtml.
5. Select Add.
6. If the unified.cshtml file is not open already, double-click the file to open it, and then clear the file contents.
7. For this walkthrough, we remove the reference to layout-page. Add the following code snippet to
unified.cshtml:
@{
Layout = null;
}
8. Open the unified.cshtml file you downloaded from Azure AD B2C built-in HTML5 template.
9. Replace the single at signs (@) with double at signs (@@).
10. Copy the content of the file and paste it below the Layout definition. Your code should look like:
Step 2.3: Change the background image
Locate the <img> element that contains the ID value background_background_image, and then replace the src
value with https://kbdevstorage1.blob.core.windows.net/asset-blobs/19889_en_1 or any other background
image you want to use.
This code specifies that the method should use a View template file to render a response to the browser.
Because we don't explicitly specify the name of the View template file, MVC defaults to using the
unified.cshtml View file in the /Views/Home folder.
After you add the unified method, your code should look like:
2. Debug your web app, and make sure that the unified page is accessible (for example,
http://localhost:<Port number>/Home/unified ).
2. Select the Microsoft Azure App Service tile, and then select Publish.
The Create App Service window opens. In it you can begin to create all the necessary Azure resources to
run the ASP.NET web app in Azure.
NOTE
For more information about publishing, see Create an ASP.NET web app in Azure.
3. In the Web App Name box, type a unique app name (valid characters are a-z, A-Z, 0-9, and the hyphen (-).
The URL of the web app is http://<app_name>.azurewebsites.NET , where <app_name> is your web app name.
You can accept the automatically generated name, which is unique.
4. Select Create to start creating the Azure resources.
After the creation process is complete, the wizard publishes the ASP.NET web app to Azure and then
launches the app in the default browser.
5. Copy the URL of the unified page (for example, https://<app_name>.azurewebsites.net/home/unified).
3. In the CORS window, in the Allowed Origins box, do either of the following:
Enter the URL or URLs that you want to allow JavaScript calls to come from. You need to use all
lowercase letters in the URLs that you enter.
Enter an asterisk (*) to specify that all origin domains are accepted.
4. Select Save.
After you select Save, the API app accepts JavaScript calls from the specified URLs.
NOTE
To verify that the site where you're hosting your content has enabled CORS and can test CORS requests, go to the
test-cors.org website.
4. Paste the entire contents of the <ContentDefinitions> node that you copied as a child of the
<BuildingBlocks> element.
5. Search for the <ContentDefinition> node that contains Id="api.signuporsignin" in the XML that you
copied.
6. Change the value of LoadUri from ~/tenant/default/unified to
https://<app_name>.azurewebsites.net/home/unified. Your custom policy should look like the following:
NOTE
Run Now requires at least one application to be preregistered on the tenant. To learn how to register applications,
see the Azure AD B2C Get started article or the Application registration article.
2. Open B2C_1A_signup_signin, the relying party (RP ) custom policy that you uploaded, and then select
Run now. You should be able to see your custom HTML5 with the background that you created earlier.
Step 8: Add dynamic content
Change the background based on query string parameter named campaignId. Your RP application (web and
mobile apps) sends the parameter to Azure AD B2C. Your policy reads the parameter and sends its value to your
HTML5 template.
Step 8.1: Add a content definition parameter
Add the ContentDefinitionParameters element by doing the following:
1. Open the SignUpOrSignin file of your policy (for example, SignUpOrSignin.xml).
2. Under the <DefaultUserJourney> node, add the UserJourneyBehaviors node:
<RelyingParty>
<DefaultUserJourney ReferenceId="SignUpOrSignIn" />
<UserJourneyBehaviors>
<ContentDefinitionParameters>
<Parameter Name="campaignId">{OAUTH-KV:campaignId}</Parameter>
</ContentDefinitionParameters>
</UserJourneyBehaviors>
...
</RelyingParty>
Step 8.2: Change your code to accept a query string parameter, and replace the background image
Modify the HomeController unified method to accept the campaignId parameter. The method then checks the
parameter's value and sets the ViewData["background"] variable accordingly.
1. Open the Controllers\HomeController.cs file, and then change the unified method by adding the following
code snippet:
public IActionResult unified(string campaignId)
{
// If campaign ID is Hawaii, show Hawaii background
if (campaignId != null && campaignId.ToLower() == "hawaii")
{
ViewData["background"] = "https://kbdevstorage1.blob.core.windows.net/asset-blobs/19889_en_1";
}
// If campaign ID is Tokyo, show Tokyo background
else if (campaignId != null && campaignId.ToLower() == "tokyo")
{
ViewData["background"] = "https://kbdevstorage1.blob.core.windows.net/asset-blobs/19666_en_1";
}
// Default background
else
{
ViewData["background"] = "https://kbdevstorage1.blob.core.windows.net/asset-blobs/18983_en_1";
}
return View();
}
2. Locate the <img>element with ID background_background_image , and replace the src value with
@ViewData["background"] .
Use custom email in Azure Active Directory B2C (Azure AD B2C ) to send customized email to users that sign up to
use your applications. By using DisplayControls (currently in preview ) and a third-party email provider, you can use
your own email template and From: address and subject, as well as support localization and custom one-time
password (OTP ) settings.
Custom email verification requires the use of a third-party email provider like SendGrid or SparkPost, a custom
REST API, or any HTTP -based email provider (including your own). This article describes setting up a solution that
uses SendGrid.
NOTE
This feature is in public preview.
</td>
<td width="1"> </td>
<td width="1"></td>
<td width="1"> </td>
<td width="1" valign="top"></td>
<td width="29"> </td>
<td width="1" style="background:#e3e3e3;"></td>
</tr>
<tr>
<td width="1" style="background:#e3e3e3; border-bottom:1px solid #e3e3e3;"></td>
<td width="24" style="border-bottom:1px solid #e3e3e3;"> </td>
<td id="PageFooterContainer" width="585" valign="top" colspan="6" style="border-
bottom:1px solid #e3e3e3;padding:0px;">
</td>
</td>
<td valign="top" width="50%"></td>
</tr>
</table>
<img src="https://mucp.api.account.microsoft.com/m/v2/v?
d=AIAACWEPFYXYIUTJIJVV4ST7XLBHVI5MLLYBKJAVXHBDTBHUM5VBSVVPTTVRWDFIXJ5JQTHYOH5TUYIPO4ZAFRFK52UAMIS3UNIPPI
7ZJNDZPRXD5VEJBN4H6RO3SPTBS6AJEEAJOUYL4APQX5RJUJOWGPKUABY&i=AIAACL23GD2PFRFEY5YVM2XQLM5YYWMHFDZOCDXU
I2B4LM7ETZQO473CVF22PT6WPGR5IIE6TCS6VGEKO5OZIONJWCDMRKWQQVNP5VBYAINF3S7STKYOVDJ4JF2XEW4QQVNHMAPQNHFV3KMR
3V3BA4I36B6BO7L4VQUHQOI64EOWPLMG5RB3SIMEDEHPILXTF73ZYD3JT6MYOLAZJG7PJJCAXCZCQOEFVH5VCW2KBQOKRYISWQLRWAT7
IINZ3EFGQI2CY2EMK3FQOXM7UI3R7CZ6D73IKDI" width="1" height="1"></body>
</html>
Create a DisplayControl
A verification display control is used to verify the email address with a verification code that's sent to the user.
This example display control is configured to:
1. Collect the email address claim type from the user.
2. Wait for the user to provide the verificationCode claim type with the code sent to the user.
3. Return the email back to the self-asserted technical profile that has a reference to this display control.
4. Using the SendCode action, generate an OTP code and send an email with the OTP code to the user.
Under ClaimsSchema, add the following DisplayControl of type VerificationControl to your policy.
<DisplayControls>
<DisplayControl Id="emailVerificationControl" UserInterfaceControlType="VerificationControl">
<DisplayClaims>
<DisplayClaim ClaimTypeReferenceId="email" Required="true" />
<DisplayClaim ClaimTypeReferenceId="verificationCode" ControlClaimType="VerificationCode" Required="true"
/>
</DisplayClaims>
<OutputClaims>
<OutputClaim ClaimTypeReferenceId="email" />
</OutputClaims>
<Actions>
<Action Id="SendCode">
<ValidationClaimsExchange>
<ValidationClaimsExchangeTechnicalProfile TechnicalProfileReferenceId="GenerateOtp" />
<ValidationClaimsExchangeTechnicalProfile TechnicalProfileReferenceId="SendGrid" />
</ValidationClaimsExchange>
</Action>
<Action Id="VerifyCode">
<ValidationClaimsExchange>
<ValidationClaimsExchangeTechnicalProfile TechnicalProfileReferenceId="VerifyOtp" />
</ValidationClaimsExchange>
</Action>
</Actions>
</DisplayControl>
</DisplayControls>
Add OTP technical profiles
The GenerateOtp technical profile generates a code for the email address. The VerifyOtp technical profile verifies
the code associated with the email address. You can change the configuration of the format and the expiration of
the one-time password. For more information about OTP technical profiles, see Define a one-time password
technical profile.
<ClaimsProvider>
<DisplayName>One time password technical profiles</DisplayName>
<TechnicalProfiles>
<TechnicalProfile Id="GenerateOtp">
<DisplayName>Generate one time password</DisplayName>
<Protocol Name="Proprietary" Handler="Web.TPEngine.Providers.OneTimePasswordProtocolProvider,
Web.TPEngine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
<Metadata>
<Item Key="Operation">GenerateCode</Item>
<Item Key="CodeExpirationInSeconds">1200</Item>
<Item Key="CodeLength">6</Item>
<Item Key="CharacterSet">0-9</Item>
<Item Key="ReuseSameCode">true</Item>
<Item Key="MaxNumAttempts">5</Item>
</Metadata>
<InputClaims>
<InputClaim ClaimTypeReferenceId="email" PartnerClaimType="identifier" />
</InputClaims>
<OutputClaims>
<OutputClaim ClaimTypeReferenceId="otp" PartnerClaimType="otpGenerated" />
</OutputClaims>
</TechnicalProfile>
<TechnicalProfile Id="VerifyOtp">
<DisplayName>Verify one time password</DisplayName>
<Protocol Name="Proprietary" Handler="Web.TPEngine.Providers.OneTimePasswordProtocolProvider,
Web.TPEngine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
<Metadata>
<Item Key="Operation">VerifyCode</Item>
<Item Key="UserMessage.VerificationHasExpired">You have exceed the maximum time allowed.</Item>
<Item Key="UserMessage.MaxRetryAttemped">You have exceed the number of retries allowed.</Item>
<Item Key="UserMessage.InvalidCode">You have entered the wrong code.</Item>
<Item Key="UserMessage.ServerError">Cannot verify the code, please try again later.</Item>
</Metadata>
<InputClaims>
<InputClaim ClaimTypeReferenceId="email" PartnerClaimType="identifier" />
<InputClaim ClaimTypeReferenceId="verificationCode" PartnerClaimType="otpToVerify" />
</InputClaims>
</TechnicalProfile>
</ClaimsProviders>
<TechnicalProfile Id="LocalAccountSignUpWithLogonEmail">
<DisplayName>Email signup</DisplayName>
<Protocol Name="Proprietary" Handler="Web.TPEngine.Providers.SelfAssertedAttributeProvider, Web.TPEngine,
Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
<Metadata>
<Item Key="IpAddressClaimReferenceId">IpAddress</Item>
<Item Key="ContentDefinitionReferenceId">api.localaccountsignup</Item>
<Item Key="language.button_continue">Create</Item>
</Metadata>
<InputClaims>
<InputClaim ClaimTypeReferenceId="email" />
</InputClaims>
<DisplayClaims>
<DisplayClaim DisplayControlReferenceId="emailVerificationControl" />
<DisplayClaim DisplayControlReferenceId="SecondaryEmailVerificationControl" />
<DisplayClaim ClaimTypeReferenceId="displayName" Required="true" />
<DisplayClaim ClaimTypeReferenceId="givenName" Required="true" />
<DisplayClaim ClaimTypeReferenceId="surName" Required="true" />
<DisplayClaim ClaimTypeReferenceId="newPassword" Required="true" />
<DisplayClaim ClaimTypeReferenceId="reenterPassword" Required="true" />
</DisplayClaims>
<OutputClaims>
<OutputClaim ClaimTypeReferenceId="email" Required="true" />
<OutputClaim ClaimTypeReferenceId="objectId" />
<OutputClaim ClaimTypeReferenceId="executed-SelfAsserted-Input" DefaultValue="true" />
<OutputClaim ClaimTypeReferenceId="authenticationSource" />
<OutputClaim ClaimTypeReferenceId="newUser" />
</OutputClaims>
<ValidationTechnicalProfiles>
<ValidationTechnicalProfile ReferenceId="AAD-UserWriteUsingLogonEmail" />
</ValidationTechnicalProfiles>
<UseTechnicalProfileForSessionManagement ReferenceId="SM-AAD" />
</TechnicalProfile>
Next steps
For information about using a custom REST API or any HTTP -based SMTP email provider, see Define a RESTful
technical profile in an Azure AD B2C custom policy.
Select a page layout in Azure Active Directory B2C using
custom policies
10/15/2019 • 2 minutes to read • Edit Online
NOTE
This feature is in public preview.
You can enable JavaScript client-side code in your Azure Active Directory B2C (Azure AD B2C ) policies whether you’re
using user flows or custom policies. To enable JavaScript for your applications, you must add an element to your custom
policy, select a page layout, and use b2clogin.com in your requests.
A page layout is an association of elements that Azure AD B2C provides and the content that you provide.
This article discusses how to select a page layout in Azure AD B2C by configuring it in a custom policy.
NOTE
If you want to enable JavaScript for user flows, see JavaScript and page layout versions in Azure Active Directory B2C.
<ContentDefinition Id="api.idpselections">
<LoadUri>~/tenant/default/idpSelector.cshtml</LoadUri>
<RecoveryUri>~/common/default_page_error.html</RecoveryUri>
<DataUri>urn:com:microsoft:aad:b2c:elements:contract:providerselection:1.0.0</DataUri>
<Metadata>
<Item Key="DisplayName">Idp selection page</Item>
<Item Key="language.intro">Sign in</Item>
</Metadata>
</ContentDefinition>
To select a page layout, you change the DataUri values in your ContentDefinitions in your policies. By switching from
the old DataUri values to the new values, you're selecting an immutable package. The benefit of using this package is
that you’ll know it won't change and cause unexpected behavior on your page.
To set up a page layout, use the following table to find DataUri values.
urn:com:microsoft:aad:b2c:elements:claimsconsent:1.0.0 urn:com:microsoft:aad:b2c:elements:contract:claimsconsent:1.0.0
urn:com:microsoft:aad:b2c:elements:globalexception:1.0.0 urn:com:microsoft:aad:b2c:elements:contract:globalexception:1.0.0
urn:com:microsoft:aad:b2c:elements:globalexception:1.1.0 urn:com:microsoft:aad:b2c:elements:contract:globalexception:1.1.0
urn:com:microsoft:aad:b2c:elements:idpselection:1.0.0 urn:com:microsoft:aad:b2c:elements:contract:providerselection:1.0.0
OLD DATAURI VALUE NEW DATAURI VALUE
urn:com:microsoft:aad:b2c:elements:multifactor:1.0.0 urn:com:microsoft:aad:b2c:elements:contract:multifactor:1.0.0
urn:com:microsoft:aad:b2c:elements:multifactor:1.1.0 urn:com:microsoft:aad:b2c:elements:contract:multifactor:1.1.0
urn:com:microsoft:aad:b2c:elements:selfasserted:1.0.0 urn:com:microsoft:aad:b2c:elements:contract:selfasserted:1.0.0
urn:com:microsoft:aad:b2c:elements:selfasserted:1.1.0 urn:com:microsoft:aad:b2c:elements:contract:selfasserted:1.1.0
urn:com:microsoft:aad:b2c:elements:unifiedssd:1.0.0 urn:com:microsoft:aad:b2c:elements:contract:unifiedssd:1.0.0
urn:com:microsoft:aad:b2c:elements:unifiedssp:1.0.0 urn:com:microsoft:aad:b2c:elements:contract:unifiedssp:1.0.0
urn:com:microsoft:aad:b2c:elements:unifiedssp:1.1.0 urn:com:microsoft:aad:b2c:elements:contract:unifiedssp:1.1.0
Next steps
Find more information about how you can customize the user interface of your applications in Customize the user
interface of your application using a custom policy in Azure Active Directory B2C.
JavaScript samples for use in Azure Active Directory
B2C
9/17/2019 • 3 minutes to read • Edit Online
NOTE
This feature is in public preview.
You can add your own JavaScript client-side code to your Azure Active Directory B2C (Azure AD B2C )
applications. To enable JavaScript for your applications, you must add an element to your custom policy, select a
page layout, and use b2clogin.com in your requests. This article describes how you can change your custom policy
to enable script execution.
NOTE
If you want to enable JavaScript for user flows, see JavaScript and page layout versions in Azure Active Directory B2C.
Prerequisites
Select a page layout for the user interface elements of your application. If you intend to use JavaScript, you need
to define a page layout version for all of your content definitions in your custom policy.
<RelyingParty>
<DefaultUserJourney ReferenceId="B2CSignUpOrSignInWithPassword" />
<UserJourneyBehaviors>
<ScriptExecution>Allow</ScriptExecution>
</UserJourneyBehaviors>
...
</RelyingParty>
JavaScript samples
Show or hide a password
A common way to help your customers with their sign-up success is to allow them to see what they’ve entered as
their password. This option helps users sign up by enabling them to easily see and make corrections to their
password if needed. Any field of type password has a checkbox with a Show password label. This enables the
user to see the password in plain text. Include this code snippet into your sign-up or sign-in template for a self-
asserted page:
function makePwdToggler(pwd){
// Create show-password checkbox
var checkbox = document.createElement('input');
checkbox.setAttribute('type', 'checkbox');
var id = pwd.id + 'toggler';
checkbox.setAttribute('id', id);
function setupPwdTogglers(){
var pwdInputs = document.querySelectorAll('input[type=password]');
for (var i = 0; i < pwdInputs.length; i++) {
makePwdToggler(pwdInputs[i]);
}
}
setupPwdTogglers();
In the code, replace termsOfUseUrl with the link to your terms of use agreement. For your directory, create a new
user attribute called termsOfUse and then include termsOfUse as a user attribute.
Next steps
Find more information about how you can customize the user interface of your applications in Customize the user
interface of your application using a custom policy in Azure Active Directory B2C.
Configure password complexity using custom policies
in Azure Active Directory B2C
12/9/2019 • 2 minutes to read • Edit Online
NOTE
In Azure Active Directory B2C, custom policies are designed primarily to address complex scenarios. For most scenarios, we
recommend that you use built-in user flows.
In Azure Active Directory B2C (Azure AD B2C ), you can configure the complexity requirements for passwords that
are provided by a user when creating an account. By default, Azure AD B2C uses Strong passwords. This article
shows you how to configure password complexity in custom policies. It's also possible to configure password
complexity in user flows.
Prerequisites
Complete the steps in Get started with custom policies in Active Directory B2C.
<ClaimsSchema>
<ClaimType Id="newPassword">
<InputValidationReference Id="PasswordValidation" />
</ClaimType>
<ClaimType Id="reenterPassword">
<InputValidationReference Id="PasswordValidation" />
</ClaimType>
</ClaimsSchema>
4. Predicates have method types of IsLengthRange or MatchesRegex . The MatchesRegex type is used to match
a regular expression. The IsLengthRange type takes a minimum and maximum string length. Add a
Predicates element to the BuildingBlocks element if it doesn't exist with the following Predicate
elements:
<Predicates>
<Predicate Id="PIN" Method="MatchesRegex" HelpText="The password must be a pin.">
<Parameters>
<Parameter Id="RegularExpression">^[0-9]+$</Parameter>
</Parameters>
</Predicate>
<Predicate Id="Length" Method="IsLengthRange" HelpText="The password must be between 8 and 16
characters.">
<Parameters>
<Parameter Id="Minimum">8</Parameter>
<Parameter Id="Maximum">16</Parameter>
</Parameters>
</Predicate>
</Predicates>
5. Each InputValidation element is constructed by using the defined Predicate elements. This element
allows you to perform boolean aggregations that are similar to and and or . Add an InputValidations
element to the BuildingBlocks element if it doesn't exist with the following InputValidation element:
<InputValidations>
<InputValidation Id="PasswordValidation">
<PredicateReferences Id="LengthGroup" MatchAtLeast="1">
<PredicateReference Id="Length" />
</PredicateReferences>
<PredicateReferences Id="3of4" MatchAtLeast="3" HelpText="You must have at least 3 of the following
character classes:">
<PredicateReference Id="Lowercase" />
<PredicateReference Id="Uppercase" />
<PredicateReference Id="Number" />
<PredicateReference Id="Symbol" />
</PredicateReferences>
</InputValidation>
</InputValidations>
6. Make sure that the PolicyProfile technical profile contains the following elements:
<RelyingParty>
<DefaultUserJourney ReferenceId="SignUpOrSignIn"/>
<TechnicalProfile Id="PolicyProfile">
<DisplayName>PolicyProfile</DisplayName>
<Protocol Name="OpenIdConnect"/>
<InputClaims>
<InputClaim ClaimTypeReferenceId="passwordPolicies" DefaultValue="DisablePasswordExpiration,
DisableStrongPassword"/>
</InputClaims>
<OutputClaims>
<OutputClaim ClaimTypeReferenceId="displayName"/>
<OutputClaim ClaimTypeReferenceId="givenName"/>
<OutputClaim ClaimTypeReferenceId="surname"/>
<OutputClaim ClaimTypeReferenceId="email"/>
<OutputClaim ClaimTypeReferenceId="objectId" PartnerClaimType="sub"/>
</OutputClaims>
<SubjectNamingInfo ClaimType="sub"/>
</TechnicalProfile>
</RelyingParty>
Next steps
Learn how to Configure password change using custom policies in Azure Active Directory B2C.
Set up sign-in with an Amazon account using custom
policies in Azure Active Directory B2C
12/9/2019 • 6 minutes to read • Edit Online
NOTE
In Azure Active Directory B2C, custom policies are designed primarily to address complex scenarios. For most scenarios, we
recommend that you use built-in user flows.
This article shows you how to enable sign-in for users from an Amazon account by using custom policies in Azure
Active Directory B2C (Azure AD B2C ).
Prerequisites
Complete the steps in Get started with custom policies.
If you don't already have an Amazon account, create one at https://www.amazon.com/.
<ClaimsProvider>
<Domain>amazon.com</Domain>
<DisplayName>Amazon</DisplayName>
<TechnicalProfiles>
<TechnicalProfile Id="Amazon-OAUTH">
<DisplayName>Amazon</DisplayName>
<Protocol Name="OAuth2" />
<Metadata>
<Item Key="ProviderName">amazon</Item>
<Item Key="authorization_endpoint">https://www.amazon.com/ap/oa</Item>
<Item Key="AccessTokenEndpoint">https://api.amazon.com/auth/o2/token</Item>
<Item Key="ClaimsEndpoint">https://api.amazon.com/user/profile</Item>
<Item Key="scope">profile</Item>
<Item Key="HttpBinding">POST</Item>
<Item Key="UsePolicyInRedirectUri">0</Item>
<Item Key="client_id">Your Amazon application client ID</Item>
</Metadata>
<CryptographicKeys>
<Key Id="client_secret" StorageReferenceId="B2C_1A_AmazonSecret" />
</CryptographicKeys>
<OutputClaims>
<OutputClaim ClaimTypeReferenceId="issuerUserId" PartnerClaimType="user_id" />
<OutputClaim ClaimTypeReferenceId="email" PartnerClaimType="email" />
<OutputClaim ClaimTypeReferenceId="displayName" PartnerClaimType="name" />
<OutputClaim ClaimTypeReferenceId="identityProvider" DefaultValue="amazon.com" />
<OutputClaim ClaimTypeReferenceId="authenticationSource" DefaultValue="socialIdpAuthentication" />
</OutputClaims>
<OutputClaimsTransformations>
<OutputClaimsTransformation ReferenceId="CreateRandomUPNUserName" />
<OutputClaimsTransformation ReferenceId="CreateUserPrincipalName" />
<OutputClaimsTransformation ReferenceId="CreateAlternativeSecurityId" />
</OutputClaimsTransformations>
<UseTechnicalProfileForSessionManagement ReferenceId="SM-SocialLogin" />
</TechnicalProfile>
</TechnicalProfiles>
</ClaimsProvider>
Update the value of TechnicalProfileReferenceId to the ID of the technical profile you created earlier. For
example, Amazon-OAuth .
3. Save the TrustFrameworkExtensions.xml file and upload it again for verification.
NOTE
In Azure Active Directory B2C, custom policies are designed primarily to address complex scenarios. For most scenarios, we
recommend that you use built-in user flows.
This article shows you how to enable sign-in for users from an Azure Active Directory (Azure AD ) organization by
using custom policies in Azure Active Directory B2C (Azure AD B2C ).
Prerequisites
Complete the steps in Get started with custom policies in Azure Active Directory B2C.
Register an application
To enable sign-in for users from a specific Azure AD organization, you need to register an application within the
organizational Azure AD tenant.
1. Sign in to the Azure portal.
2. Make sure you're using the directory that contains your organizational Azure AD tenant (for example,
contoso.com). Select the Directory + subscription filter in the top menu, and then choose the directory
that contains your Azure AD tenant.
3. Choose All services in the top-left corner of the Azure portal, and then search for and select App
registrations.
4. Select New registration.
5. Enter a Name for your application. For example, Azure AD B2C App .
6. Accept the default selection of Accounts in this organizational directory only for this application.
7. For the Redirect URI, accept the value of Web, and enter the following URL in all lowercase letters, where
your-B2C-tenant-name is replaced with the name of your Azure AD B2C tenant.
https://your-B2C-tenant-name.b2clogin.com/your-B2C-tenant-name.onmicrosoft.com/oauth2/authresp
4. Under the ClaimsProvider element, update the value for Domain to a unique value that can be used to
distinguish it from other identity providers. For example Contoso . You don't put a .com at the end of this
domain setting.
5. Under the ClaimsProvider element, update the value for DisplayName to a friendly name for the claims
provider. This value is not currently used.
Update the technical profile
To get a token from the Azure AD endpoint, you need to define the protocols that Azure AD B2C should use to
communicate with Azure AD. This is done inside the TechnicalProfile element of ClaimsProvider.
1. Update the ID of the TechnicalProfile element. This ID is used to refer to this technical profile from other
parts of the policy.
2. Update the value for DisplayName. This value will be displayed on the sign-in button on your sign-in screen.
3. Update the value for Description.
4. Azure AD uses the OpenID Connect protocol, so make sure that the value for Protocol is OpenIdConnect .
5. Set value of the METADATA to
https://login.windows.net/your-AD-tenant-name.onmicrosoft.com/.well-known/openid-configuration , where
your-AD-tenant-name is your Azure AD tenant name. For example,
https://login.windows.net/fabrikam.onmicrosoft.com/.well-known/openid-configuration
6. Open your browser and go to the METADATA URL that you just updated, look for the issuer object, and then
copy and paste the value into the value for ProviderName in the XML file.
7. Set client_id to the application ID from the application registration.
8. Under CryptographicKeys, update the value of StorageReferenceId to the name of the policy key that you
created earlier. For example, B2C_1A_ContosoAppSecret .
Upload the extension file for verification
By now, you have configured your policy so that Azure AD B2C knows how to communicate with your Azure AD
directory. Try uploading the extension file of your policy just to confirm that it doesn't have any issues so far.
1. On the Custom Policies page in your Azure AD B2C tenant, select Upload Policy.
2. Enable Overwrite the policy if it exists, and then browse to and select the TrustFrameworkExtensions.xml
file.
3. Click Upload.
Update the value of TechnicalProfileReferenceId to the Id of the technical profile you created earlier. For
example, ContosoProfile .
3. Save the TrustFrameworkExtensions.xml file and upload it again for verification.
Next steps
When working with custom policies, you might sometimes need additional information when troubleshooting a
policy during its development.
To help diagnose issues, you can temporarily put the policy into "developer mode" and collect logs with Azure
Application Insights. Find out how in Azure Active Directory B2C: Collecting Logs.
Set up sign-in for multi-tenant Azure Active Directory
using custom policies in Azure Active Directory B2C
12/9/2019 • 9 minutes to read • Edit Online
NOTE
In Azure Active Directory B2C, custom policies are designed primarily to address complex scenarios. For most scenarios, we
recommend that you use built-in user flows.
This article shows you how to enable sign-in for users using the multi-tenant endpoint for Azure Active Directory
(Azure AD ) by using custom policies in Azure AD B2C. This allows users from multiple Azure AD tenants to sign in
using Azure AD B2C, without you having to configure an identity provider for each tenant. However, guest
members in any of these tenants will not be able to sign in. For that, you need to individually configure each
tenant.
Prerequisites
Complete the steps in Get started with custom policies in Azure Active Directory B2C.
Register an application
To enable sign-in for users from a specific Azure AD organization, you need to register an application within the
organizational Azure AD tenant.
1. Sign in to the Azure portal.
2. Make sure you're using the directory that contains your organizational Azure AD tenant (for example,
contoso.com). Select the Directory + subscription filter in the top menu, and then choose the directory
that contains your tenant.
3. Choose All services in the top-left corner of the Azure portal, and then search for and select App
registrations.
4. Select New registration.
5. Enter a Name for your application. For example, Azure AD B2C App .
6. Select Accounts in any organizational directory for this application.
7. For the Redirect URI, accept the value of Web, and enter the following URL in all lowercase letters, where
your-B2C-tenant-name is replaced with the name of your Azure AD B2C tenant.
https://your-B2C-tenant-name.b2clogin.com/your-B2C-tenant-name.onmicrosoft.com/oauth2/authresp
4. Under the ClaimsProvider element, update the value for Domain to a unique value that can be used to
distinguish it from other identity providers.
5. Under the TechnicalProfile element, update the value for DisplayName, for example, Contoso Employee .
This value is displayed on the sign-in button on your sign-in page.
6. Set client_id to the application ID of the Azure AD multi-tenant application that you registered earlier.
7. Under CryptographicKeys, update the value of StorageReferenceId to the name of the policy key that
created earlier. For example, B2C_1A_AADAppSecret .
Restrict access
NOTE
Using https://login.microsoftonline.com/ as the value for ValidTokenIssuerPrefixes allows all Azure AD users to sign
in to your application.
You need to update the list of valid token issuers and restrict access to a specific list of Azure AD tenant users who
can sign in.
To obtain the values, look at the OpenID Connect discovery metadata for each of the Azure AD tenants that you
would like to have users sign in from. The format of the metadata URL is similar to
https://login.microsoftonline.com/your-tenant/v2.0/.well-known/openid-configuration , where your-tenant is your
Azure AD tenant name. For example:
https://login.microsoftonline.com/fabrikam.onmicrosoft.com/v2.0/.well-known/openid-configuration
Perform these steps for each Azure AD tenant that should be used to sign in:
1. Open your browser and go to the OpenID Connect metadata URL for the tenant. Find the issuer object and
record its value. It should look similar to
https://login.microsoftonline.com/00000000-0000-0000-0000-000000000000/ .
2. Copy and paste the value into the ValidTokenIssuerPrefixes key. Separate multiple issuers with a comma. An
example with two issuers appears in the previous ClaimsProvider XML sample.
Upload the extension file for verification
By now, you have configured your policy so that Azure AD B2C knows how to communicate with your Azure AD
directories. Try uploading the extension file of your policy just to confirm that it doesn't have any issues so far.
1. On the Custom Policies page in your Azure AD B2C tenant, select Upload Policy.
2. Enable Overwrite the policy if it exists, and then browse to and select the TrustFrameworkExtensions.xml file.
3. Select Upload.
Update the value of TechnicalProfileReferenceId to the Id of the technical profile you created earlier. For
example, Common-AAD .
3. Save the TrustFrameworkExtensions.xml file and upload it again for verification.
Next steps
When working with custom policies, you might sometimes need additional information when troubleshooting a
policy during its development.
To help diagnose issues, you can temporarily put the policy into "developer mode" and collect logs with Azure
Application Insights. Find out how in Azure Active Directory B2C: Collecting Logs.
Set up sign-in with a Google account using custom
policies in Azure Active Directory B2C
12/9/2019 • 7 minutes to read • Edit Online
NOTE
In Azure Active Directory B2C, custom policies are designed primarily to address complex scenarios. For most scenarios, we
recommend that you use built-in user flows.
This article shows you how to enable sign-in for users with a Google account by using custom policies in Azure
Active Directory B2C (Azure AD B2C ).
Prerequisites
Complete the steps in the Get started with custom policies in Active Directory B2C.
If you don't already have a Google account, create one at Create your Google Account.
<ClaimsProvider>
<Domain>google.com</Domain>
<DisplayName>Google</DisplayName>
<TechnicalProfiles>
<TechnicalProfile Id="Google-OAUTH">
<DisplayName>Google</DisplayName>
<Protocol Name="OAuth2" />
<Metadata>
<Item Key="ProviderName">google</Item>
<Item Key="authorization_endpoint">https://accounts.google.com/o/oauth2/auth</Item>
<Item Key="AccessTokenEndpoint">https://accounts.google.com/o/oauth2/token</Item>
<Item Key="ClaimsEndpoint">https://www.googleapis.com/oauth2/v1/userinfo</Item>
<Item Key="scope">email profile</Item>
<Item Key="HttpBinding">POST</Item>
<Item Key="UsePolicyInRedirectUri">0</Item>
<Item Key="client_id">Your Google application ID</Item>
</Metadata>
<CryptographicKeys>
<Key Id="client_secret" StorageReferenceId="B2C_1A_GoogleSecret" />
</CryptographicKeys>
<OutputClaims>
<OutputClaim ClaimTypeReferenceId="issuerUserId" PartnerClaimType="id" />
<OutputClaim ClaimTypeReferenceId="email" PartnerClaimType="email" />
<OutputClaim ClaimTypeReferenceId="givenName" PartnerClaimType="given_name" />
<OutputClaim ClaimTypeReferenceId="surname" PartnerClaimType="family_name" />
<OutputClaim ClaimTypeReferenceId="displayName" PartnerClaimType="name" />
<OutputClaim ClaimTypeReferenceId="identityProvider" DefaultValue="google.com" />
<OutputClaim ClaimTypeReferenceId="authenticationSource" DefaultValue="socialIdpAuthentication"
/>
</OutputClaims>
<OutputClaimsTransformations>
<OutputClaimsTransformation ReferenceId="CreateRandomUPNUserName" />
<OutputClaimsTransformation ReferenceId="CreateUserPrincipalName" />
<OutputClaimsTransformation ReferenceId="CreateAlternativeSecurityId" />
<OutputClaimsTransformation ReferenceId="CreateSubjectClaimFromAlternativeSecurityId" />
</OutputClaimsTransformations>
<UseTechnicalProfileForSessionManagement ReferenceId="SM-SocialLogin" />
</TechnicalProfile>
</TechnicalProfiles>
</ClaimsProvider>
4. Set client_id to the application ID from the application registration.
5. Save the file.
Upload the extension file for verification
By now, you have configured your policy so that Azure AD B2C knows how to communicate with your Azure AD
directory. Try uploading the extension file of your policy just to confirm that it doesn't have any issues so far.
1. On the Custom Policies page in your Azure AD B2C tenant, select Upload Policy.
2. Enable Overwrite the policy if it exists, and then browse to and select the TrustFrameworkExtensions.xml file.
3. Click Upload.
Update the value of TechnicalProfileReferenceId to the ID of the technical profile you created earlier. For
example, Google-OAuth .
3. Save the TrustFrameworkExtensions.xml file and upload it again for verification.
NOTE
In Azure Active Directory B2C, custom policies are designed primarily to address complex scenarios. For most scenarios, we
recommend that you use built-in user flows.
This article shows you how to enable sign-in for users from a LinkedIn account by using custom policies in Azure
Active Directory B2C (Azure AD B2C ).
Prerequisites
Complete the steps in Get started with custom policies in Azure Active Directory B2C.
LinkedIn account - If you don't already have one, create an account.
LinkedIn Page - You need a LinkedIn Page to associate with the LinkedIn application you create in the next
section.
Create an application
To use LinkedIn as an identity provider in Azure AD B2C, you need to create a LinkedIn application.
Create app
1. Sign in to the LinkedIn application management website with your LinkedIn account credentials.
2. Select Create app.
3. Enter an App name.
4. Enter a Company name corresponding to a LinkedIn page name. Create a LinkedIn Page if you don't already
have one.
5. (Optional) Enter a Privacy policy URL. It must be a valid URL, but doesn't need to be a reachable endpoint.
6. Enter a Business email.
7. Upload an App logo image. The logo image must be square and its dimensions must be at least 100x100
pixels.
8. Leave the default settings in the Products section.
9. Review the information presented in Legal terms. If you agree to the terms, check the box.
10. Select Create app.
Configure auth
1. Select the Auth tab.
2. Record the Client ID.
3. Reveal and record the Client Secret.
4. Under OAuth 2.0 settings, add the following Redirect URL. Replace your-tenant with the name of your
tenant. Use all lowercase letters for the tenant name even if it's defined with uppercase letters in Azure AD
B2C.
https://your-tenant.b2clogin.com/your-tenant.onmicrosoft.com/oauth2/authresp
4. Replace the value of client_id with the client ID of the LinkedIn application that you previously recorded.
5. Save the file.
Add the claims transformations
The LinkedIn technical profile requires the ExtractGivenNameFromLinkedInResponse and
ExtractSurNameFromLinkedInResponse claims transformations to be added to the list of
ClaimsTransformations. If you don't have a ClaimsTransformations element defined in your file, add the parent
XML elements as shown below. The claims transformations also need a new claim type defined named
nullStringClaim.
Add the BuildingBlocks element near the top of the TrustFrameworkExtensions.xml file. See
TrustFrameworkBase.xml for an example.
<BuildingBlocks>
<ClaimsSchema>
<!-- Claim type needed for LinkedIn claims transformations -->
<ClaimType Id="nullStringClaim">
<DisplayName>nullClaim</DisplayName>
<DataType>string</DataType>
<AdminHelpText>A policy claim to store output values from ClaimsTransformations that aren't useful. This
claim should not be used in TechnicalProfiles.</AdminHelpText>
<UserHelpText>A policy claim to store output values from ClaimsTransformations that aren't useful. This
claim should not be used in TechnicalProfiles.</UserHelpText>
</ClaimType>
</ClaimsSchema>
<ClaimsTransformations>
<!-- Claim transformations needed for LinkedIn technical profile -->
<ClaimsTransformation Id="ExtractGivenNameFromLinkedInResponse"
TransformationMethod="GetSingleItemFromJson">
<InputClaims>
<InputClaim ClaimTypeReferenceId="givenName" TransformationClaimType="inputJson" />
</InputClaims>
<OutputClaims>
<OutputClaim ClaimTypeReferenceId="nullStringClaim" TransformationClaimType="key" />
<OutputClaim ClaimTypeReferenceId="givenName" TransformationClaimType="value" />
</OutputClaims>
</ClaimsTransformation>
<ClaimsTransformation Id="ExtractSurNameFromLinkedInResponse" TransformationMethod="GetSingleItemFromJson">
<InputClaims>
<InputClaim ClaimTypeReferenceId="surname" TransformationClaimType="inputJson" />
</InputClaims>
<OutputClaims>
<OutputClaim ClaimTypeReferenceId="nullStringClaim" TransformationClaimType="key" />
<OutputClaim ClaimTypeReferenceId="surname" TransformationClaimType="value" />
</OutputClaims>
</ClaimsTransformation>
</ClaimsTransformations>
</BuildingBlocks>
Update the value of TechnicalProfileReferenceId to the ID of the technical profile you created earlier. For
example, LinkedIn-OAUTH .
3. Save the TrustFrameworkExtensions.xml file and upload it again for verification.
<Item Key="ClaimsEndpoint">https://api.linkedin.com/v1/people/~:(id,first-name,last-name,email-
address,headline)</Item>
<Item Key="scope">r_emailaddress r_basicprofile</Item>
To:
<Item Key="ClaimsEndpoint">https://api.linkedin.com/v2/me</Item>
<Item Key="scope">r_emailaddress r_liteprofile</Item>
<Item Key="external_user_identity_claim_id">id</Item>
<Item Key="BearerTokenTransmissionMethod">AuthorizationHeader</Item>
<Item Key="ResolveJsonPathsInJsonTokens">true</Item>
To:
<BuildingBlocks>
<ClaimsSchema>
<!-- Claim type needed for LinkedIn claims transformations -->
<ClaimType Id="nullStringClaim">
<DisplayName>nullClaim</DisplayName>
<DataType>string</DataType>
<AdminHelpText>A policy claim to store unuseful output values from ClaimsTransformations. This claim
should not be used in a TechnicalProfiles.</AdminHelpText>
<UserHelpText>A policy claim to store unuseful output values from ClaimsTransformations. This claim
should not be used in a TechnicalProfiles.</UserHelpText>
</ClaimType>
</ClaimsSchema>
<ClaimsTransformations>
<!-- Claim transformations needed for LinkedIn technical profile -->
<ClaimsTransformation Id="ExtractGivenNameFromLinkedInResponse"
TransformationMethod="GetSingleItemFromJson">
<InputClaims>
<InputClaim ClaimTypeReferenceId="givenName" TransformationClaimType="inputJson" />
</InputClaims>
<OutputClaims>
<OutputClaim ClaimTypeReferenceId="nullStringClaim" TransformationClaimType="key" />
<OutputClaim ClaimTypeReferenceId="givenName" TransformationClaimType="value" />
</OutputClaims>
</ClaimsTransformation>
<ClaimsTransformation Id="ExtractSurNameFromLinkedInResponse" TransformationMethod="GetSingleItemFromJson">
<InputClaims>
<InputClaim ClaimTypeReferenceId="surname" TransformationClaimType="inputJson" />
</InputClaims>
<OutputClaims>
<OutputClaim ClaimTypeReferenceId="nullStringClaim" TransformationClaimType="key" />
<OutputClaim ClaimTypeReferenceId="surname" TransformationClaimType="value" />
</OutputClaims>
</ClaimsTransformation>
</ClaimsTransformations>
</BuildingBlocks>
4. Add the following orchestration step into your user journey, so that the API claims provider is triggered
when a user signs in using LinkedIn. Make sure to update the Order number appropriately. Add this step
immediately after the orchestration step that triggers the LinkedIn technical profile.
Obtaining the email address from LinkedIn during sign-up is optional. If you choose not to obtain the email from
LinkedIn but require one during sign up, the user is required to manually enter the email address and validate it.
For a full sample of a policy that uses the LinkedIn identity provider, see the Custom Policy Starter Pack.
Set up sign-in with a Microsoft account using custom
policies in Azure Active Directory B2C
12/9/2019 • 7 minutes to read • Edit Online
NOTE
In Azure Active Directory B2C, custom policies are designed primarily to address complex scenarios. For most scenarios, we
recommend that you use built-in user flows.
This article shows you how to enable sign-in for users from a Microsoft account by using custom policies in Azure
Active Directory B2C (Azure AD B2C ).
Prerequisites
Complete the steps in Get started with custom policies in Azure Active Directory B2C.
If you don't already have a Microsoft account, create one at https://www.live.com/.
Add an application
To enable sign-in for users with a Microsoft account, you need to register an application within the Azure AD
tenant. The Azure AD tenant is not the same as your Azure AD B2C tenant.
1. Sign in to the Azure portal.
2. Make sure you're using the directory that contains your Azure AD tenant by selecting the Directory +
subscription filter in the top menu and choosing the directory that contains your Azure AD tenant.
3. Choose All services in the top-left corner of the Azure portal, and then search for and select App
registrations.
4. Select New registration.
5. Enter a Name for your application. For example, MSAapp1.
6. Under Supported account types, select Accounts in any organizational directory and personal
Microsoft accounts (e.g. Skype, Xbox, Outlook.com ).
7. Under Redirect URI (optional), select Web and enter
https://your-tenant-name.b2clogin.com/your-tenant-name.onmicrosoft.com/oauth2/authresp in the text box.
Replace your-tenant-name with your Azure AD B2C tenant name.
8. Select Register
9. Record the Application (client) ID shown on the application Overview page. You need this when you
configure the claims provider in a later section.
10. Select Certificates & secrets
11. Click New client secret
12. Enter a Description for the secret, for example MSA Application Client Secret, and then click Add.
13. Record the application password shown in the Value column. You use this value in the next section.
4. Replace the value of client_id with the Azure AD application's Application (client) ID that you recorded
earlier.
5. Save the file.
You've now configured your policy so that Azure AD B2C knows how to communicate with your Microsoft account
application in Azure AD.
Upload the extension file for verification
Before continuing, upload the modified policy to confirm that it doesn't have any issues so far.
1. Navigate to your Azure AD B2C tenant in the Azure portal and select Identity Experience Framework.
2. On the Custom policies page, select Upload custom policy.
3. Enable Overwrite the policy if it exists, and then browse to and select the TrustFrameworkExtensions.xml file.
4. Click Upload.
If no errors are displayed in the portal, continue to the next section.
Update the value of TechnicalProfileReferenceId to match that of the Id value in the TechnicalProfile
element of the claims provider you added earlier. For example, MSA-OIDC .
3. Save the TrustFrameworkExtensions.xml file and upload it again for verification.
4. Update the value of the ReferenceId attribute in DefaultUserJourney to match the ID of the user journey
that you created earlier (SignUpSignInMSA).
5. Save your changes, upload the file, and then select the new policy in the list.
6. Make sure that Azure AD B2C application that you created in the previous section (or by completing the
prerequisites, for example webapp1 or testapp1) is selected in the Select application field, and then test it
by clicking Run now.
7. Select the Microsoft Account button and sign in.
If the sign-in operation is successful, you're redirected to jwt.ms which displays the Decoded Token, similar
to:
{
"typ": "JWT",
"alg": "RS256",
"kid": "<key-ID>"
}.{
"exp": 1562365200,
"nbf": 1562361600,
"ver": "1.0",
"iss": "https://your-b2c-tenant.b2clogin.com/10000000-0000-0000-0000-000000000000/v2.0/",
"sub": "20000000-0000-0000-0000-000000000000",
"aud": "30000000-0000-0000-0000-000000000000",
"acr": "b2c_1a_signupsigninmsa",
"nonce": "defaultNonce",
"iat": 1562361600,
"auth_time": 1562361600,
"idp": "live.com",
"name": "Azure User",
"email": "azureuser@contoso.com",
"tid": "6fc3b573-7b38-4c0c-b627-2e8684f6c575"
}.[Signature]
Set up sign-in with a Twitter account by using custom
policies in Azure Active Directory B2C
12/9/2019 • 6 minutes to read • Edit Online
NOTE
In Azure Active Directory B2C, custom policies are designed primarily to address complex scenarios. For most scenarios, we
recommend that you use built-in user flows.
This article shows you how to enable sign-in for users of a Twitter account by using custom policies in Azure Active
Directory B2C (Azure AD B2C ).
Prerequisites
Complete the steps in Get started with custom policies in Azure Active Directory B2C.
If you don't already have a Twitter account, create one at Twitter sign-up page.
Create an application
To use Twitter as an identity provider in Azure AD B2C, you need to create a Twitter application.
1. Sign in to the Twitter Developers website with your Twitter account credentials.
2. Select Create an app.
3. Enter an App name and an Application description.
4. In Website URL, enter https://your-tenant.b2clogin.com . Replace your-tenant with the name of your tenant.
For example, https://contosob2c.b2clogin.com.
5. For the Callback URL, enter
https://your-tenant.b2clogin.com/your-tenant.onmicrosoft.com/your-policy-Id/oauth1/authresp . Replace
your-tenant with the name of your tenant name and your-policy-Id with the identifier of your policy. For
example, b2c_1A_signup_signin_twitter . You need to use all lowercase letters when entering your tenant name
even if the tenant is defined with uppercase letters in Azure AD B2C.
6. At the bottom of the page, read and accept the terms, and then select Create.
7. On the App details page, select Edit > Edit details, check the box for Enable Sign in with Twitter, and then
select Save.
8. Select Keys and tokens and record the Consumer API Key and the Consumer API secret key values to be
used later.
<ClaimsProvider>
<Domain>twitter.com</Domain>
<DisplayName>Twitter</DisplayName>
<TechnicalProfiles>
<TechnicalProfile Id="Twitter-OAUTH1">
<DisplayName>Twitter</DisplayName>
<Protocol Name="OAuth1" />
<Metadata>
<Item Key="ProviderName">Twitter</Item>
<Item Key="authorization_endpoint">https://api.twitter.com/oauth/authenticate</Item>
<Item Key="access_token_endpoint">https://api.twitter.com/oauth/access_token</Item>
<Item Key="request_token_endpoint">https://api.twitter.com/oauth/request_token</Item>
<Item Key="ClaimsEndpoint">https://api.twitter.com/1.1/account/verify_credentials.json?
include_email=true</Item>
<Item Key="ClaimsResponseFormat">json</Item>
<Item Key="client_id">Your Twitter application consumer key</Item>
</Metadata>
<CryptographicKeys>
<Key Id="client_secret" StorageReferenceId="B2C_1A_TwitterSecret" />
</CryptographicKeys>
<OutputClaims>
<OutputClaim ClaimTypeReferenceId="issuerUserId" PartnerClaimType="user_id" />
<OutputClaim ClaimTypeReferenceId="displayName" PartnerClaimType="screen_name" />
<OutputClaim ClaimTypeReferenceId="email" />
<OutputClaim ClaimTypeReferenceId="identityProvider" DefaultValue="twitter.com" />
<OutputClaim ClaimTypeReferenceId="authenticationSource" DefaultValue="socialIdpAuthentication"
/>
</OutputClaims>
<OutputClaimsTransformations>
<OutputClaimsTransformation ReferenceId="CreateRandomUPNUserName" />
<OutputClaimsTransformation ReferenceId="CreateUserPrincipalName" />
<OutputClaimsTransformation ReferenceId="CreateAlternativeSecurityId" />
<OutputClaimsTransformation ReferenceId="CreateSubjectClaimFromAlternativeSecurityId" />
</OutputClaimsTransformations>
<UseTechnicalProfileForSessionManagement ReferenceId="SM-SocialLogin" />
</TechnicalProfile>
</TechnicalProfiles>
</ClaimsProvider>
4. Replace the value of client_id with the consumer key that you previously recorded.
5. Save the file.
Upload the extension file for verification
By now, you have configured your policy so that Azure AD B2C knows how to communicate with your Twitter
account. Try uploading the extension file of your policy just to confirm that it doesn't have any issues so far.
1. On the Custom Policies page in your Azure AD B2C tenant, select Upload Policy.
2. Enable Overwrite the policy if it exists, and then browse to and select the TrustFrameworkExtensions.xml file.
3. Click Upload.
Update the value of TechnicalProfileReferenceId to the ID of the technical profile you created earlier. For
example, Twitter-OAUTH1 .
3. Save the TrustFrameworkExtensions.xml file and upload it again for verification.
NOTE
In Azure Active Directory B2C, custom policies are designed primarily to address complex scenarios. For most scenarios, we
recommend that you use built-in user flows.
This article shows you how to enable sign-in for an ADFS user account by using custom policies in Azure Active
Directory B2C (Azure AD B2C ). You enable sign-in by adding a SAML technical profile to a custom policy.
Prerequisites
Complete the steps in Get started with custom policies in Azure Active Directory B2C.
Make sure that you have access to a certificate .pfx file with a private key. You can generate your own signed
certificate and upload it to Azure AD B2C. Azure AD B2C uses this certificate to sign the SAML request sent to
your SAML identity provider.
In order for Azure to accept the .pfx file password, the password must be encrypted with the TripleDES -SHA1
option in Windows Certificate Store Export utility as opposed to AES256-SHA256.
<ClaimsProvider>
<Domain>contoso.com</Domain>
<DisplayName>Contoso ADFS</DisplayName>
<TechnicalProfiles>
<TechnicalProfile Id="Contoso-SAML2">
<DisplayName>Contoso ADFS</DisplayName>
<Description>Login with your ADFS account</Description>
<Protocol Name="SAML2"/>
<Metadata>
<Item Key="WantsEncryptedAssertions">false</Item>
<Item Key="PartnerEntity">https://your-ADFS-domain/federationmetadata/2007-
06/federationmetadata.xml</Item>
<Item Key="XmlSignatureAlgorithm">Sha256</Item>
</Metadata>
<CryptographicKeys>
<Key Id="SamlAssertionSigning" StorageReferenceId="B2C_1A_ADFSSamlCert"/>
<Key Id="SamlMessageSigning" StorageReferenceId="B2C_1A_ADFSSamlCert"/>
</CryptographicKeys>
<OutputClaims>
<OutputClaim ClaimTypeReferenceId="issuerUserId" PartnerClaimType="userPrincipalName" />
<OutputClaim ClaimTypeReferenceId="givenName" PartnerClaimType="given_name"/>
<OutputClaim ClaimTypeReferenceId="surname" PartnerClaimType="family_name"/>
<OutputClaim ClaimTypeReferenceId="email" PartnerClaimType="email"/>
<OutputClaim ClaimTypeReferenceId="displayName" PartnerClaimType="name"/>
<OutputClaim ClaimTypeReferenceId="identityProvider" DefaultValue="contoso.com" />
<OutputClaim ClaimTypeReferenceId="authenticationSource"
DefaultValue="socialIdpAuthentication"/>
</OutputClaims>
<OutputClaimsTransformations>
<OutputClaimsTransformation ReferenceId="CreateRandomUPNUserName"/>
<OutputClaimsTransformation ReferenceId="CreateUserPrincipalName"/>
<OutputClaimsTransformation ReferenceId="CreateAlternativeSecurityId"/>
<OutputClaimsTransformation ReferenceId="CreateSubjectClaimFromAlternativeSecurityId"/>
</OutputClaimsTransformations>
<UseTechnicalProfileForSessionManagement ReferenceId="SM-Noop"/>
</TechnicalProfile>
</TechnicalProfiles>
</ClaimsProvider>
4. Replace your-ADFS-domain with the name of your ADFS domain and replace the value of the
identityProvider output claim with your DNS (Arbitrary value that indicates your domain).
5. Save the file.
Upload the extension file for verification
By now, you have configured your policy so that Azure AD B2C knows how to communicate with ADFS account.
Try uploading the extension file of your policy just to confirm that it doesn't have any issues so far.
1. On the Custom Policies page in your Azure AD B2C tenant, select Upload Policy.
2. Enable Overwrite the policy if it exists, and then browse to and select the TrustFrameworkExtensions.xml
file.
3. Click Upload.
NOTE
The Visual Studio code B2C extension uses "socialIdpUserId." A social policy is also required for ADFS.
Register the claims provider
At this point, the identity provider has been set up, but it’s not available in any of the sign-up or sign-in screens. To
make it available, you create a duplicate of an existing template user journey, and then modify it so that it also has
the ADFS identity provider.
1. Open the TrustFrameworkBase.xml file from the starter pack.
2. Find and copy the entire contents of the UserJourney element that includes Id="SignUpOrSignIn" .
3. Open the TrustFrameworkExtensions.xml and find the UserJourneys element. If the element doesn't exist, add
one.
4. Paste the entire content of the UserJourney element that you copied as a child of the UserJourneys element.
5. Rename the ID of the user journey. For example, SignUpSignInADFS .
Display the button
The ClaimsProviderSelection element is analogous to an identity provider button on a sign-up or sign-in screen.
If you add a ClaimsProviderSelection element for an ADFS account, a new button shows up when a user lands
on the page.
1. Find the OrchestrationStep element that includes Order="1" in the user journey that you created.
2. Under ClaimsProviderSelections, add the following element. Set the value of TargetClaimsExchangeId
to an appropriate value, for example ContosoExchange :
Update the value of TechnicalProfileReferenceId to the ID of the technical profile you created earlier. For
example, Contoso-SAML2 .
3. Save the TrustFrameworkExtensions.xml file and upload it again for verification.
https://your-tenant-name.b2clogin.com/your-tenant-name/your-policy/samlp/metadata?idptp=your-technical-profile
User-Principal-Name userPrincipalName
Surname family_name
Given-Name given_name
E-Mail-Address email
Display-Name name
Note that these names will not display in the outgoing claim type dropdown. You need to manually type
them in. (The dropdown is actually editable).
12. Based on your certificate type, you may need to set the HASH algorithm. On the relying party trust (B2C
Demo) properties window, select the Advanced tab and change the Secure hash algorithm to SHA-256 ,
and click Ok.
13. In Server Manager, select Tools, and then select ADFS Management.
14. Select the relying party trust you created, select Update from Federation Metadata, and then click
Update.
Create an Azure AD B2C application
Communication with Azure AD B2C occurs through an application that you register in your B2C tenant. This
section lists optional steps you can complete to create a test application if you haven't already done so.
To register an application in your Azure AD B2C tenant, you can use the current Applications experience, or our
new unified App registrations (Preview) experience. Learn more about the new experience.
Applications
App registrations (Preview )
1. Sign in to the Azure portal.
2. Select the Directory + subscription filter in the top menu, and then select the directory that contains your
Azure AD B2C tenant.
3. In the left menu, select Azure AD B2C. Or, select All services and search for and select Azure AD B2C.
4. Select Applications, and then select Add.
5. Enter a name for the application. For example, testapp1.
6. For Web App / Web API, select Yes.
7. For Reply URL, enter https://jwt.ms
8. Select Create.
Update and test the relying party file
Update the relying party (RP ) file that initiates the user journey that you created.
1. Make a copy of SignUpOrSignIn.xml in your working directory, and rename it. For example, rename it to
SignUpSignInADFS.xml.
2. Open the new file and update the value of the PolicyId attribute for TrustFrameworkPolicy with a unique
value. For example, SignUpSignInADFS .
3. Update the value of PublicPolicyUri with the URI for the policy. For example,
http://contoso.com/B2C_1A_signup_signin_adfs
4. Update the value of the ReferenceId attribute in DefaultUserJourney to match the ID of the new user
journey that you created (SignUpSignInADFS ).
5. Save your changes, upload the file, and then select the new policy in the list.
6. Make sure that Azure AD B2C application that you created is selected in the Select application field, and then
test it by clicking Run now.
Set up sign-in with a Salesforce SAML provider by
using custom policies in Azure Active Directory B2C
12/9/2019 • 7 minutes to read • Edit Online
NOTE
In Azure Active Directory B2C, custom policies are designed primarily to address complex scenarios. For most scenarios, we
recommend that you use built-in user flows.
This article shows you how to enable sign-in for users from a Salesforce organization using custom policies in
Azure Active Directory B2C (Azure AD B2C ). You enable sign-in by adding a SAML technical profile to a custom
policy.
Prerequisites
Complete the steps in Get started with custom policies in Azure Active Directory B2C.
If you haven't already done so, sign up for a free Developer Edition account. This article uses the Salesforce
Lightning Experience.
Set up a My Domain for your Salesforce organization.
Set up Salesforce as an identity provider
1. Sign in to Salesforce.
2. On the left menu, under Settings, expand Identity, and then select Identity Provider.
3. Select Enable Identity Provider.
4. Under Select the certificate, select the certificate you want Salesforce to use to communicate with Azure AD
B2C. You can use the default certificate.
5. Click Save.
Create a connected app in Salesforce
1. On the Identity Provider page, select Service Providers are now created via Connected Apps. Click
here.
2. Under Basic Information, enter the required values for your connected app.
3. Under Web App Settings, check the Enable SAML box.
4. In the Entity ID field, enter the following URL. Make sure that you replace the value for your-tenant with
the name of your Azure AD B2C tenant.
https://your-tenant.b2clogin.com/your-tenant.onmicrosoft.com/B2C_1A_TrustFrameworkBase
5. In the ACS URL field, enter the following URL. Make sure that you replace the value for your-tenant with
the name of your Azure AD B2C tenant.
https://your-tenant.b2clogin.com/your-
tenant.onmicrosoft.com/B2C_1A_TrustFrameworkBase/samlp/sso/assertionconsumer
NOTE
Make sure that you update the tenant name and password in the top two lines.
<ClaimsProvider>
<Domain>salesforce</Domain>
<DisplayName>Salesforce</DisplayName>
<TechnicalProfiles>
<TechnicalProfile Id="salesforce">
<DisplayName>Salesforce</DisplayName>
<Description>Login with your Salesforce account</Description>
<Protocol Name="SAML2"/>
<Metadata>
<Item Key="WantsEncryptedAssertions">false</Item>
<Item Key="WantsSignedAssertions">false</Item>
<Item Key="PartnerEntity">https://contoso-dev-ed.my.salesforce.com/.well-
known/samlidp.xml</Item>
</Metadata>
<CryptographicKeys>
<Key Id="SamlAssertionSigning" StorageReferenceId="B2C_1A_SAMLSigningCert"/>
<Key Id="SamlMessageSigning" StorageReferenceId="B2C_1A_SAMLSigningCert"/>
</CryptographicKeys>
<OutputClaims>
<OutputClaim ClaimTypeReferenceId="issuerUserId" PartnerClaimType="userId"/>
<OutputClaim ClaimTypeReferenceId="givenName" PartnerClaimType="given_name"/>
<OutputClaim ClaimTypeReferenceId="surname" PartnerClaimType="family_name"/>
<OutputClaim ClaimTypeReferenceId="email" PartnerClaimType="email"/>
<OutputClaim ClaimTypeReferenceId="displayName" PartnerClaimType="username"/>
<OutputClaim ClaimTypeReferenceId="authenticationSource"
DefaultValue="socialIdpAuthentication"/>
<OutputClaim ClaimTypeReferenceId="identityProvider" DefaultValue="SAMLIdp" />
</OutputClaims>
<OutputClaimsTransformations>
<OutputClaimsTransformation ReferenceId="CreateRandomUPNUserName"/>
<OutputClaimsTransformation ReferenceId="CreateUserPrincipalName"/>
<OutputClaimsTransformation ReferenceId="CreateAlternativeSecurityId"/>
<OutputClaimsTransformation ReferenceId="CreateSubjectClaimFromAlternativeSecurityId"/>
</OutputClaimsTransformations>
<UseTechnicalProfileForSessionManagement ReferenceId="SM-Noop"/>
</TechnicalProfile>
</TechnicalProfiles>
</ClaimsProvider>
4. Update the value of PartnerEntity with the Salesforce metadata URL you copied earlier.
5. Update the value of both instances of StorageReferenceId to the name of the key of your signing
certificate. For example, B2C_1A_SAMLSigningCert.
Upload the extension file for verification
By now, you have configured your policy so that Azure AD B2C knows how to communicate with your Salesforce
account. Try uploading the extension file of your policy just to confirm that it doesn't have any issues so far.
1. On the Custom Policies page in your Azure AD B2C tenant, select Upload Policy.
2. Enable Overwrite the policy if it exists, and then browse to and select the TrustFrameworkExtensions.xml
file.
3. Click Upload.
Update the value of TechnicalProfileReferenceId to the Id of the technical profile you created earlier. For
example, LinkedIn-OAUTH .
3. Save the TrustFrameworkExtensions.xml file and upload it again for verification.
This article provides information about how you can manage your token, session, and single sign-on (SSO )
configurations using custom policies in Azure Active Directory B2C (Azure AD B2C ).
<ClaimsProviders>
<ClaimsProvider>
<DisplayName>Token Issuer</DisplayName>
<TechnicalProfiles>
<TechnicalProfile Id="JwtIssuer">
<Metadata>
<Item Key="token_lifetime_secs">3600</Item>
<Item Key="id_token_lifetime_secs">3600</Item>
<Item Key="refresh_token_lifetime_secs">1209600</Item>
<Item Key="rolling_refresh_token_lifetime_secs">7776000</Item>
<Item Key="IssuanceClaimPattern">AuthorityAndTenantGuid</Item>
<Item Key="AuthenticationContextReferenceClaimPattern">None</Item>
</Metadata>
</TechnicalProfile>
</TechnicalProfiles>
</ClaimsProvider>
</ClaimsProviders>
Issuer (iss) claim - The Issuer (iss) claim is set with the IssuanceClaimPattern metadata item. The
applicable values are AuthorityAndTenantGuid and AuthorityWithTfp .
Setting claim representing policy ID - The options for setting this value are TFP (trust framework
policy) and ACR (authentication context reference). TFP is the recommended value. Set
AuthenticationContextReferenceClaimPattern with the value of None .
In the ClaimsSchema element, add this element:
<ClaimType Id="trustFrameworkPolicy">
<DisplayName>Trust framework policy name</DisplayName>
<DataType>string</DataType>
</ClaimType>
<UserJourneyBehaviors>
<SingleSignOn Scope="Application" />
<SessionExpiryType>Absolute</SessionExpiryType>
<SessionExpiryInSeconds>86400</SessionExpiryInSeconds>
</UserJourneyBehaviors>
A custom policy in Azure Active Directory B2C (Azure AD B2C ) provides users of your application an opportunity
to sign up or sign in with an identity provider. When this happens, Azure AD B2C receives an access token from
the identity provider. Azure AD B2C uses that token to retrieve information about the user. You add a claim type
and output claim to your custom policy to pass the token through to the applications that you register in Azure AD
B2C.
Azure AD B2C supports passing the access token of OAuth 2.0 and OpenID Connect identity providers. For all
other identity providers, the claim is returned blank.
Prerequisites
Your custom policy is configured with an OAuth 2.0 or OpenID Connect identity provider.
<BuildingBlocks>
<ClaimsSchema>
<ClaimType Id="identityProviderAccessToken">
<DisplayName>Identity Provider Access Token</DisplayName>
<DataType>string</DataType>
<AdminHelpText>Stores the access token of the identity provider.</AdminHelpText>
</ClaimType>
...
</ClaimsSchema>
</BuildingBlocks>
2. Add the OutputClaim element to the TechnicalProfile element for each OAuth 2.0 identity provider that
you would like the access token for. The following example shows the element added to the Facebook
technical profile:
<ClaimsProvider>
<DisplayName>Facebook</DisplayName>
<TechnicalProfiles>
<TechnicalProfile Id="Facebook-OAUTH">
<OutputClaims>
<OutputClaim ClaimTypeReferenceId="identityProviderAccessToken" PartnerClaimType="
{oauth2:access_token}" />
</OutputClaims>
...
</TechnicalProfile>
</TechnicalProfiles>
</ClaimsProvider>
<RelyingParty>
<DefaultUserJourney ReferenceId="SignUpOrSignIn" />
<TechnicalProfile Id="PolicyProfile">
<OutputClaims>
<OutputClaim ClaimTypeReferenceId="identityProviderAccessToken"
PartnerClaimType="idp_access_token"/>
</OutputClaims>
...
</TechnicalProfile>
</RelyingParty>
When setting up sign-in for your application using Azure Active Directory (AD ) B2C, you can prepopulate the sign-
in name or direct sign-in to a specific social identity provider, such as Facebook, LinkedIn, or a Microsoft account.
If you are using a custom policy, you can configure the domain name using the <Domain>domain name</Domain> XML
element of any <ClaimsProvider> .
<ClaimsProvider>
<!-- Add the domain hint value to the claims provider -->
<Domain>facebook.com</Domain>
<DisplayName>Facebook</DisplayName>
<TechnicalProfiles>
...
Walkthrough: Integrate REST API claims exchanges in
your Azure AD B2C user journey as validation on
user input
12/9/2019 • 4 minutes to read • Edit Online
NOTE
In Azure Active Directory B2C, custom policies are designed primarily to address complex scenarios. For most scenarios, we
recommend that you use built-in user flows.
The Identity Experience Framework (IEF ) that underlies Azure Active Directory B2C (Azure AD B2C ) enables the
identity developer to integrate an interaction with a RESTful API in a user journey.
At the end of this walkthrough, you will be able to create an Azure AD B2C user journey that interacts with
RESTful services.
The IEF sends data in claims and receives data back in claims. The interaction with the API:
Can be designed as a REST API claims exchange or as a validation profile, which happens inside an
orchestration step.
Typically validates input from the user. If the value from the user is rejected, the user can try again to enter a
valid value with the opportunity to return an error message.
You can also design the interaction as an orchestration step. For more information, see Walkthrough: Integrate
REST API claims exchanges in your Azure AD B2C user journey as an orchestration step.
For the validation profile example, we will use the profile edit user journey in the starter pack file ProfileEdit.xml.
We can verify that the name provided by the user in the profile edit is not part of an exclusion list.
Prerequisites
An Azure AD B2C tenant configured to complete a local account sign-up/sign-in, as described in Getting
started.
A REST API endpoint to interact with. For this walkthrough, we've set up a demo site called WingTipGames
with a REST API service.
We have created an Azure function that receives a claim that it expects as playerTag . The function validates
whether this claim exists. You can access the complete Azure function code in GitHub.
if (requestContentAsJObject.playerTag == null)
{
return request.CreateResponse(HttpStatusCode.BadRequest);
}
return request.CreateResponse(HttpStatusCode.OK);
The IEF expects the userMessage claim that the Azure function returns. This claim will be presented as a string to
the user if the validation fails, such as when a 409 conflict status is returned in the preceding example.
NOTE
In the following XML, RESTful provider Version=1.0.0.0 is described as the protocol. Consider it as the function that will
interact with the external service.
<ClaimsProvider>
<DisplayName>REST APIs</DisplayName>
<TechnicalProfiles>
<TechnicalProfile Id="AzureFunctions-CheckPlayerTagWebHook">
<DisplayName>Check Player Tag Web Hook Azure Function</DisplayName>
<Protocol Name="Proprietary" Handler="Web.TPEngine.Providers.RestfulProvider, Web.TPEngine,
Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
<Metadata>
<Item Key="ServiceUrl">https://wingtipb2cfuncs.azurewebsites.net/api/CheckPlayerTagWebHook?
code=L/05YRSpojU0nECzM4Tp3LjBiA2ZGh3kTwwp1OVV7m0SelnvlRVLCg==</Item>
<Item Key="SendClaimsIn">Body</Item>
<!-- Set AuthenticationType to Basic or ClientCertificate in production environments -->
<Item Key="AuthenticationType">None</Item>
<!-- REMOVE the following line in production environments -->
<Item Key="AllowInsecureAuthInProduction">true</Item>
</Metadata>
<InputClaims>
<InputClaim ClaimTypeReferenceId="givenName" PartnerClaimType="playerTag" />
</InputClaims>
<UseTechnicalProfileForSessionManagement ReferenceId="SM-Noop" />
</TechnicalProfile>
<TechnicalProfile Id="SelfAsserted-ProfileUpdate">
<ValidationTechnicalProfiles>
<ValidationTechnicalProfile ReferenceId="AzureFunctions-CheckPlayerTagWebHook" />
</ValidationTechnicalProfiles>
</TechnicalProfile>
</TechnicalProfiles>
</ClaimsProvider>
The InputClaims element defines the claims that will be sent from the IEF to the REST service. In this example, the
contents of the claim givenName will be sent to the REST service as playerTag . In this example, the IEF does not
expect claims back. Instead, it waits for a response from the REST service and acts based on the status codes that it
receives.
The comments above AuthenticationType and AllowInsecureAuthInProduction specify changes you should make
when you move to a production environment. To learn how to secure your RESTful APIs for production, see
Secure RESTful APIs with basic auth and Secure RESTful APIs with certificate auth.
Next steps
Modify the profile edit and user registration to gather additional information from your users
Walkthrough: Integrate REST API claims exchanges in your Azure AD B2C user journey as an orchestration step
Reference: RESTful technical profile
To learn how to secure your APIs, see the following articles:
Secure your RESTful API with basic authentication (username and password)
Secure your RESTful API with client certificates
Add REST API claims exchanges to custom policies in
Azure Active Directory B2C
9/17/2019 • 5 minutes to read • Edit Online
NOTE
In Azure Active Directory B2C, custom policies are designed primarily to address complex scenarios. For most scenarios, we
recommend that you use built-in user flows.
You can add interaction with a RESTful API to your custom policies in Azure Active Directory B2C (Azure AD
B2C ). This article shows you how to create an Azure AD B2C user journey that interacts with RESTful services.
The interaction includes a claims exchange of information between the REST API claims and Azure AD B2C.
Claims exchanges have the following characteristics:
Can be designed as an orchestration step.
Can trigger an external action. For instance, it can log an event in an external database.
Can be used to fetch a value and then store it in the user database.
Can change the flow of execution.
The scenario that is represented in this article includes the following actions:
1. Look up the user in an external system.
2. Get the city where that user is registered.
3. Return that attribute to the application as a claim.
Prerequisites
Complete the steps in Get started with custom policies.
A REST API endpoint to interact with. This article uses a simple Azure function as an example. To create the
Azure function, see Create your first function in the Azure portal.
using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;
The InputClaims element defines the claims that are sent to the REST service. In this example, the value of the
claim givenName is sent to the REST service as the claim email . The OutputClaims element defines the claims
that are expected from the REST service.
The comments above AuthenticationType and AllowInsecureAuthInProduction specify changes you should make
when you move to a production environment. To learn how to secure your RESTful APIs for production, see
Secure RESTful APIs with basic auth and Secure RESTful APIs with certificate auth.
<BuildingBlocks>
<ClaimsSchema>
<ClaimType Id="city">
<DisplayName>City</DisplayName>
<DataType>string</DataType>
<UserHelpText>Your city</UserHelpText>
<UserInputType>TextBox</UserInputType>
</ClaimType>
</ClaimsSchema>
</BuildingBlocks>
The final XML for the user journey should look like this example:
<UserJourney Id="ProfileEdit">
<OrchestrationSteps>
<OrchestrationStep Order="1" Type="ClaimsProviderSelection"
ContentDefinitionReferenceId="api.idpselections">
<ClaimsProviderSelections>
<ClaimsProviderSelection TargetClaimsExchangeId="FacebookExchange" />
<ClaimsProviderSelection TargetClaimsExchangeId="LocalAccountSigninEmailExchange" />
</ClaimsProviderSelections>
</OrchestrationStep>
<OrchestrationStep Order="2" Type="ClaimsExchange">
<ClaimsExchanges>
<ClaimsExchange Id="FacebookExchange" TechnicalProfileReferenceId="Facebook-OAUTH" />
<ClaimsExchange Id="LocalAccountSigninEmailExchange" TechnicalProfileReferenceId="SelfAsserted-
LocalAccountSignin-Email" />
</ClaimsExchanges>
</OrchestrationStep>
<OrchestrationStep Order="3" Type="ClaimsExchange">
<Preconditions>
<Precondition Type="ClaimEquals" ExecuteActionsIf="true">
<Value>authenticationSource</Value>
<Value>localAccountAuthentication</Value>
<Action>SkipThisOrchestrationStep</Action>
</Precondition>
</Preconditions>
<ClaimsExchanges>
<ClaimsExchange Id="AADUserRead" TechnicalProfileReferenceId="AAD-UserReadUsingAlternativeSecurityId"
/>
</ClaimsExchanges>
</OrchestrationStep>
<OrchestrationStep Order="4" Type="ClaimsExchange">
<Preconditions>
<Precondition Type="ClaimEquals" ExecuteActionsIf="true">
<Value>authenticationSource</Value>
<Value>socialIdpAuthentication</Value>
<Action>SkipThisOrchestrationStep</Action>
</Precondition>
</Preconditions>
<ClaimsExchanges>
<ClaimsExchange Id="AADUserReadWithObjectId" TechnicalProfileReferenceId="AAD-UserReadUsingObjectId"
/>
</ClaimsExchanges>
</OrchestrationStep>
<OrchestrationStep Order="5" Type="ClaimsExchange">
<ClaimsExchanges>
<ClaimsExchange Id="B2CUserProfileUpdateExchange" TechnicalProfileReferenceId="SelfAsserted-
ProfileUpdate" />
</ClaimsExchanges>
</OrchestrationStep>
<!-- Add a step 6 to the user journey before the JWT token is created-->
<OrchestrationStep Order="6" Type="ClaimsExchange">
<ClaimsExchanges>
<ClaimsExchange Id="GetLoyaltyData" TechnicalProfileReferenceId="AzureFunctions-WebHook" />
</ClaimsExchanges>
</OrchestrationStep>
<OrchestrationStep Order="7" Type="SendClaims" CpimIssuerTechnicalProfileReferenceId="JwtIssuer" />
</OrchestrationSteps>
<ClientDefinition ReferenceId="DefaultWeb" />
</UserJourney>
{
"exp": 1493053292,
"nbf": 1493049692,
"ver": "1.0",
"iss": "https://contoso.b2clogin.com/f06c2fe8-709f-4030-85dc-38a4bfd9e82d/v2.0/",
"sub": "a58e7c6c-7535-4074-93da-b0023fbaf3ac",
"aud": "4e87c1dd-e5f5-4ac8-8368-bc6a98751b8b",
"acr": "b2c_1a_profileedit",
"nonce": "defaultNonce",
"iat": 1493049692,
"auth_time": 1493049692,
"city": "Redmond"
}
Next steps
You can also design the interaction as a validation profile. For more information, see Walkthrough: Integrate REST
API claims exchanges in your Azure AD B2C user journey as validation on user input.
Modify the profile edit to gather additional information from your users
Reference: RESTful technical profile
To learn out how to secure your APIs, see the following articles:
Secure your RESTful API with basic authentication (username and password)
Secure your RESTful API with client certificates
Integrate REST API claims exchanges in your Azure
AD B2C user journey as validation of user input
12/9/2019 • 10 minutes to read • Edit Online
NOTE
In Azure Active Directory B2C, custom policies are designed primarily to address complex scenarios. For most scenarios, we
recommend that you use built-in user flows.
With the Identity Experience Framework, which underlies Azure Active Directory B2C (Azure AD B2C ), you can
integrate with a RESTful API in a user journey. In this walkthrough, you'll learn how Azure AD B2C interacts with
.NET Framework RESTful services (web API).
Introduction
By using Azure AD B2C, you can add your own business logic to a user journey by calling your own RESTful
service. The Identity Experience Framework sends data to the RESTful service in an Input claims collection and
receives data back from RESTful in an Output claims collection. With RESTful service integration, you can:
Validate user input data: This action prevents malformed data from persisting into Azure AD. If the value
from the user is not valid, your RESTful service returns an error message that instructs the user to provide an
entry. For example, you can verify that the email address provided by the user exists in your customer's
database.
Overwrite input claims: For example, if a user enters the first name in all lowercase or all uppercase letters,
you can format the name with only the first letter capitalized.
Enrich user data by further integrating with corporate line-of-business applications: Your RESTful
service can receive the user's email address, query the customer's database, and return the user's loyalty
number to Azure AD B2C. The return claims can be stored in the user's Azure AD account, evaluated in the
next Orchestration Steps, or included in the access token.
Run custom business logic: You can send push notifications, update corporate databases, run a user
migration process, manage permissions, audit databases, and perform other actions.
You can design the integration with the RESTful services in the following ways:
Validation technical profile: The call to the RESTful service happens within the validation technical
profile of the specified technical profile. The validation technical profile validates the user-provided data
before the user journey moves forward. With the validation technical profile, you can:
Send input claims.
Validate the input claims and throw custom error messages.
Send back output claims.
Claims exchange: This design is similar to the validation technical profile, but it happens within an
orchestration step. This definition is limited to:
Send input claims.
Send back output claims.
RESTful walkthrough
In this walkthrough, you develop a .NET Framework web API that validates the user input and provides a user
loyalty number. For example, your application can grant access to platinum benefits based on the loyalty number.
Overview:
Develop the RESTful service (.NET Framework web API)
Use the RESTful service in the user journey
Send input claims and read them in your code
Validate the user's first name
Send back a loyalty number
Add the loyalty number to a JSON Web Token (JWT)
Prerequisites
Complete the steps in the Getting started with custom policies article.
4. In the New ASP.NET Web Application window, select a Web API or Azure API app template.
5. Make sure that authentication is set to No Authentication.
6. Select OK to create the project.
namespace Contoso.AADB2C.API.Models
{
public class InputClaimsModel
{
public string email { get; set; }
public string firstName { get; set; }
public string lastName { get; set; }
}
}
4. Create a new model, OutputClaimsModel , and then add the following properties to the OutputClaimsModel
class:
namespace Contoso.AADB2C.API.Models
{
public class OutputClaimsModel
{
public string loyaltyNumber { get; set; }
}
}
5. Create one more model, B2CResponseContent , which you use to throw input validation error messages. Add
the following properties to the B2CResponseContent class, provide the missing references, and then save the
file:
namespace Contoso.AADB2C.API.Models
{
public class B2CResponseContent
{
public string version { get; set; }
public int status { get; set; }
public string userMessage { get; set; }
2. In the Add Scaffold window, select Web API Controller - Empty, and then select Add.
3. In the Add Controller window, name the controller IdentityController, and then select Add.
namespace Contoso.AADB2C.API.Controllers
{
public class IdentityController: ApiController
{
[HttpPost]
public IHttpActionResult SignUp()
{
// If no data came in, then return
if (this.Request.Content == null) throw new Exception();
if (inputClaims == null)
{
return Content(HttpStatusCode.Conflict, new B2CResponseContent("Can not deserialize
input claims", HttpStatusCode.Conflict));
}
// Create an output claims object and set the loyalty number with a random value
OutputClaimsModel outputClaims = new OutputClaimsModel();
outputClaims.loyaltyNumber = new Random().Next(100, 1000).ToString();
The Create App Service window opens. In it, you create all the necessary Azure resources to run the
ASP.NET web app in Azure.
TIP
For more information about how to publish, see Create an ASP.NET web app in Azure.
3. In the Web App Name box, type a unique app name (valid characters are a-z, 0-9, and hyphens (-). The
URL of the web app is http://<app_name>.azurewebsites.NET, where app_name is the name of your web
app. You can accept the automatically generated name, which is unique.
4. To start creating Azure resources, select Create. After the ASP.NET web app has been created, the wizard
publishes it to Azure and then starts the app in the default browser.
5. Copy the web app's URL.
<BuildingBlocks>
<ClaimsSchema>
<ClaimType Id="loyaltyNumber">
<DisplayName>loyaltyNumber</DisplayName>
<DataType>string</DataType>
<UserHelpText>Customer loyalty number</UserHelpText>
</ClaimType>
</ClaimsSchema>
</BuildingBlocks>
<ClaimsProvider>
<DisplayName>REST APIs</DisplayName>
<TechnicalProfiles>
The comments above AuthenticationType and AllowInsecureAuthInProduction specify changes you should make
when you move to a production environment. To learn how to secure your RESTful APIs for production, see
Secure RESTful APIs with basic auth and Secure RESTful APIs with certificate auth.
Step 6: Add the loyaltyNumber claim to your relying party policy file so
the claim is sent to your application
Edit your SignUpOrSignIn.xml relying party (RP ) file, and modify the TechnicalProfile Id="PolicyProfile" element
to add the following: <OutputClaim ClaimTypeReferenceId="loyaltyNumber" /> .
After you add the new claim, the relying party code looks like this:
<RelyingParty>
<DefaultUserJourney ReferenceId="SignUpOrSignIn" />
<TechnicalProfile Id="PolicyProfile">
<DisplayName>PolicyProfile</DisplayName>
<Protocol Name="OpenIdConnect" />
<OutputClaims>
<OutputClaim ClaimTypeReferenceId="displayName" />
<OutputClaim ClaimTypeReferenceId="givenName" />
<OutputClaim ClaimTypeReferenceId="surname" />
<OutputClaim ClaimTypeReferenceId="email" />
<OutputClaim ClaimTypeReferenceId="objectId" PartnerClaimType="sub"/>
<OutputClaim ClaimTypeReferenceId="identityProvider" />
<OutputClaim ClaimTypeReferenceId="loyaltyNumber" DefaultValue="" />
</OutputClaims>
<SubjectNamingInfo ClaimType="sub" />
</TechnicalProfile>
</RelyingParty>
</TrustFrameworkPolicy>
NOTE
Run now requires at least one application to be preregistered on the tenant. To learn how to register applications,
see the Azure AD B2C Get started article or the Application registration article.
2. Open B2C_1A_signup_signin, the relying party (RP ) custom policy that you uploaded, and then select
Run now.
3. Test the process by typing Test in the Given Name box. Azure AD B2C displays an error message at the
top of the window.
4. In the Given Name box, type a name (other than "Test"). Azure AD B2C signs up the user and then sends a
loyaltyNumber to your application. Note the number in this JWT.
{
"typ": "JWT",
"alg": "RS256",
"kid": "X5eXk4xyojNFum1kl2Ytv8dlNP4-c57dO6QGTVBwaNk"
}.{
"exp": 1507125903,
"nbf": 1507122303,
"ver": "1.0",
"iss": "https://contoso.b2clogin.com/f06c2fe8-709f-4030-85dc-38a4bfd9e82d/v2.0/",
"aud": "e1d2612f-c2bc-4599-8e7b-d874eaca1ee1",
"acr": "b2c_1a_signup_signin",
"nonce": "defaultNonce",
"iat": 1507122303,
"auth_time": 1507122303,
"loyaltyNumber": "290",
"given_name": "Emily",
"emails": ["B2cdemo@outlook.com"]
}
Next steps
Your next task is to secure your RESTful API using basic or client certificate authentication. To learn how to secure
your APIs, see the following articles:
Secure your RESTful API with basic authentication (username and password)
Secure your RESTful API with client certificates
For information about all the elements available in a RESTful technical profile, see Reference: RESTful technical
profile.
Secure your RESTful services by using HTTP basic
authentication
12/9/2019 • 6 minutes to read • Edit Online
NOTE
In Azure Active Directory B2C, custom policies are designed primarily to address complex scenarios. For most scenarios, we
recommend that you use built-in user flows.
In a related Azure AD B2C article, you create a RESTful service (web API) that integrates with Azure Active
Directory B2C (Azure AD B2C ) user journeys without authentication.
In this article, you add HTTP basic authentication to your RESTful service so that only verified users, including
B2C, can access your API. With HTTP basic authentication, you set the user credentials (app ID and app secret) in
your custom policy.
For more information, see Basic authentication in ASP.NET web API.
Prerequisites
Complete the steps in the Integrate REST API claims exchanges in your Azure AD B2C user journey article.
using Microsoft.Owin;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Security.Principal;
using System.Text;
using System.Threading.Tasks;
using System.Web;
namespace Contoso.AADB2C.API
{
/// <summary>
/// Class to create a custom owin middleware to check for client authentication
/// </summary>
public class ClientAuthMiddleware
{
private static readonly string ClientID = ConfigurationManager.AppSettings["WebApp:ClientId"];
private static readonly string ClientSecret =
ConfigurationManager.AppSettings["WebApp:ClientSecret"];
/// <summary>
/// Gets or sets the next owin middleware
/// </summary>
private Func<IDictionary<string, object>, Task> Next { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="ClientAuthMiddleware"/> class.
/// </summary>
/// <param name="next"></param>
public ClientAuthMiddleware(Func<IDictionary<string, object>, Task> next)
{
this.Next = next;
}
/// <summary>
/// Invoke client authentication middleware during each request.
/// </summary>
/// <param name="environment">Owin environment</param>
/// <returns></returns>
public Task Invoke(IDictionary<string, object> environment)
{
// Get wrapper class for the environment
var context = new OwinContext(environment);
// Check whether the authorization header is available. This contains the credentials.
var authzValue = context.Request.Headers.Get("Authorization");
if (string.IsNullOrEmpty(authzValue) || !authzValue.StartsWith("Basic ",
StringComparison.OrdinalIgnoreCase))
{
// Process next middleware
return Next(environment);
}
// Get credentials
var creds = authzValue.Substring("Basic ".Length).Trim();
string clientId;
string clientSecret;
return Next(environment);
}
/// <summary>
/// Retrieve credentials from header
/// </summary>
/// <param name="credentials">Authorization header</param>
/// <param name="clientId">Client identifier</param>
/// <param name="clientSecret">Client secret</param>
/// <returns>True if valid credentials were presented</returns>
private bool RetrieveCreds(string credentials, out string clientId, out string clientSecret)
{
string pair;
clientId = clientSecret = string.Empty;
try
{
pair = Encoding.UTF8.GetString(Convert.FromBase64String(credentials));
}
catch (FormatException)
{
return false;
}
catch (ArgumentException)
{
return false;
}
var ix = pair.IndexOf(':');
if (ix == -1)
{
return false;
}
using Microsoft.Owin;
using Owin;
[assembly: OwinStartup(typeof(Contoso.AADB2C.API.Startup))]
namespace Contoso.AADB2C.API
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.Use<ClientAuthMiddleware>();
}
}
}
Step 3: Add the RESTful services app ID and app secret to Azure AD
B2C
After your RESTful service is protected by the client ID (username) and secret, you must store the credentials in
your Azure AD B2C tenant. Your custom policy provides the credentials when it invokes your RESTful services.
Step 3.1: Add a RESTful services client ID
1. In your Azure AD B2C tenant, select B2C Settings > Identity Experience Framework.
2. Select Policy Keys to view the keys that are available in your tenant.
3. Select Add.
4. For Options, select Manual.
5. For Name, type B2cRestClientId. The prefix B2C_1A_ might be added automatically.
6. In the Secret box, enter the app ID that you defined earlier.
7. For Key usage, select Signature.
8. Select Create.
9. Confirm that you've created the B2C_1A_B2cRestClientId key.
Step 3.2: Add a RESTful services client secret
1. In your Azure AD B2C tenant, select B2C Settings > Identity Experience Framework.
2. Select Policy Keys to view the keys available in your tenant.
3. Select Add.
4. For Options, select Manual.
5. For Name, type B2cRestClientSecret. The prefix B2C_1A_ might be added automatically.
6. In the Secret box, enter the app secret that you defined earlier.
7. For Key usage, select Signature.
8. Select Create.
9. Confirm that you've created the B2C_1A_B2cRestClientSecret key.
<Item Key="AuthenticationType">Basic</Item>
5. Immediately after the closing <Metadata> element, add the following XML snippet:
<CryptographicKeys>
<Key Id="BasicAuthenticationUsername" StorageReferenceId="B2C_1A_B2cRestClientId" />
<Key Id="BasicAuthenticationPassword" StorageReferenceId="B2C_1A_B2cRestClientSecret" />
</CryptographicKeys>
After you add the snippet, your technical profile should look like the following XML code:
NOTE
Run Now requires at least one application to be preregistered on the tenant. To learn how to register applications,
see the Azure AD B2C Get started article or the Application registration article.
2. Open B2C_1A_signup_signin, the relying party (RP ) custom policy that you uploaded, and then select
Run now.
3. Test the process by typing Test in the Given Name box. Azure AD B2C displays an error message at the
top of the window.
4. In the Given Name box, type a name (other than "Test"). Azure AD B2C signs up the user and then sends
a loyalty number to your application. Note the number in this example:
{
"typ": "JWT",
"alg": "RS256",
"kid": "X5eXk4xyojNFum1kl2Ytv8dlNP4-c57dO6QGTVBwaNk"
}.{
"exp": 1507125903,
"nbf": 1507122303,
"ver": "1.0",
"iss": "https://contoso.b2clogin.com/f06c2fe8-709f-4030-85dc-38a4bfd9e82d/v2.0/",
"aud": "e1d2612f-c2bc-4599-8e7b-d874eaca1ee1",
"acr": "b2c_1a_signup_signin",
"nonce": "defaultNonce",
"iat": 1507122303,
"auth_time": 1507122303,
"loyaltyNumber": "290",
"given_name": "Emily",
"emails": ["B2cdemo@outlook.com"]
}
Next steps
Use client certificates to secure your RESTful API
Secure your RESTful service by using client
certificates
12/9/2019 • 7 minutes to read • Edit Online
NOTE
In Azure Active Directory B2C, custom policies are designed primarily to address complex scenarios. For most scenarios, we
recommend that you use built-in user flows.
In a related article, you create a RESTful service that interacts with Azure Active Directory B2C (Azure AD B2C ).
In this article, you learn how to restrict access to your Azure web app (RESTful API) by using a client certificate.
This mechanism is called TLS mutual authentication, or client certificate authentication. Only services that have
proper certificates, such as Azure AD B2C, can access your service.
NOTE
You can also secure your RESTful service by using HTTP basic authentication. However, HTTP basic authentication is
considered less secure over a client certificate. Our recommendation is to secure the RESTful service by using client
certificate authentication as described in this article.
Prerequisites
Complete the steps in the Integrate REST API claims exchanges article.
Get a valid certificate (a .pfx file with a private key).
NOTE
Make sure that your Azure App Service plan is Standard or greater. For more information, see Azure App Service plans in-
depth overview.
NOTE
For more information about setting the clientCertEnabled property, see Configure TLS mutual authentication for web
apps.
Step 2: Upload your certificate to Azure AD B2C policy keys
After you set clientCertEnabled to true, the communication with your RESTful API requires a client certificate.
To obtain, upload, and store the client certificate in your Azure AD B2C tenant, do the following:
1. In your Azure AD B2C tenant, select B2C Settings > Identity Experience Framework.
2. To view the keys that are available in your tenant, select Policy Keys.
3. Select Add. The Create a key window opens.
4. In the Options box, select Upload.
5. In the Name box, type B2cRestClientCertificate. The prefix B2C_1A_ is added automatically.
6. In the File upload box, select your certificate's .pfx file with a private key.
7. In the Password box, type the certificate's password.
8. Select Create.
9. To view the keys that are available in your tenant and confirm that you've created the
B2C_1A_B2cRestClientCertificate key, select Policy Keys.
5. Immediately after the closing <Metadata> element, add the following XML snippet:
<CryptographicKeys>
<Key Id="ClientCertificate" StorageReferenceId="B2C_1A_B2cRestClientCertificate" />
</CryptographicKeys>
After you add the snippet, your technical profile should look like the following XML code:
NOTE
Run Now requires at least one application to be preregistered on the tenant. To learn how to register applications,
see the Azure AD B2C Get started article or the Application registration article.
2. Open B2C_1A_signup_signin, the relying party (RP ) custom policy that you uploaded, and then select
Run now.
3. Test the process by typing Test in the Given Name box. Azure AD B2C displays an error message at the
top of the window.
4. In the Given Name box, type a name (other than "Test"). Azure AD B2C signs up the user and then sends
a loyalty number to your application. Note the number in this JWT example:
{
"typ": "JWT",
"alg": "RS256",
"kid": "X5eXk4xyojNFum1kl2Ytv8dlNP4-c57dO6QGTVBwaNk"
}.{
"exp": 1507125903,
"nbf": 1507122303,
"ver": "1.0",
"iss": "https://contoso.b2clogin.com/f06c2fe8-709f-4030-85dc-38a4bfd9e82d/v2.0/",
"aud": "e1d2612f-c2bc-4599-8e7b-d874eaca1ee1",
"acr": "b2c_1a_signup_signin",
"nonce": "defaultNonce",
"iat": 1507122303,
"auth_time": 1507122303,
"loyaltyNumber": "290",
"given_name": "Emily",
"emails": ["B2cdemo@outlook.com"]
}
NOTE
If you receive the error message, The name is not valid, please provide a valid name, it means that Azure AD B2C
successfully called your RESTful service while it presented the client certificate. The next step is to validate the
certificate.
Replace the certificate's Subject name, Issuer name, and Certificate thumbprint values with your certificate
values.
6.2 Add the IsValidClientCertificate function
Open the Controllers\IdentityController.cs file, and then add to the Identity controller class the following
function:
// Basic verification
if (clientCertInRequest.Verify() == false)
{
Trace.TraceError("Basic verification failed");
return false;
}
if (!foundIssuerCN)
{
Trace.TraceError($"Issuer '{clientCertInRequest.Issuer}' is not valid");
return false;
}
// 5. If you also want to test whether the certificate chains to a trusted root authority, you can
uncomment the following code:
//
//X509Chain certChain = new X509Chain();
//certChain.Build(certificate);
//bool isValidCertChain = true;
//foreach (X509ChainElement chElement in certChain.ChainElements)
//{
// if (!chElement.Certificate.Verify())
// {
// isValidCertChain = false;
// break;
// }
//}
//if (!isValidCertChain) return false;
return true;
}
In the preceding sample code, we accept the certificate as valid only if all the following conditions are met:
The certificate is not expired and is active for the current time on server.
The Subject name of the certificate is equal to the ClientCertificate:Subject application setting value.
The Issuer name of the certificate is equal to the ClientCertificate:Issuer application setting value.
The thumbprint of the certificate is equal to the ClientCertificate:Thumbprint application setting value.
IMPORTANT
Depending on the sensitivity of your service, you might need to add more validations. For example, you might need to test
whether the certificate chains to a trusted root authority, issuer organization name validation, and so on.
if (IsValidClientCertificate() == false)
{
return Content(HttpStatusCode.Conflict, new B2CResponseContent("Your client certificate is not valid",
HttpStatusCode.Conflict));
}
After you add the snippet, your Identity controller should look like the following code:
NOTE
In Azure Active Directory B2C, custom policies are designed primarily to address complex scenarios. For most scenarios, we
recommend that you use built-in user flows.
In this article, you create a custom attribute in your Azure Active Directory B2C (Azure AD B2C ) directory. You'll
use this new attribute as a custom claim in the profile edit user journey.
Prerequisites
Follow the steps in the article Azure Active Directory B2C: Get started with custom policies.
<!-- Provide objectId and appId before using extension properties. -->
<Metadata>
<Item Key="ApplicationObjectId">insert objectId here</Item>
<Item Key="ClientId">insert appId here</Item>
</Metadata>
<!-- End of changes -->
<CryptographicKeys>
<Key Id="issuer_secret" StorageReferenceId="TokenSigningKeyContainer" />
</CryptographicKeys>
<IncludeInSso>false</IncludeInSso>
<UseTechnicalProfileForSessionManagement ReferenceId="SM-Noop" />
</TechnicalProfile>
</ClaimsProvider>
</ClaimsProviders>
NOTE
When the TechnicalProfile writes for the first time to the newly created extension property, you might experience a one-
time error. The extension property is created the first time it's used.
<RelyingParty>
<DefaultUserJourney ReferenceId="ProfileEdit" />
<TechnicalProfile Id="PolicyProfile">
<DisplayName>PolicyProfile</DisplayName>
<Protocol Name="OpenIdConnect" />
<OutputClaims>
<OutputClaim ClaimTypeReferenceId="objectId" PartnerClaimType="sub"/>
<OutputClaim ClaimTypeReferenceId="city" />
3. Open the TrustFrameworkExtensions.xml file and add the <ClaimsSchema> element and its child elements
to the BuildingBlocks element:
<BuildingBlocks>
<ClaimsSchema>
<ClaimType Id="extension_loyaltyId">
<DisplayName>Loyalty Identification Tag</DisplayName>
<DataType>string</DataType>
<UserHelpText>Your loyalty number from your membership card</UserHelpText>
<UserInputType>TextBox</UserInputType>
</ClaimType>
</ClaimsSchema>
</BuildingBlocks>
4. Add the same ClaimType definition to TrustFrameworkBase.xml. It's not necessary to add a ClaimType
definition in both the base and the extensions files. However, the next steps add the extension_loyaltyId to
TechnicalProfiles in the base file. So the policy validator rejects the upload of the base file without it. It
might be useful to trace the execution of the user journey named ProfileEdit in the
TrustFrameworkBase.xml file. Search for the user journey with the same name in your editor. Observe
that Orchestration step 5 invokes the TechnicalProfileReferenceID="SelfAsserted-ProfileUpdate.
Search and inspect this TechnicalProfile to familiarize yourself with the flow.
5. Open the TrustFrameworkBase.xml file and add loyaltyId as an input and output claim in the
TechnicalProfile SelfAsserted-ProfileUpdate:
<TechnicalProfile Id="SelfAsserted-ProfileUpdate">
<DisplayName>User ID signup</DisplayName>
<Protocol Name="Proprietary" Handler="Web.TPEngine.Providers.SelfAssertedAttributeProvider,
Web.TPEngine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
<Metadata>
<Item Key="ContentDefinitionReferenceId">api.selfasserted.profileupdate</Item>
</Metadata>
<IncludeInSso>false</IncludeInSso>
<InputClaims>
<InputClaim ClaimTypeReferenceId="alternativeSecurityId" />
<InputClaim ClaimTypeReferenceId="userPrincipalName" />
<InputClaim ClaimTypeReferenceId="givenName" />
<InputClaim ClaimTypeReferenceId="surname" />
</OutputClaims>
<ValidationTechnicalProfiles>
<ValidationTechnicalProfile ReferenceId="AAD-UserWriteProfileUsingObjectId" />
</ValidationTechnicalProfiles>
</TechnicalProfile>
</PersistedClaims>
<IncludeTechnicalProfile ReferenceId="AAD-Common" />
</TechnicalProfile>
<TechnicalProfile Id="AAD-UserReadUsingObjectId">
<Metadata>
<Item Key="Operation">Read</Item>
<Item Key="RaiseErrorIfClaimsPrincipalDoesNotExist">true</Item>
</Metadata>
<IncludeInSso>false</IncludeInSso>
<InputClaims>
<InputClaim ClaimTypeReferenceId="objectId" Required="true" />
</InputClaims>
<OutputClaims>
<OutputClaim ClaimTypeReferenceId="signInNames.emailAddress" />
<OutputClaim ClaimTypeReferenceId="displayName" />
<OutputClaim ClaimTypeReferenceId="otherMails" />
<OutputClaim ClaimTypeReferenceId="givenName" />
<OutputClaim ClaimTypeReferenceId="surname" />
</OutputClaims>
<IncludeTechnicalProfile ReferenceId="AAD-Common" />
</TechnicalProfile>
Next steps
1. Add the new claim to the flows to sign in to social accounts by changing the following TechnicalProfiles.
Social and federated accounts use these two TechnicalProfiles to sign in. They write and read user data by
using the alternativeSecurityId as the locator of the user object.
<TechnicalProfile Id="AAD-UserWriteUsingAlternativeSecurityId">
<TechnicalProfile Id="AAD-UserReadUsingAlternativeSecurityId">
2. Use the same extension attributes between built-in and custom policies. When you add extension, or
custom, attributes via the portal experience, those attributes are registered by using the b2c-extensions-
app that exists in every B2C tenant. Take the following steps to use extension attributes in your custom
policy:
a. Within your B2C tenant in portal.azure.com, navigate to Azure Active Directory and select App
registrations. b. Find your b2c-extensions-app and select it. c. Under Essentials, enter the Application
ID and the Object ID. d. Include them in your AAD -Common TechnicalProfile metadata:
<ClaimsProviders>
<ClaimsProvider>
<DisplayName>Azure Active Directory</DisplayName>
<TechnicalProfile Id="AAD-Common">
<DisplayName>Azure Active Directory</DisplayName>
<Protocol Name="Proprietary" Handler="Web.TPEngine.Providers.AzureActiveDirectoryProvider,
Web.TPEngine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
<!-- Provide objectId and appId before using extension properties. -->
<Metadata>
<Item Key="ApplicationObjectId">insert objectId here</Item> <!-- This is the "Object ID"
from the "b2c-extensions-app"-->
<Item Key="ClientId">insert appId here</Item> <!--This is the "Application ID" from the
"b2c-extensions-app"-->
</Metadata>
3. Stay consistent with the portal experience. Create these attributes by using the portal UI before you use
them in your custom policies. When you create an attribute ActivationStatus in the portal, you must refer
to it as follows:
NOTE
A TechnicalProfile is an element type, or function, that defines an endpoint’s name, metadata, and protocol. The
TechnicalProfile details the exchange of claims that the Identity Experience Framework performs. When this function is
called in an orchestration step or from another TechnicalProfile, the InputClaims and OutputClaims are provided as
parameters by the caller.
Extension attributes in the Graph API are named by using the convention
extension_ApplicationObjectID_attributename .
Custom policies refer to extension attributes as extension_attributename. This reference omits the
ApplicationObjectId in XML.
You have to specify the attribute ID in the following format extension_attributename wherever it is being referenced.
Collect Azure Active Directory B2C logs with
Application Insights
12/9/2019 • 3 minutes to read • Edit Online
This article provides steps for collecting logs from Active Directory B2C (Azure AD B2C ) so that you can diagnose
problems with your custom policies. Application Insights provides a way to diagnose exceptions and visualize
application performance issues. Azure AD B2C includes a feature for sending data to Application Insights.
The detailed activity logs described here should be enabled ONLY during the development of your custom
policies.
WARNING
Do not enable development mode in production. Logs collect all claims sent to and from identity providers. You as the
developer assume responsibility for any personal data collected in your Application Insights logs. These detailed logs are
collected only when the policy is placed in DEVELOPER MODE.
DeploymentMode="Development"
UserJourneyRecorderEndpoint="urn:journeyrecorder:applicationinsights"
3. If it doesn't already exist, add a <UserJourneyBehaviors> child node to the <RelyingParty> node. It must be
located immediately after
<DefaultUserJourney ReferenceId="UserJourney Id" from your extensions policy, or equivalent (for
example:SignUpOrSigninWithAAD" />
.
4. Add the following node as a child of the <UserJourneyBehaviors> element. Make sure to replace
{Your Application Insights Key} with the Application Insights Instrumentation Key that you recorded
earlier.
<JourneyInsights TelemetryEngine="ApplicationInsights" InstrumentationKey="{Your Application Insights
Key}" DeveloperMode="true" ClientEnabled="false" ServerEnabled="true" TelemetryVersion="1.0.0" />
<TrustFrameworkPolicy
...
TenantId="fabrikamb2c.onmicrosoft.com"
PolicyId="SignUpOrSignInWithAAD"
DeploymentMode="Development"
UserJourneyRecorderEndpoint="urn:journeyrecorder:applicationinsights"
>
...
<RelyingParty>
<DefaultUserJourney ReferenceId="UserJourney ID from your extensions policy, or equivalent (for
example: SignUpOrSigninWithAzureAD)" />
<UserJourneyBehaviors>
<JourneyInsights TelemetryEngine="ApplicationInsights" InstrumentationKey="{Your Application
Insights Key}" DeveloperMode="true" ClientEnabled="false" ServerEnabled="true" TelemetryVersion="1.0.0"
/>
</UserJourneyBehaviors>
...
</TrustFrameworkPolicy>
QUERY DESCRIPTION
traces | where timestamp > ago(1d) See all of the logs generated by Azure AD B2C for the last day
If you use Azure Active Directory B2C (Azure AD B2C ) custom policies, you might experience challenges setting up
the Identity Experience Framework in its policy language XML format. Learning to write custom policies can be like
learning a new language. In this article, we describe some tools and tips that can help you discover and resolve
issues.
This article focuses on troubleshooting your Azure AD B2C custom policy configuration. It doesn't address the
relying party application or its identity library.
XML editing
The most common error in setting up custom policies is improperly formatted XML. A good XML editor is nearly
essential. It displays XML natively, color-codes content, pre-fills common terms, keeps XML elements indexed, and
can validate against an XML schema.
Two of our favorite editors are Visual Studio Code and Notepad++.
XML schema validation identifies errors before you upload your XML file. In the root folder of the starter pack, get
the XML schema definition file TrustFrameworkPolicy_0.3.0.0.xsd. To find out how to use the XSD schema file for
validation in your editor, look for XML tools and XML validation or similar in the editor's documentation.
You might find a review of XML rules helpful. Azure AD B2C rejects any XML formatting errors that it detects.
Occasionally, incorrectly formatted XML might cause error messages that are misleading.
Error snippet:
...makes a reference to ClaimType with id "displayName" but neither the policy nor any of its base policies
contain such an element
The ClaimType value might be misspelled, or does not exist in the schema.
ClaimType values must be defined in at least one of the files in the policy. For example:
<ClaimType Id="issuerUserId">
If ClaimType is defined in the extensions file, but it's also used in a TechnicalProfile value in the base file,
uploading the base file results in an error.
The causes for this error can be the same as for the ClaimType error.
Error snippet:
Reason: User is currently logged as a user of 'yourtenant.onmicrosoft.com' tenant. In order to manage
'yourtenant.onmicrosoft.com', please login as a user of 'yourtenant.onmicrosoft.com' tenant
Check that the TenantId value in the <TrustFrameworkPolicy\> and <BasePolicy\> elements match your target
Azure AD B2C tenant.
Recommended practices
Keep multiple versions of your scenarios. Group them in a project with your application. The base,
extensions, and relying party files are directly dependent on each other. Save them as a group. As new features are
added to your policies, keep separate working versions. Stage working versions in your own file system with the
application code they interact with. Your applications might invoke many different relying party policies in a tenant.
They might become dependent on the claims that they expect from your Azure AD B2C policies.
Develop and test technical profiles with known user journeys. Use tested starter pack policies to set up your
technical profiles. Test them separately before you incorporate them into your own user journeys.
Develop and test user journeys with tested technical profiles. Change the orchestration steps of a user
journey incrementally. Progressively build your intended scenarios.
Next steps
Available on GitHub, download the active-directory-b2c-custom-policy-starterpack .zip archive. You can also clone
the repository:
NOTE
This feature is in public preview.
When you use Azure Active Directory B2C (Azure AD B2C ) together with Azure Application Insights, you can get
detailed and customized event logs for your user journeys. In this article, you learn how to:
Gain insights on user behavior.
Troubleshoot your own policies in development or in production.
Measure performance.
Create notifications from Application Insights.
How it works
The Identity Experience Framework in Azure AD B2C includes the provider
Handler="Web.TPEngine.Providers.AzureApplicationInsightsProvider, Web.TPEngine, Version=1.0.0.0 . It sends event
data directly to Application Insights by using the instrumentation key provided to Azure AD B2C.
A technical profile uses this provider to define an event from Azure AD B2C. The profile specifies the name of the
event, the claims that are recorded, and the instrumentation key. To post an event, the technical profile is then
added as an orchestration step , or as a validation technical profile in a custom user journey.
Application Insights can unify the events by using a correlation ID to record a user session. Application Insights
makes the event and session available within seconds and presents many visualization, export, and analytical tools.
Prerequisites
Complete the steps in Get started with custom policies. This article assumes that you're using the custom policy
starter pack. But the starter pack isn't required.
AzureInsights-UserSignup Creates a UserSignup event when the user triggers the sign-
up option in a sign-up/sign-in journey.
<ClaimsProvider>
<DisplayName>Application Insights</DisplayName>
<TechnicalProfiles>
<TechnicalProfile Id="AzureInsights-SignInRequest">
<InputClaims>
<!-- An input claim with a PartnerClaimType="eventName" is required. This is used by the
AzureApplicationInsightsProvider to create an event with the specified value. -->
<InputClaim ClaimTypeReferenceId="EventType" PartnerClaimType="eventName" DefaultValue="SignInRequest"
/>
</InputClaims>
<IncludeTechnicalProfile ReferenceId="AzureInsights-Common" />
</TechnicalProfile>
<TechnicalProfile Id="AzureInsights-SignInComplete">
<InputClaims>
<InputClaim ClaimTypeReferenceId="EventType" PartnerClaimType="eventName"
DefaultValue="SignInComplete" />
<InputClaim ClaimTypeReferenceId="federatedUser" PartnerClaimType="{property:FederatedUser}"
DefaultValue="false" />
<InputClaim ClaimTypeReferenceId="parsedDomain" PartnerClaimType="{property:FederationPartner}"
DefaultValue="Not Applicable" />
</InputClaims>
<IncludeTechnicalProfile ReferenceId="AzureInsights-Common" />
</TechnicalProfile>
<TechnicalProfile Id="AzureInsights-UserSignup">
<InputClaims>
<InputClaim ClaimTypeReferenceId="EventType" PartnerClaimType="eventName" DefaultValue="UserSignup" />
</InputClaims>
<IncludeTechnicalProfile ReferenceId="AzureInsights-Common" />
</TechnicalProfile>
<TechnicalProfile Id="AzureInsights-Common">
<DisplayName>Alternate Email</DisplayName>
<Protocol Name="Proprietary" Handler="Web.TPEngine.Providers.Insights.AzureApplicationInsightsProvider,
Web.TPEngine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
<Metadata>
<!-- The ApplicationInsights instrumentation key which will be used for logging the events -->
<Item Key="InstrumentationKey">xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx</Item>
<!-- A Boolean that indicates whether developer mode is enabled. This controls how events are
buffered. In a development environment with minimal event volume, enabling developer mode results in events
being sent immediately to ApplicationInsights. -->
<Item Key="DeveloperMode">false</Item>
<!-- A Boolean that indicates whether telemetry should be enabled or not. -->
<Item Key="DisableTelemetry ">false</Item>
</Metadata>
<InputClaims>
<!-- Properties of an event are added through the syntax {property:NAME}, where NAME is property being
added to the event. DefaultValue can be either a static value or a value that's resolved by one of the
supported DefaultClaimResolvers. -->
<InputClaim ClaimTypeReferenceId="PolicyId" PartnerClaimType="{property:Policy}" DefaultValue="
{Policy:PolicyId}" />
<InputClaim ClaimTypeReferenceId="CorrelationId" PartnerClaimType="{property:JourneyId}" />
<InputClaim ClaimTypeReferenceId="Culture" PartnerClaimType="{property:Culture}" DefaultValue="
{Culture:RFC5646}" />
</InputClaims>
</TechnicalProfile>
</TechnicalProfiles>
</ClaimsProvider>
IMPORTANT
Change the instrumentation key in the AzureInsights-Common technical profile to the GUID that your Application Insights
resource provides.
Add the technical profiles as orchestration steps
Call Azure-Insights-SignInRequest as orchestration step 2 to track that a sign-in/sign-up request has been
received:
Immediately before the SendClaims orchestration step, add a new step that calls Azure-Insights-UserSignup . It's
triggered when the user selects the sign-up button in a sign-up/sign-in journey.
<!-- Handles the user clicking the sign up link in the local account sign in page -->
<OrchestrationStep Order="8" Type="ClaimsExchange">
<Preconditions>
<Precondition Type="ClaimsExist" ExecuteActionsIf="false">
<Value>newUser</Value>
<Action>SkipThisOrchestrationStep</Action>
</Precondition>
<Precondition Type="ClaimEquals" ExecuteActionsIf="true">
<Value>newUser</Value>
<Value>false</Value>
<Action>SkipThisOrchestrationStep</Action>
</Precondition>
</Preconditions>
<ClaimsExchanges>
<ClaimsExchange Id="TrackUserSignUp" TechnicalProfileReferenceId="AzureInsights-UserSignup" />
</ClaimsExchanges>
</OrchestrationStep>
Immediately after the SendClaims orchestration step, call Azure-Insights-SignInComplete . This step shows a
successfully completed journey.
IMPORTANT
After you add the new orchestration steps, renumber the steps sequentially without skipping any integers from 1 to N.
Azure Active Directory B2C (Azure AD B2C ) custom policies that use the Identity Experience Framework provide
your organization with a centralized service. This service reduces the complexity of identity federation in a large
community of interest. The complexity is reduced to a single trust relationship and a single metadata exchange.
Azure AD B2C custom policies use the Identity Experience Framework to enable you to answer the following
questions:
What are the legal, security, privacy, and data protection policies that must be adhered to?
Who are the contacts and what are the processes for becoming an accredited participant?
Who are the accredited identity information providers (also known as "claims providers") and what do they
offer?
Who are the accredited relying parties (and optionally, what do they require)?
What are the technical “on the wire” interoperability requirements for participants?
What are the operational “runtime” rules that must be enforced for exchanging digital identity information?
To answer all these questions, Azure AD B2C custom policies that use the Identity Experience Framework use the
Trust Framework (TF ) construct. Let’s consider this construct and what it provides.
NOTE
We collectively refer to all the possible types of identity information that might be exchanged as "claims": claims about an end
user’s authentication credential, identity vetting, communication device, physical location, personally identifying attributes,
and so on.
We use the term "claims"--rather than "attributes"--because in online transactions, these data artifacts are not facts that can
be directly verified by the relying party. Rather they're assertions, or claims, about facts for which the relying party must
develop sufficient confidence to grant the end user’s requested transaction.
We also use the term "claims" because Azure AD B2C custom policies that use the Identity Experience Framework are
designed to simplify the exchange of all types of digital identity information in a consistent manner regardless of whether the
underlying protocol is defined for user authentication or attribute retrieval. Likewise, we use the term "claims providers" to
collectively refer to identity providers, attribute providers, and attribute verifiers when we do not want to distinguish between
their specific functions.
Thus they govern how identity information is exchanged between a relying party, identity and attribute providers,
and attribute verifiers. They control which identity and attribute providers are required for a relying party’s
authentication. They should be considered as a domain-specific language (DSL ), that is, a computer language that's
specialized for a particular application domain with inheritance, if statements, polymorphism.
These policies constitute the machine-readable portion of the TF construct in Azure AD B2C Custom policies
leveraging the Identity Experience Framework. They include all the operational details, including claims providers’
metadata and technical profiles, claims schema definitions, claims transformation functions, and user journeys that
are filled in to facilitate operational orchestration and automation.
They are assumed to be living documents because there is a good chance that their contents will change over time
concerning the active participants declared in the policies. There is also the potential that the terms and conditions
for being a participant might change.
Federation setup and maintenance are vastly simplified by shielding relying parties from ongoing trust and
connectivity reconfigurations as different claims providers/verifiers join or leave (the community represented by)
the set of policies.
Interoperability is another significant challenge. Additional claims providers/verifiers must be integrated, because
relying parties are unlikely to support all the necessary protocols. Azure AD B2C custom policies solve this
problem by supporting industry-standard protocols and by applying specific user journeys to transpose requests
when relying parties and attribute providers do not support the same protocol.
User journeys include protocol profiles and metadata that are used to plumb “on the wire” interoperability between
the relying party and other participants. There are also operational runtime rules that are applied to identity
information exchange request/response messages for enforcing compliance with published policies as part of the
TF specification. The idea of user journeys is key to the customization of the customer experience. It also sheds light
on how the system works at the protocol level.
On that basis, relying party applications and portals can, depending on their context, invoke Azure AD B2C custom
policies that leverage the Identity Experience Framework passing the name of a specific policy and get precisely the
behavior and information exchange they want without any muss, fuss, or risk.
TrustFrameworkPolicy
9/17/2019 • 4 minutes to read • Edit Online
NOTE
In Azure Active Directory B2C, custom policies are designed primarily to address complex scenarios. For most scenarios, we
recommend that you use built-in user flows.
A custom policy is represented as one or more XML -formatted files, which refer to each other in a hierarchical
chain. The XML elements define elements of the policy, such as the claims schema, claims transformations, content
definitions, claims providers, technical profiles, user journey, and orchestration steps. Each policy file is defined
within the top-level TrustFrameworkPolicy element of a policy file.
<TrustFrameworkPolicy
xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="https://www.w3.org/2001/XMLSchema"
xmlns="http://schemas.microsoft.com/online/cpim/schemas/2013/06"
PolicySchemaVersion="0.3.0.0"
TenantId="mytenant.onmicrosoft.com"
PolicyId="B2C_1A_TrustFrameworkBase"
PublicPolicyUri="http://mytenant.onmicrosoft.com/B2C_1A_TrustFrameworkBase">
...
<TrustFrameworkPolicy
xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="https://www.w3.org/2001/XMLSchema"
xmlns="http://schemas.microsoft.com/online/cpim/schemas/2013/06"
PolicySchemaVersion="0.3.0.0"
TenantId="mytenant.onmicrosoft.com"
PolicyId="B2C_1A_TrustFrameworkBase"
PublicPolicyUri="http://mytenant.onmicrosoft.com/B2C_1A_TrustFrameworkBase">
Inheritance model
These types of policy files are typically used in a user journey:
A Base file that contains most of the definitions. To help with troubleshooting and long-term maintenance of
your policies, it is recommended that you make a minimum number of changes to this file.
An Extensions file that holds the unique configuration changes for your tenant. This policy file is derived from
the Base file. Use this file to add new functionality or override existing functionality. For example, use this file to
federate with new identity providers.
A Relying Party (RP ) file that is the single task-focused file that is invoked directly by the relying party
application, such as your web, mobile, or desktop applications. Each unique task such as sign-up or sign-in,
password reset, or profile edit, requires its own RP policy file. This policy file is derived from the Extensions file.
A relying party application calls the RP policy file to execute a specific task. For example, to initiate the sign-in flow.
The Identity Experience Framework in Azure AD B2C adds all of the elements first from the Base file, and then
from the Extensions file, and finally from the RP policy file to assemble the current policy in effect. Elements of the
same type and name in the RP file override those elements in the Extensions, and Extensions overrides Base. The
following diagram shows the relationship between the policy files and the relying party applications.
The inheritance model is as follows:
The parent policy and child policy are of the same schema.
The child policy at any level can inherit from the parent policy and extend it by adding new elements.
There is no limit on the number of levels.
For more information, see Get started with custom policies.
Base policy
To inherit a policy from another policy, a BasePolicy element must be declared under the TrustFrameworkPolicy
element of the policy file. The BasePolicy element is a reference to the base policy from which this policy is
derived.
The BasePolicy element contains the following elements:
The following example shows how to specify a base policy. This B2C_1A_TrustFrameworkExtensions policy is
derived from the B2C_1A_TrustFrameworkBase policy.
<TrustFrameworkPolicy
xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="https://www.w3.org/2001/XMLSchema"
xmlns="http://schemas.microsoft.com/online/cpim/schemas/2013/06"
PolicySchemaVersion="0.3.0.0"
TenantId="mytenant.onmicrosoft.com"
PolicyId="B2C_1A_TrustFrameworkExtensions"
PublicPolicyUri="http://mytenant.onmicrosoft.com/B2C_1A_TrustFrameworkExtensions">
<BasePolicy>
<TenantId>yourtenant.onmicrosoft.com</TenantId>
<PolicyId>B2C_1A_TrustFrameworkBase</PolicyId>
</BasePolicy>
...
</TrustFrameworkPolicy>
Policy execution
A relying party application, such as a web, mobile, or desktop application, calls the relying party (RP ) policy. The
RP policy file executes a specific task, such as signing in, resetting a password, or editing a profile. The RP policy
configures the list of claims the relying party application receives as part of the token that is issued. Multiple
applications can use the same policy. All applications receive the same token with claims, and the user goes
through the same user journey. A single application can use multiple policies.
Inside the RP policy file, you specify the DefaultUserJourney element, which points to the UserJourney. The user
journey usually is defined in the Base or Extensions policy.
B2C_1A_signup_signin policy:
<RelyingParty>
<DefaultUserJourney ReferenceId="SignUpOrSignIn">
...
B2C_1A_TrustFrameWorkBase or B2C_1A_TrustFrameworkExtensionPolicy:
<UserJourneys>
<UserJourney Id="SignUpOrSignIn">
...
A user journey defines the business logic of what a user goes through. Each user journey is a set of orchestration
steps that performs a series of actions, in sequence in terms of authentication and information collection.
The SocialAndLocalAccounts policy file in the starter pack contains the SignUpOrSignIn, ProfileEdit,
PasswordReset user journeys. You can add more user journeys for other scenarios, such as changing an email
address or linking and unlinking a social account.
The orchestration steps may call a Technical Profile. A technical profile provides a framework with a built-in
mechanism to communicate with different types of parties. For example, a technical profile can perform these
actions among others:
Render a user experience.
Allow users to sign in with social or an enterprise account, such as Facebook, Microsoft account, Google,
Salesforce or any other identity provider.
Set up phone verification for MFA.
Read and write data to and from an Azure AD B2C identity store.
Call a custom Restful API service.
The TrustFrameworkPolicy element contains the following elements:
BasePolicy as specified above
BuildingBlocks
ClaimsProviders
UserJourneys
RelyingParty
BuildingBlocks
12/12/2019 • 2 minutes to read • Edit Online
NOTE
In Azure Active Directory B2C, custom policies are designed primarily to address complex scenarios. For most scenarios, we
recommend that you use built-in user flows.
<TrustFrameworkPolicy
xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="https://www.w3.org/2001/XMLSchema"
xmlns="http://schemas.microsoft.com/online/cpim/schemas/2013/06"
PolicySchemaVersion="0.3.0.0"
TenantId="mytenant.onmicrosoft.com"
PolicyId="B2C_1A_TrustFrameworkBase"
PublicPolicyUri="http://mytenant.onmicrosoft.com/B2C_1A_TrustFrameworkBase">
<BuildingBlocks>
<ClaimsSchema>
...
</ClaimsSchema>
<Predicates>
...
</Predicates>
<PredicateValidations>
...
</PredicateValidations>
<ClaimsTransformations>
...
</ClaimsTransformations>
<ContentDefinitions>
...
</ContentDefinitions>
<Localization>
...
</Localization>
<DisplayControls>
...
</DisplayControls>
</BuildingBlocks>
The BuildingBlocks element contains the following elements that must be specified in the order defined:
ClaimsSchema - Defines the claim types that can be referenced as part of the policy. The claims schema is
the place where you declare your claim types. A claim type is similar to a variable in many programmatic
languages. You can use the claim type to collect data from the user of your application, receive claims from
social identity providers, send and receive data from a custom REST API, or store any internal data used by
your custom policy.
Predicates and PredicateValidationsInput - Enables you to perform a validation process to ensure that only
properly formed data is entered into a claim.
ClaimsTransformations - Contains a list of claims transformations that can be used in your policy. A claims
transformation converts one claim into another. In the claims transformation, you specify a transform
method, such as:
Changing the case of a string claim to the one specified. For example, changing a string from lowercase
to uppercase.
Comparing two claims and returning a claim with true indicating that the claims match, otherwise false.
Creating a string claim from the provided parameter in the policy.
Creating a random string using the random number generator.
Formatting a claim according to the provided format string. This transformation uses the C#
String.Format method.
InputValidation - This element allows you to perform boolean aggregations that are similar to and and or.
ContentDefinitions - Contains URLs for HTML5 templates to use in your user journey. In a custom policy, a
content definition defines the HTML5 page URI that's used for a specified step in the user journey. For
example, the sign-in or sign-up, password reset, or error pages. You can modify the look and feel by
overriding the LoadUri for the HTML5 file. Or you can create new content definitions according to your
needs. This element may contain a localized resources reference using a localization ID.
Localization - Allows you to support multiple languages. The localization support in policies allows you set
up the list of supported languages in a policy and pick a default language. Language-specific strings and
collections are also supported.
DisplayControls - Defines the controls to be displayed on a page. Display controls have special functionality
and interact with back-end validation technical profiles. Display controls are currently in preview.
ClaimsSchema
9/15/2019 • 7 minutes to read • Edit Online
NOTE
In Azure Active Directory B2C, custom policies are designed primarily to address complex scenarios. For most scenarios, we
recommend that you use built-in user flows.
The ClaimsSchema element defines the claim types that can be referenced as part of the policy. Claims schema is
the place where you declare your claims. A claim can be first name, last name, display name, phone number and
more. ClaimsSchema element contains list of ClaimType elements. The ClaimType element contains the Id
attribute, which is the claim name.
<BuildingBlocks>
<ClaimsSchema>
<ClaimType Id="Id">
<DisplayName>Surname</DisplayName>
<DataType>string</DataType>
<DefaultPartnerClaimTypes>
<Protocol Name="OAuth2" PartnerClaimType="family_name" />
<Protocol Name="OpenIdConnect" PartnerClaimType="family_name" />
<Protocol Name="SAML2"
PartnerClaimType="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname" />
</DefaultPartnerClaimTypes>
<UserHelpText>Your surname (also known as family name or last name).</UserHelpText>
<UserInputType>TextBox</UserInputType>
ClaimType
The ClaimType element contains the following attribute:
DefaultPartnerClaimTypes
The DefaultPartnerClaimTypes may contain the following element:
<ClaimType Id="surname">
<DisplayName>Surname</DisplayName>
<DataType>string</DataType>
<DefaultPartnerClaimTypes>
<Protocol Name="OAuth2" PartnerClaimType="family_name" />
<Protocol Name="OpenIdConnect" PartnerClaimType="family_name" />
<Protocol Name="SAML2" PartnerClaimType="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname" />
</DefaultPartnerClaimTypes>
</ClaimType>
As a result, the JWT token issued by Azure AD B2C, emits the family_name instead of ClaimType name surname.
{
"sub": "6fbbd70d-262b-4b50-804c-257ae1706ef2",
"auth_time": 1535013501,
"given_name": "David",
"family_name": "Williams",
"name": "David Williams",
}
Mask
The Mask element contains the following attributes:
The following example configures a PhoneNumber claim with the Simple mask:
<ClaimType Id="PhoneNumber">
<DisplayName>Phone Number</DisplayName>
<DataType>string</DataType>
<Mask Type="Simple">XXX-XXX-</Mask>
<UserHelpText>Your telephone number.</UserHelpText>
</ClaimType>
The Identity Experience Framework renders the phone number while hiding the first six digits:
The following example configures a AlternateEmail claim with the Regex mask:
<ClaimType Id="AlternateEmail">
<DisplayName>Please verify the secondary email linked to your account</DisplayName>
<DataType>string</DataType>
<Mask Type="Regex" Regex="(?<=.).(?=.*@)">*</Mask>
<UserInputType>Readonly</UserInputType>
</ClaimType>
The Identity Experience Framework renders only the first letter of the email address and the email domain name:
Restriction
The Restriction element may contain the following attribute:
Enumeration
The Enumeration element contains the following attributes:
The following example configures a city dropdown list claim with a default value set to New York :
<ClaimType Id="city">
<DisplayName>city where you work</DisplayName>
<DataType>string</DataType>
<UserInputType>DropdownSingleSelect</UserInputType>
<Restriction>
<Enumeration Text="Bellevue" Value="bellevue" SelectByDefault="false" />
<Enumeration Text="Redmond" Value="redmond" SelectByDefault="false" />
<Enumeration Text="New York" Value="new-york" SelectByDefault="true" />
</Restriction>
</ClaimType>
Pattern
The Pattern element can contain the following attributes:
The following example configures an email claim with regular expression input validation and help text:
<ClaimType Id="email">
<DisplayName>Email Address</DisplayName>
<DataType>string</DataType>
<DefaultPartnerClaimTypes>
<Protocol Name="OpenIdConnect" PartnerClaimType="email" />
</DefaultPartnerClaimTypes>
<UserHelpText>Email address that can be used to contact you.</UserHelpText>
<UserInputType>TextBox</UserInputType>
<Restriction>
<Pattern RegularExpression="^[a-zA-Z0-9.!#$%&'^_`{}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$"
HelpText="Please enter a valid email address." />
</Restriction>
</ClaimType>
The Identity Experience Framework renders the email address claim with email format input validation:
UserInputType
Azure AD B2C supports a variety of user input types, such as a textbox, password, and dropdown list that can be
used when manually entering claim data for the claim type. You must specify the UserInputType when you
collect information from the user by using a self-asserted technical profile.
TextBox
The TextBox user input type is used to provide a single-line text box.
<ClaimType Id="displayName">
<DisplayName>Display Name</DisplayName>
<DataType>string</DataType>
<UserHelpText>Your display name.</UserHelpText>
<UserInputType>TextBox</UserInputType>
</ClaimType>
EmailBox
The EmailBox user input type is used to provide a basic email input field.
<ClaimType Id="email">
<DisplayName>Email Address</DisplayName>
<DataType>string</DataType>
<UserHelpText>Email address that can be used to contact you.</UserHelpText>
<UserInputType>EmailBox</UserInputType>
<Restriction>
<Pattern RegularExpression="^[a-zA-Z0-9!#$%&'+^_`{}~-]+(?:\.[a-zA-Z0-9!#$%&'+^_`{}~-]+)*@(?:[a-zA-
Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$" HelpText="Please enter a
valid email address." />
</Restriction>
</ClaimType>
Password
The Password user input type is used to record a password entered by the user.
<ClaimType Id="password">
<DisplayName>Password</DisplayName>
<DataType>string</DataType>
<UserHelpText>Enter password</UserHelpText>
<UserInputType>Password</UserInputType>
</ClaimType>
DateTimeDropdown
The DateTimeDropdown user input type is used to provide a set of drop-downs to select a day, month, and year.
You can use Predicates and PredicateValidations elements to control the minimum and maximum date values. For
more information, see the Configure a date range section of Predicates and PredicateValidations.
<ClaimType Id="dateOfBirth">
<DisplayName>Date Of Birth</DisplayName>
<DataType>date</DataType>
<UserHelpText>The date on which you were born.</UserHelpText>
<UserInputType>DateTimeDropdown</UserInputType>
</ClaimType>
RadioSingleSelect
The RadioSingleSelect user input type is used to provide a collection of radio buttons that allows the user to
select one option.
<ClaimType Id="color">
<DisplayName>Preferred color</DisplayName>
<DataType>string</DataType>
<UserInputType>RadioSingleSelect</UserInputType>
<Restriction>
<Enumeration Text="Blue" Value="Blue" SelectByDefault="false" />
<Enumeration Text="Green " Value="Green" SelectByDefault="false" />
<Enumeration Text="Orange" Value="Orange" SelectByDefault="true" />
</Restriction>
</ClaimType>
DropdownSingleSelect
The DropdownSingleSelect user input type is used to provide a drop-down box that allows the user to select
one option.
<ClaimType Id="city">
<DisplayName>City where you work</DisplayName>
<DataType>string</DataType>
<UserInputType>DropdownSingleSelect</UserInputType>
<Restriction>
<Enumeration Text="Bellevue" Value="bellevue" SelectByDefault="false" />
<Enumeration Text="Redmond" Value="redmond" SelectByDefault="false" />
<Enumeration Text="New York" Value="new-york" SelectByDefault="true" />
</Restriction>
</ClaimType>
CheckboxMultiSelect
The CheckboxMultiSelect user input type is used to provide a collection of checkboxes that allows the user to
select multiple options.
<ClaimType Id="languages">
<DisplayName>Languages you speak</DisplayName>
<DataType>string</DataType>
<UserInputType>CheckboxMultiSelect</UserInputType>
<Restriction>
<Enumeration Text="English" Value="English" SelectByDefault="true" />
<Enumeration Text="France " Value="France" SelectByDefault="false" />
<Enumeration Text="Spanish" Value="Spanish" SelectByDefault="false" />
</Restriction>
</ClaimType>
Readonly
The Readonly user input type is used to provide a readonly field to display the claim and value.
<ClaimType Id="membershipNumber">
<DisplayName>Membership number</DisplayName>
<DataType>string</DataType>
<UserHelpText>Your membership number (read only)</UserHelpText>
<UserInputType>Readonly</UserInputType>
</ClaimType>
Paragraph
The Paragraph user input type is used to provide a field that shows text only in a paragraph tag. For example,
<p>text</p>.
<ClaimType Id="responseMsg">
<DisplayName>Error message: </DisplayName>
<DataType>string</DataType>
<AdminHelpText>A claim responsible for holding response messages to send to the relying
party</AdminHelpText>
<UserHelpText>A claim responsible for holding response messages to send to the relying party</UserHelpText>
<UserInputType>Paragraph</UserInputType>
<Restriction>
<Enumeration Text="B2C_V1_90001" Value="You cant sign in because you are a minor" />
<Enumeration Text="B2C_V1_90002" Value="This action can only be performed by gold members" />
<Enumeration Text="B2C_V1_90003" Value="You have not been enabled for this operation" />
</Restriction>
</ClaimType>
NOTE
In Azure Active Directory B2C, custom policies are designed primarily to address complex scenarios. For most scenarios, we
recommend that you use built-in user flows.
The ClaimsTransformations element contains a list of claims transformation functions that can be used in user
journeys as part of a custom policy. A claims transformation converts a given claim into another one. In the
claims transformation, you specify the transform method, for example adding an item to a string collection or
changing the case of a string.
To include the list of claims transformation functions that can be used in the user journeys, a
ClaimsTransformations XML element must be declared under the BuildingBlocks section of the policy.
<ClaimsTransformations>
<ClaimsTransformation Id="<identifier>" TransformationMethod="<method>">
...
</ClaimsTransformation>
</ClaimsTransformations>
ClaimsTransformation
The ClaimsTransformation element contains the following elements:
InputClaims
The InputClaims element contains the following element:
InputClaim
The InputClaim element contains the following attributes:
InputParameters
The InputParameters element contains the following element:
InputParameter
OutputClaims
The OutputClaims element contains the following element:
OutputClaim
The OutputClaim element contains the following attributes:
If input claim and the output claim are the same type (string, or boolean), you can use the same input claim as the
output claim. In this case, the claims transformation changes the input claim with the output value.
Example
For example, you may store the last version of your terms of services that the user accepted. When you update
the terms of services, you can ask the user to accept the new version. In the following example, the
HasTOSVersionChanged claims transformation compares the value of the TOSVersion claim with the value of
the LastTOSAcceptedVersion claim and then returns the boolean TOSVersionChanged claim.
<BuildingBlocks>
<ClaimsSchema>
<ClaimType Id="TOSVersionChanged">
<DisplayName>Indicates if the TOS version accepted by the end user is equal to the current
version</DisplayName>
<DataType>boolean</DataType>
</ClaimType>
<ClaimType Id="TOSVersion">
<DisplayName>TOS version</DisplayName>
<DataType>string</DataType>
</ClaimType>
<ClaimType Id="LastTOSAcceptedVersion">
<DisplayName>TOS version accepted by the end user</DisplayName>
<DataType>string</DataType>
</ClaimType>
</ClaimsSchema>
<ClaimsTransformations>
<ClaimsTransformation Id="HasTOSVersionChanged" TransformationMethod="CompareClaims">
<InputClaims>
<InputClaim ClaimTypeReferenceId="TOSVersion" TransformationClaimType="inputClaim1" />
<InputClaim ClaimTypeReferenceId="LastTOSAcceptedVersion" TransformationClaimType="inputClaim2" />
</InputClaims>
<InputParameters>
<InputParameter Id="operator" DataType="string" Value="NOT EQUAL" />
</InputParameters>
<OutputClaims>
<OutputClaim ClaimTypeReferenceId="TOSVersionChanged" TransformationClaimType="outputClaim" />
</OutputClaims>
</ClaimsTransformation>
</ClaimsTransformations>
</BuildingBlocks>
NOTE
In Azure Active Directory B2C, custom policies are designed primarily to address complex scenarios. For most scenarios, we
recommend that you use built-in user flows.
This article provides examples for using the boolean claims transformations of the Identity Experience Framework
schema in Azure Active Directory B2C (Azure AD B2C ). For more information, see ClaimsTransformations.
AndClaims
Performs an And operation of two boolean inputClaims and sets the outputClaim with result of the operation.
The following claims transformation demonstrates how to And two boolean ClaimTypes: isEmailNotExist , and
isSocialAccount . The output claim presentEmailSelfAsserted is set to true if the value of both input claims are
true . In an orchestration step, you can use a precondition to preset a self-asserted page, only if a social account
email is empty.
Example
Input claims:
inputClaim1: true
inputClaim2: false
Output claims:
outputClaim: false
AssertBooleanClaimIsEqualToValue
Checks that boolean values of two claims are equal, and throws an exception if they are not.
The following claims transformation demonstrates how to check the value of a boolean ClaimType with a true
value. If the value of the accountEnabled ClaimType is false, an error message is thrown.
The login-NonInteractive validation technical profile calls the AssertAccountEnabledIsTrue claims transformation.
<TechnicalProfile Id="login-NonInteractive">
...
<OutputClaimsTransformations>
<OutputClaimsTransformation ReferenceId="AssertAccountEnabledIsTrue" />
</OutputClaimsTransformations>
</TechnicalProfile>
The self-asserted technical profile calls the validation login-NonInteractive technical profile.
<TechnicalProfile Id="SelfAsserted-LocalAccountSignin-Email">
<Metadata>
<Item Key="UserMessageIfClaimsTransformationBooleanValueIsNotEqual">Custom error message if account is
disabled.</Item>
</Metadata>
<ValidationTechnicalProfiles>
<ValidationTechnicalProfile ReferenceId="login-NonInteractive" />
</ValidationTechnicalProfiles>
</TechnicalProfile>
Example
Input claims:
inputClaim: false
valueToCompareTo: true
Result: Error thrown
NotClaims
Performs a Not operation of the boolean inputClaim and sets the outputClaim with result of the operation.
Example
Input claims:
inputClaim: false
Output claims:
outputClaim: true
OrClaims
Computes an Or of two boolean inputClaims and sets the outputClaim with result of the operation.
The following claims transformation demonstrates how to Or two boolean ClaimTypes. In the orchestration step,
you can use a precondition to preset a self-asserted page, if the value of one of the claims is true .
Example
Input claims:
inputClaim1: true
inputClaim2: false
Output claims:
outputClaim: true
Date claims transformations
12/9/2019 • 3 minutes to read • Edit Online
NOTE
In Azure Active Directory B2C, custom policies are designed primarily to address complex scenarios. For most scenarios, we
recommend that you use built-in user flows.
This article provides examples for using the date claims transformations of the Identity Experience Framework
schema in Azure Active Directory B2C (Azure AD B2C ). For more information, see ClaimsTransformations.
AssertDateTimeIsGreaterThan
Checks that one date and time claim (string data type) is later than a second date and time claim (string data type),
and throws an exception.
The AssertDateTimeIsGreaterThan claims transformation is always executed from a validation technical profile
that is called by a self-asserted technical profile. The DateTimeGreaterThan self-asserted technical profile
metadata controls the error message that the technical profile presents to the user.
The following example compares the currentDateTime claim with the approvedDateTime claim. An error is thrown if
currentDateTime is later than approvedDateTime . The transformation treats values as equal if they are within 5
minutes (30000 milliseconds) difference.
<ClaimsTransformation Id="AssertApprovedDateTimeLaterThanCurrentDateTime"
TransformationMethod="AssertDateTimeIsGreaterThan">
<InputClaims>
<InputClaim ClaimTypeReferenceId="approvedDateTime" TransformationClaimType="leftOperand" />
<InputClaim ClaimTypeReferenceId="currentDateTime" TransformationClaimType="rightOperand" />
</InputClaims>
<InputParameters>
<InputParameter Id="AssertIfEqualTo" DataType="boolean" Value="false" />
<InputParameter Id="AssertIfRightOperandIsNotPresent" DataType="boolean" Value="true" />
<InputParameter Id="TreatAsEqualIfWithinMillseconds" DataType="int" Value="300000" />
</InputParameters>
</ClaimsTransformation>
<TechnicalProfile Id="login-NonInteractive">
...
<OutputClaimsTransformations>
<OutputClaimsTransformation ReferenceId="AssertApprovedDateTimeLaterThanCurrentDateTime" />
</OutputClaimsTransformations>
</TechnicalProfile>
The self-asserted technical profile calls the validation login-NonInteractive technical profile.
<TechnicalProfile Id="SelfAsserted-LocalAccountSignin-Email">
<Metadata>
<Item Key="DateTimeGreaterThan">Custom error message if the provided left operand is greater than the
right operand.</Item>
</Metadata>
<ValidationTechnicalProfiles>
<ValidationTechnicalProfile ReferenceId="login-NonInteractive" />
</ValidationTechnicalProfiles>
</TechnicalProfile>
Example
Input claims:
leftOperand: 2018-10-01T15:00:00.0000000Z
rightOperand: 2018-10-01T14:00:00.0000000Z
Result: Error thrown
ConvertDateToDateTimeClaim
Converts a Date ClaimType to a DateTime ClaimType. The claims transformation converts the time format and
adds 12:00:00 AM to the date.
The following example demonstrates the conversion of the claim dateOfBirth (date data type) to another claim
dateOfBirthWithTime (dateTime data type).
Example
Input claims:
inputClaim: 2019-06-01
Output claims:
outputClaim: 1559347200 (June 1, 2019 12:00:00 AM )
GetCurrentDateTime
Get the current UTC date and time and add the value to a ClaimType.
ITEM TRANSFORMATIONCLAIMTYPE DATA TYPE NOTES
Example
Output claims:
currentDateTime: 1534418820 (August 16, 2018 11:27:00 AM )
DateTimeComparison
Determine whether one dateTime is later, earlier, or equal to another. The result is a new boolean ClaimType
boolean with a value of true or false .
Use this claims transformation to determine if two ClaimTypes are equal, later, or earlier than each other. For
example, you may store the last time a user accepted your terms of services (TOS ). After 3 months, you can ask the
user to access the TOS again. To run the claim transformation, you first need to get the current dateTime and also
the last time user accepts the TOS.
<ClaimsTransformation Id="CompareLastTOSAcceptedWithCurrentDateTime"
TransformationMethod="DateTimeComparison">
<InputClaims>
<InputClaim ClaimTypeReferenceId="currentDateTime" TransformationClaimType="firstDateTime" />
<InputClaim ClaimTypeReferenceId="extension_LastTOSAccepted" TransformationClaimType="secondDateTime" />
</InputClaims>
<InputParameters>
<InputParameter Id="operator" DataType="string" Value="later than" />
<InputParameter Id="timeSpanInSeconds" DataType="int" Value="7776000" />
</InputParameters>
<OutputClaims>
<OutputClaim ClaimTypeReferenceId="isLastTOSAcceptedGreaterThanNow" TransformationClaimType="result" />
</OutputClaims>
</ClaimsTransformation>
Example
Input claims:
firstDateTime: 2018-01-01T00:00:00.100000Z
secondDateTime: 2018-04-01T00:00:00.100000Z
Input parameters:
operator: later than
timeSpanInSeconds: 7776000 (90 days)
Output claims:
result: true
General claims transformations
12/9/2019 • 2 minutes to read • Edit Online
NOTE
In Azure Active Directory B2C, custom policies are designed primarily to address complex scenarios. For most scenarios, we
recommend that you use built-in user flows.
This article provides examples for using general claims transformations of the Identity Experience Framework
schema in Azure Active Directory B2C (Azure AD B2C ). For more information, see ClaimsTransformations.
DoesClaimExist
Checks if the inputClaim exists or not and sets outputClaim to true or false accordingly.
Use this claims transformation to check if a claim exists or contains any value. The return value is a boolean that
indicates whether the claim exists. Following example checks if the email address exists.
Example
Input claims:
inputClaim: someone@contoso.com
Output claims:
outputClaim: true
Hash
Hash the provided plain text using the salt and a secret. The hashing algorithm used is SHA-256.
ITEM TRANSFORMATIONCLAIMTYPE DATA TYPE NOTES
Example
Input claims:
plaintext: MyPass@word1
salt: 487624568
randomizerSecret: B2C_1A_AccountTransformSecret
Output claims:
outputClaim: CdMNb/KTEfsWzh9MR1kQGRZCKjuxGMWhA5YQNihzV6U=
Integer claims transformations
12/9/2019 • 2 minutes to read • Edit Online
NOTE
In Azure Active Directory B2C, custom policies are designed primarily to address complex scenarios. For most scenarios, we
recommend that you use built-in user flows.
This article provides examples for using the integer claims transformations of the Identity Experience Framework
schema in Azure Active Directory B2C (Azure AD B2C ). For more information, see ClaimsTransformations.
ConvertNumberToStringClaim
Converts a long data type into a string data type.
In this example, the numericUserId claim with a value type of long is converted to a UserId claim with a value type
of string.
Example
Input claims:
inputClaim: 12334 (long)
Output claims:
outputClaim: "12334" (string)
JSON claims transformations
12/12/2019 • 5 minutes to read • Edit Online
NOTE
In Azure Active Directory B2C, custom policies are designed primarily to address complex scenarios. For most scenarios, we
recommend that you use built-in user flows.
This article provides examples for using the JSON claims transformations of the Identity Experience Framework
schema in Azure Active Directory B2C (Azure AD B2C ). For more information, see ClaimsTransformations.
GenerateJson
Use either claim values or constants to generate a JSON string. The path string following dot notation is used to
indicate where to insert the data into a JSON string. After splitting by dots, any integers are interpreted as the
index of a JSON array and non-integers are interpreted as the index of a JSON object.
InputClaim Any string following dot string The JsonPath of the JSON
notation where the claim value will be
inserted into.
InputParameter Any string following dot string The JsonPath of the JSON
notation where the constant string
value will be inserted into.
The following example generates a JSON string based on the claim value of "email" and "otp" as well as constant
strings.
Example
The following claims transformation outputs a JSON string claim that will be the body of the request sent to
SendGrid (a third-party email provider). The JSON object's structure is defined by the IDs in dot notation of the
InputParameters and the TransformationClaimTypes of the InputClaims. Numbers in the dot notation imply
arrays. The values come from the InputClaims' values and the InputParameters' "Value" properties.
Input claims :
email, transformation claim type personalizations.0.to.0.email: "someone@example.com"
otp, transformation claim type personalizations.0.dynamic_template_data.otp "346349"
Input parameter:
template_id: "d-4c56ffb40fa648b1aa6822283df94f60"
from.email: "service@contoso.com"
personalizations.0.subject "Contoso account email verification code"
Output claim:
requestBody: JSON value
{
"personalizations": [
{
"to": [
{
"email": "someone@example.com"
}
],
"dynamic_template_data": {
"otp": "346349",
"verify-email" : "someone@example.com"
},
"subject": "Contoso account email verification code"
}
],
"template_id": "d-989077fbba9746e89f3f6411f596fb96",
"from": {
"email": "service@contoso.com"
}
}
GetClaimFromJson
Get a specified element from a JSON data.
In the following example, the claims transformation extracted the emailAddress element from the JSON data:
{"emailAddress": "someone@example.com", "displayName": "Someone"}
Example
Input claims:
inputJson: {"emailAddress": "someone@example.com", "displayName": "Someone"}
Input parameter:
claimToExtract: emailAddress
Output claims:
extractedClaim: someone@example.com
GetClaimsFromJsonArray
Get a list of specified elements from Json data.
OutputClaim Collection string, int, boolean, and List of claims to extract. The
datetime name of the claim should be
equal to the one specified in
jsonSourceClaim input claim.
In the following example, the claims transformation extracts the following claims: email (string), displayName
(string), membershipNum (int), active (boolean) and birthdate (datetime) from the JSON data.
[{"key":"email","value":"someone@example.com"}, {"key":"displayName","value":"Someone"},
{"key":"membershipNum","value":6353399}, {"key":"active","value":true}, {"key":"birthdate","value":"1980-09-
23T00:00:00Z"}]
<ClaimsTransformation Id="GetClaimsFromJson" TransformationMethod="GetClaimsFromJsonArray">
<InputClaims>
<InputClaim ClaimTypeReferenceId="jsonSourceClaim" TransformationClaimType="jsonSource" />
</InputClaims>
<InputParameters>
<InputParameter Id="errorOnMissingClaims" DataType="boolean" Value="false" />
<InputParameter Id="includeEmptyClaims" DataType="boolean" Value="false" />
<InputParameter Id="jsonSourceKeyName" DataType="string" Value="key" />
<InputParameter Id="jsonSourceValueName" DataType="string" Value="value" />
</InputParameters>
<OutputClaims>
<OutputClaim ClaimTypeReferenceId="email" />
<OutputClaim ClaimTypeReferenceId="displayName" />
<OutputClaim ClaimTypeReferenceId="membershipNum" />
<OutputClaim ClaimTypeReferenceId="active" />
<OutputClaim ClaimTypeReferenceId="birthdate" />
</OutputClaims>
</ClaimsTransformation>
Input claims:
jsonSourceClaim: [{"key":"email","value":"someone@example.com"},
{"key":"displayName","value":"Someone"}, {"key":"membershipNum","value":6353399},
{"key":"active","value": true}, {"key":"birthdate","value":"1980-09-23T00:00:00Z"}]
Input parameters:
errorOnMissingClaims: false
includeEmptyClaims: false
jsonSourceKeyName: key
jsonSourceValueName: value
Output claims:
email: "someone@example.com"
displayName: "Someone"
membershipNum: 6353399
active: true
birthdate: 1980-09-23T00:00:00Z
GetNumericClaimFromJson
Gets a specified numeric (long) element from a JSON data.
{
"emailAddress": "someone@example.com",
"displayName": "Someone",
"id" : 6353399
}
Example
Input claims:
inputJson: {"emailAddress": "someone@example.com", "displayName": "Someone", "id" : 6353399}
Input parameters
claimToExtract: id
Output claims:
extractedClaim: 6353399
GetSingleValueFromJsonArray
Gets the first element from a JSON data array.
In the following example, the claims transformation extracts the first element (email address) from the JSON array
["someone@example.com", "Someone", 6353399] .
XmlStringToJsonString
Converts XML data to JSON format.
In the following example, the claims transformation converts the following XML data to JSON format.
Example
Input claim:
<user>
<name>Someone</name>
<email>someone@example.com</email>
</user>
Output claim:
{
"user": {
"name":"Someone",
"email":"someone@example.com"
}
}
Social accounts claims transformations
12/9/2019 • 4 minutes to read • Edit Online
NOTE
In Azure Active Directory B2C, custom policies are designed primarily to address complex scenarios. For most scenarios, we
recommend that you use built-in user flows.
In Azure Active Directory B2C (Azure AD B2C ), social account identities are stored in a userIdentities attribute of
a alternativeSecurityIdCollection claim type. Each item in the alternativeSecurityIdCollection specifies the
issuer (identity provider name, such as facebook.com) and the issuerUserId , which is a unique user identifier for
the issuer.
"userIdentities": [{
"issuer": "google.com",
"issuerUserId": "MTA4MTQ2MDgyOTI3MDUyNTYzMjcw"
},
{
"issuer": "facebook.com",
"issuerUserId": "MTIzNDU="
}]
This article provides examples for using the social account claims transformations of the Identity Experience
Framework schema in Azure AD B2C. For more information, see ClaimsTransformations.
CreateAlternativeSecurityId
Creates a JSON representation of the user’s alternativeSecurityId property that can be used in the calls to Azure
Active Directory. For more information, see AlternativeSecurityId's schema.
Use this claims transformation to generate a alternativeSecurityId ClaimType. It's used by all social identity
provider technical profiles, such as Facebook-OAUTH . The following claims transformation receives the user social
account ID and the identity provider name. The output of this technical profile is a JSON string format that can be
used in Azure AD directory services.
Example
Input claims:
key: 12334
identityProvider: Facebook.com
Output claims:
alternativeSecurityId: { "issuer": "facebook.com", "issuerUserId":
"MTA4MTQ2MDgyOTI3MDUyNTYzMjcw"}
AddItemToAlternativeSecurityIdCollection
Adds an AlternativeSecurityId to an alternativeSecurityIdCollection claim.
The following example links a new social identity with an existing account. To link a new social identity:
1. In the AAD -UserReadUsingAlternativeSecurityId and AAD -UserReadUsingObjectId technical profiles,
output the user's alternativeSecurityIds claim.
2. Ask the user to sign in with one of the identity providers that are not associated with this user.
3. Using the CreateAlternativeSecurityId claims transformation, create a new alternativeSecurityId claim
type with a name of AlternativeSecurityId2
4. Call the AddItemToAlternativeSecurityIdCollection claims transformation to add the
AlternativeSecurityId2 claim to the existing AlternativeSecurityIds claim.
5. Persist the alternativeSecurityIds claim to the user account
<ClaimsTransformation Id="AddAnotherAlternativeSecurityId"
TransformationMethod="AddItemToAlternativeSecurityIdCollection">
<InputClaims>
<InputClaim ClaimTypeReferenceId="AlternativeSecurityId2" TransformationClaimType="item" />
<InputClaim ClaimTypeReferenceId="AlternativeSecurityIds" TransformationClaimType="collection" />
</InputClaims>
<OutputClaims>
<OutputClaim ClaimTypeReferenceId="AlternativeSecurityIds" TransformationClaimType="collection" />
</OutputClaims>
</ClaimsTransformation>
Example
Input claims:
item: { "issuer": "facebook.com", "issuerUserId": "MTIzNDU=" }
collection: [ { "issuer": "live.com", "issuerUserId": "MTA4MTQ2MDgyOTI3MDUyNTYzMjcw" } ]
Output claims:
collection: [ { "issuer": "live.com", "issuerUserId": "MTA4MTQ2MDgyOTI3MDUyNTYzMjcw" }, {
"issuer": "facebook.com", "issuerUserId": "MTIzNDU=" } ]
GetIdentityProvidersFromAlternativeSecurityIdCollectionTransformatio
n
Returns list of issuers from the alternativeSecurityIdCollection claim into a new stringCollection claim.
The following claims transformation reads the user alternativeSecurityIds claim and extracts the list of identity
provider names associated with that account. Use output identityProvidersCollection to show the user the list of
identity providers associated with the account. Or, on the identity provider selection page, filter the list of identity
providers based on output identityProvidersCollection claim. So, user can select to link new social identity that
is not already associated with the account.
<ClaimsTransformation Id="ExtractIdentityProviders"
TransformationMethod="GetIdentityProvidersFromAlternativeSecurityIdCollectionTransformation">
<InputClaims>
<InputClaim ClaimTypeReferenceId="alternativeSecurityIds"
TransformationClaimType="alternativeSecurityIdCollection" />
</InputClaims>
<OutputClaims>
<OutputClaim ClaimTypeReferenceId="identityProviders"
TransformationClaimType="identityProvidersCollection" />
</OutputClaims>
</ClaimsTransformation>
Input claims:
alternativeSecurityIdCollection: [ { "issuer": "google.com", "issuerUserId":
"MTA4MTQ2MDgyOTI3MDUyNTYzMjcw" }, { "issuer": "facebook.com", "issuerUserId": "MTIzNDU=" } ]
Output claims:
identityProvidersCollection: [ "facebook.com", "google.com" ]
RemoveAlternativeSecurityIdByIdentityProvider
Removes an AlternativeSecurityId from an alternativeSecurityIdCollection claim.
The following example unlinks one of the social identity with an existing account. To unlink a social identity:
1. In the AAD -UserReadUsingAlternativeSecurityId and AAD -UserReadUsingObjectId technical profiles,
output the user's alternativeSecurityIds claim.
2. Ask the user to select which social account to remove from the list identity providers that are associated with
this user.
3. Call a claims transformation technical profile that calls the
RemoveAlternativeSecurityIdByIdentityProvider claims transformation, that removed the selected social
identity, using identity provider name.
4. Persist the alternativeSecurityIds claim to the user account.
<ClaimsTransformation Id="RemoveAlternativeSecurityIdByIdentityProvider"
TransformationMethod="RemoveAlternativeSecurityIdByIdentityProvider">
<InputClaims>
<InputClaim ClaimTypeReferenceId="secondIdentityProvider" TransformationClaimType="identityProvider"
/>
<InputClaim ClaimTypeReferenceId="AlternativeSecurityIds" TransformationClaimType="collection" />
</InputClaims>
<OutputClaims>
<OutputClaim ClaimTypeReferenceId="AlternativeSecurityIds" TransformationClaimType="collection" />
</OutputClaims>
</ClaimsTransformation>
</ClaimsTransformations>
Example
Input claims:
identityProvider: facebook.com
collection: [ { "issuer": "live.com", "issuerUserId": "MTA4MTQ2MDgyOTI3MDUyNTYzMjcw" }, {
"issuer": "facebook.com", "issuerUserId": "MTIzNDU=" } ]
Output claims:
collection: [ { "issuer": "live.com", "issuerUserId": "MTA4MTQ2MDgyOTI3MDUyNTYzMjcw" } ]
StringCollection claims transformations
12/9/2019 • 2 minutes to read • Edit Online
NOTE
In Azure Active Directory B2C, custom policies are designed primarily to address complex scenarios. For most scenarios, we
recommend that you use built-in user flows.
This article provides examples for using the string collection claims transformations of the Identity Experience
Framework schema in Azure Active Directory B2C (Azure AD B2C ). For more information, see
ClaimsTransformations.
AddItemToStringCollection
Adds a string claim to a new stringCollection claim.
Use this claims transformation to add a string to a new or existing stringCollection. It's commonly used in a AAD -
UserWriteUsingAlternativeSecurityId technical profile. Before a new social account is created,
CreateOtherMailsFromEmail claims transformation reads the ClaimType and adds the value to the otherMails
ClaimType.
The following claims transformation adds the email ClaimType to otherMails ClaimType.
Example
Input claims:
collection: ["someone@outlook.com"]
item: "admin@contoso.com"
Output claims:
collection: ["someone@outlook.com", "admin@contoso.com"]
AddParameterToStringCollection
Adds a string parameter to a new stringCollection claim.
Use this claims transformation to add a string value to a new or existing stringCollection. The following example
adds a constant email address (admin@contoso.com) to the otherMails claim.
Example
Input claims:
collection: ["someone@outlook.com"]
Input parameters
item: "admin@contoso.com"
Output claims:
collection: ["someone@outlook.com", "admin@contoso.com"]
GetSingleItemFromStringCollection
Gets the first item from the provided string collection.
ITEM TRANSFORMATIONCLAIMTYPE DATA TYPE NOTES
The following example reads the otherMails claim and return the first item into the email claim.
Example
Input claims:
collection: ["someone@outlook.com", "someone@contoso.com"]
Output claims:
extractedItem: "someone@outlook.com"
String claims transformations
12/9/2019 • 12 minutes to read • Edit Online
NOTE
In Azure Active Directory B2C, custom policies are designed primarily to address complex scenarios. For most scenarios, we
recommend that you use built-in user flows.
This article provides examples for using the string claims transformations of the Identity Experience Framework
schema in Azure Active Directory B2C (Azure AD B2C ). For more information, see ClaimsTransformations.
AssertStringClaimsAreEqual
Compare two claims, and throw an exception if they are not equal according to the specified comparison
inputClaim1, inputClaim2 and stringComparison.
The AssertStringClaimsAreEqual claims transformation is always executed from a validation technical profile
that is called by a self-asserted technical profile. The
UserMessageIfClaimsTransformationStringsAreNotEqual self-asserted technical profile metadata controls
the error message that is presented to the user.
You can use this claims transformation to make sure, two ClaimTypes have the same value. If not, an error
message is thrown. The following example checks that the strongAuthenticationEmailAddress ClaimType is
equal to email ClaimType. Otherwise an error message is thrown.
<ClaimsTransformation Id="AssertEmailAndStrongAuthenticationEmailAddressAreEqual"
TransformationMethod="AssertStringClaimsAreEqual">
<InputClaims>
<InputClaim ClaimTypeReferenceId="strongAuthenticationEmailAddress" TransformationClaimType="inputClaim1"
/>
<InputClaim ClaimTypeReferenceId="email" TransformationClaimType="inputClaim2" />
</InputClaims>
<InputParameters>
<InputParameter Id="stringComparison" DataType="string" Value="ordinalIgnoreCase" />
</InputParameters>
</ClaimsTransformation>
<TechnicalProfile Id="login-NonInteractive">
...
<OutputClaimsTransformations>
<OutputClaimsTransformation ReferenceId="AssertEmailAndStrongAuthenticationEmailAddressAreEqual" />
</OutputClaimsTransformations>
</TechnicalProfile>
The self-asserted technical profile calls the validation login-NonInteractive technical profile.
<TechnicalProfile Id="SelfAsserted-LocalAccountSignin-Email">
<Metadata>
<Item Key="UserMessageIfClaimsTransformationStringsAreNotEqual">Custom error message the email addresses
you provided are not the same.</Item>
</Metadata>
<ValidationTechnicalProfiles>
<ValidationTechnicalProfile ReferenceId="login-NonInteractive" />
</ValidationTechnicalProfiles>
</TechnicalProfile>
Example
Input claims:
inputClaim1: someone@contoso.com
inputClaim2: someone@outlook.com
Input parameters:
stringComparison: ordinalIgnoreCase
Result: Error thrown
ChangeCase
Changes the case of the provided claim to lower or upper case depending on the operator.
Use this claim transformation to change any string ClaimType to lower or upper case.
Example
Input claims:
email: SomeOne@contoso.com
Input parameters:
toCase: LOWER
Output claims:
email: someone@contoso.com
CreateStringClaim
Creates a string claim from the provided input parameter in the policy.
Example
Input parameter:
value: Contoso terms of service...
Output claims:
createdClaim: The TOS ClaimType contains the "Contoso terms of service..." value.
CompareClaims
Determine whether one string claim is equal to another. The result is a new boolean ClaimType with a value of
true or false .
Use this claims transformation to check if a claim is equal to another claim. For example, the following claims
transformation checks if the value of the email claim is equal to the Verified.Email claim.
Example
Input claims:
inputClaim1: someone@contoso.com
inputClaim2: someone@outlook.com
Input parameters:
operator: NOT EQUAL
ignoreCase: true
Output claims:
outputClaim: true
CompareClaimToValue
Determines whether a claim value is equal to the input parameter value.
You can use this claims transformation to check if a claim is equal to a value you specified. For example, the
following claims transformation checks if the value of the termsOfUseConsentVersion claim is equal to v1 .
Example
Input claims:
inputClaim1: v1
Input parameters:
compareTo: V1
operator: EQUAL
ignoreCase: true
Output claims:
outputClaim: true
CreateRandomString
Creates a random string using the random number generator. If the random number generator is of type integer ,
optionally a seed parameter and a maximum number may be provided. An optional string format parameter
allows the output to be formatted using it, and an optional base64 parameter specifies whether the output is
base64 encoded randomGeneratorType [guid, integer] outputClaim (String).
Following example generates a global unique ID. This claims transformation is used to create the random UPN
(user principle name).
Example
Input parameters:
randomGeneratorType: GUID
Output claims:
outputClaim: bc8bedd2-aaa3-411e-bdee-2f1810b73dfc
Following example generates an integer random value between 0 and 1000. The value is formatted to
OTP_{random value}.
FormatStringClaim
Format a claim according to the provided format string. This transformation uses the C# String.Format method.
Use this claims transformation to format any string with one parameter {0}. The following example creates a
userPrincipalName. All social identity provider technical profiles, such as Facebook-OAUTH calls the
CreateUserPrincipalName to generate a userPrincipalName.
Example
Input claims:
inputClaim: 5164db16-3eee-4629-bfda-dcc3326790e9
Input parameters:
stringFormat: cpim_{0}@{RelyingPartyTenantId}
Output claims:
outputClaim: cpim_5164db16-3eee-4629-bfda-dcc3326790e9@b2cdemo.onmicrosoft.com
FormatStringMultipleClaims
Format two claims according to the provided format string. This transformation uses the C# String.Format
method.
ITEM TRANSFORMATIONCLAIMTYPE DATA TYPE NOTES
Use this claims transformation to format any string with two parameters, {0} and {1}. The following example
creates a displayName with the specified format:
<ClaimsTransformation Id="CreateDisplayNameFromFirstNameAndLastName"
TransformationMethod="FormatStringMultipleClaims">
<InputClaims>
<InputClaim ClaimTypeReferenceId="givenName" TransformationClaimType="inputClaim1" />
<InputClaim ClaimTypeReferenceId="surName" TransformationClaimType="inputClaim2" />
</InputClaims>
<InputParameters>
<InputParameter Id="stringFormat" DataType="string" Value="{0} {1}" />
</InputParameters>
<OutputClaims>
<OutputClaim ClaimTypeReferenceId="displayName" TransformationClaimType="outputClaim" />
</OutputClaims>
</ClaimsTransformation>
Example
Input claims:
inputClaim1: Joe
inputClaim2: Fernando
Input parameters:
stringFormat: {0} {1}
Output claims:
outputClaim: Joe Fernando
GetMappedValueFromLocalizedCollection
Looking up an item from a claim Restriction collection.
The following example looks up the error message description based on the error key. The responseMsg claim
contains a collection of error messages to present to the end user or to be sent to the relying party.
<ClaimType Id="responseMsg">
<DisplayName>Error message: </DisplayName>
<DataType>string</DataType>
<UserInputType>Paragraph</UserInputType>
<Restriction>
<Enumeration Text="B2C_V1_90001" Value="You cant sign in because you are a minor" />
<Enumeration Text="B2C_V1_90002" Value="This action can only be performed by gold members" />
<Enumeration Text="B2C_V1_90003" Value="You have not been enabled for this operation" />
</Restriction>
</ClaimType>
The claims transformation looks up the text of the item and returns its value. If the restriction is localized using
<LocalizedCollection> , the claims transformation returns the localized value.
<ClaimsTransformation Id="GetResponseMsgMappedToResponseCode"
TransformationMethod="GetMappedValueFromLocalizedCollection">
<InputClaims>
<InputClaim ClaimTypeReferenceId="responseCode" TransformationClaimType="mapFromClaim" />
</InputClaims>
<OutputClaims>
<OutputClaim ClaimTypeReferenceId="responseMsg" TransformationClaimType="restrictionValueClaim" />
</OutputClaims>
</ClaimsTransformation>
Example
Input claims:
mapFromClaim: B2C_V1_90001
Output claims:
restrictionValueClaim: You cant sign in because you are a minor.
LookupValue
Look up a claim value from a list of values based on the value of another claim.
The following example looks up the domain name in one of the inputParameters collections. The claims
transformation looks up the domain name in the identifier and returns its value (an application ID ).
Example
Input claims:
inputParameterId: test.com
Input parameters:
contoso.com: 13c15f79-8fb1-4e29-a6c9-be0d36ff19f1
microsoft.com: 0213308f-17cb-4398-b97e-01da7bd4804e
test.com: c7026f88-4299-4cdb-965d-3f166464b8a9
errorOnFailedLookup: false
Output claims:
outputClaim: c7026f88-4299-4cdb-965d-3f166464b8a9
NullClaim
Clean the value of a given claim.
Use this claim transformation to remove unnecessary data from the claims property bag. So, the session cookie
will be smaller. The following example removes the value of the TermsOfService claim type.
<ClaimsTransformation Id="SetTOSToNull" TransformationMethod="NullClaim">
<OutputClaims>
<OutputClaim ClaimTypeReferenceId="TermsOfService" TransformationClaimType="claim_to_null" />
</OutputClaims>
</ClaimsTransformation>
Input claims:
outputClaim: Welcome to Contoso App. If you continue to browse and use this website, you are
agreeing to comply with and be bound by the following terms and conditions...
Output claims:
outputClaim: NULL
ParseDomain
Gets the domain portion of an email address.
Use this claims transformation to parse the domain name after the @ symbol of the user. This can be helpful in
removing Personally identifiable information (PII) from audit data. The following claims transformation
demonstrates how to parse the domain name from an email claim.
Example
Input claims:
emailAddress: joe@outlook.com
Output claims:
domain: outlook.com
SetClaimsIfStringsAreEqual
Checks that a string claim and matchTo input parameter are equal, and sets the output claims with the value
present in stringMatchMsg and stringMatchMsgCode input parameters, along with compare result output claim,
which is to be set as true or false based on the result of comparison.
ITEM TRANSFORMATIONCLAIMTYPE DATA TYPE NOTES
You can use this claims transformation to check if a claim is equal to value you specified. For example, the
following claims transformation checks if the value of the termsOfUseConsentVersion claim is equal to v1 . If
yes, change the value to v2 .
Example
Input claims:
inputClaim: v1
Input parameters:
matchTo: V1
stringComparison: ordinalIgnoreCase
stringMatchMsg: B2C_V1_90005
stringMatchMsgCode: The TOS is upgraded to v2
Output claims:
outputClaim1: B2C_V1_90005
outputClaim2: The TOS is upgraded to v2
stringCompareResultClaim: true
SetClaimsIfStringsMatch
Checks that a string claim and matchTo input parameter are equal, and sets the output claims with the value
present in outputClaimIfMatched input parameter, along with compare result output claim, which is to be set as
true or false based on the result of comparison.
For example, the following claims transformation checks if the value of ageGroup claim is equal to Minor . If yes,
return the value to B2C_V1_90001 .
<ClaimsTransformation Id="SetIsMinor" TransformationMethod="SetClaimsIfStringsMatch">
<InputClaims>
<InputClaim ClaimTypeReferenceId="ageGroup" TransformationClaimType="claimToMatch" />
</InputClaims>
<InputParameters>
<InputParameter Id="matchTo" DataType="string" Value="Minor" />
<InputParameter Id="stringComparison" DataType="string" Value="ordinalIgnoreCase" />
<InputParameter Id="outputClaimIfMatched" DataType="string" Value="B2C_V1_90001" />
</InputParameters>
<OutputClaims>
<OutputClaim ClaimTypeReferenceId="isMinor" TransformationClaimType="outputClaim" />
<OutputClaim ClaimTypeReferenceId="isMinorResponseCode" TransformationClaimType="stringCompareResultClaim"
/>
</OutputClaims>
</ClaimsTransformation>
Example
Input claims:
claimToMatch: Minor
Input parameters:
matchTo: Minor
stringComparison: ordinalIgnoreCase
outputClaimIfMatched: B2C_V1_90001
Output claims:
isMinorResponseCode: B2C_V1_90001
isMinor: true
Predicates and PredicateValidations
12/9/2019 • 7 minutes to read • Edit Online
NOTE
In Azure Active Directory B2C, custom policies are designed primarily to address complex scenarios. For most scenarios, we
recommend that you use built-in user flows.
The Predicates and PredicateValidations elements enable you to perform a validation process to ensure that
only properly formed data is entered into your Azure Active Directory B2C (Azure AD B2C ) tenant.
The following diagram shows the relationship between the elements:
Predicates
The Predicate element defines a basic validation to check the value of a claim type and returns true or false .
The validation is done by using a specified Method element and a set of Parameter elements relevant to the
method. For example, a predicate can check whether the length of a string claim value is within the range of
minimum and maximum parameters specified, or whether a string claim value contains a character set. The
UserHelpText element provides an error message for users if the check fails. The value of UserHelpText
element can be localized using language customization.
The Predicates element must appear directly following the ClaimsSchema element within the BuildingBlocks
element.
The Predicates element contains the following element:
The following example shows a IsLengthRange method with the parameters Minimum and Maximum that specify
the length range of the string:
The following example shows a IncludesCharacters method with the parameter CharacterSet that specifies the
set of characters:
The following example shows a IsDateRange method with the parameters Minimum and Maximum that specify the
date range with a format of yyyy-MM-dd and Today .
<Predicate Id="DateRange" Method="IsDateRange" HelpText="The date must be between 1970-01-01 and today.">
<Parameters>
<Parameter Id="Minimum">1970-01-01</Parameter>
<Parameter Id="Maximum">Today</Parameter>
</Parameters>
</Predicate>
PredicateValidations
While the predicates define the validation to check against a claim type, the PredicateValidations group a set of
predicates to form a user input validation that can be applied to a claim type. Each PredicateValidation element
contains a set of PredicateGroup elements that contain a set of PredicateReference elements that points to a
Predicate. To pass the validation, the value of the claim should pass all of the tests of any predicate under all of
the PredicateGroup with their set of PredicateReference elements.
The PredicateValidations element must appear directly following the Predicates element within the
BuildingBlocks element.
<PredicateValidations>
<PredicateValidation Id="">
<PredicateGroups>
<PredicateGroup Id="">
<UserHelpText></UserHelpText>
<PredicateReferences MatchAtLeast="">
<PredicateReference Id="" />
...
</PredicateReferences>
</PredicateGroup>
...
</PredicateGroups>
</PredicateValidation>
...
</PredicateValidations>
The PredicateValidations element contains the following element:
After you define the basic validations, you can combine them together and create a set of password policies that
you can use in your policy:
SimplePassword validates the DisallowedWhitespace, AllowedAADCharacters, and IsLengthBetween8And64
StrongPassword validates the DisallowedWhitespace, AllowedAADCharacters, IsLengthBetween8And64. The
last group CharacterClasses runs an additional set of predicates with MatchAtLeast set to 3. The user
password must be between 8 and 16 characters, and three of the following characters: Lowercase, Uppercase,
Number, or Symbol.
CustomPassword validates only DisallowedWhitespace, AllowedAADCharacters. So, user can provide any
password with any length, as long as the characters are valid.
<PredicateValidations>
<PredicateValidation Id="SimplePassword">
<PredicateGroups>
<PredicateGroup Id="DisallowedWhitespaceGroup">
<PredicateReferences>
<PredicateReference Id="DisallowedWhitespace" />
</PredicateReferences>
</PredicateGroup>
<PredicateGroup Id="AllowedAADCharactersGroup">
<PredicateReferences>
<PredicateReference Id="AllowedAADCharacters" />
</PredicateReferences>
</PredicateGroup>
<PredicateGroup Id="LengthGroup">
<PredicateReferences>
<PredicateReference Id="IsLengthBetween8And64" />
</PredicateReferences>
</PredicateGroup>
</PredicateGroups>
</PredicateValidation>
<PredicateValidation Id="StrongPassword">
<PredicateGroups>
<PredicateGroup Id="DisallowedWhitespaceGroup">
<PredicateReferences>
<PredicateReference Id="DisallowedWhitespace" />
</PredicateReferences>
</PredicateGroup>
<PredicateGroup Id="AllowedAADCharactersGroup">
<PredicateReferences>
<PredicateReference Id="AllowedAADCharacters" />
</PredicateReferences>
</PredicateGroup>
<PredicateGroup Id="LengthGroup">
<PredicateReferences>
<PredicateReference Id="IsLengthBetween8And64" />
</PredicateReferences>
</PredicateGroup>
<PredicateGroup Id="CharacterClasses">
<UserHelpText>The password must have at least 3 of the following:</UserHelpText>
<PredicateReferences MatchAtLeast="3">
<PredicateReference Id="Lowercase" />
<PredicateReference Id="Uppercase" />
<PredicateReference Id="Number" />
<PredicateReference Id="Symbol" />
</PredicateReferences>
</PredicateGroup>
</PredicateGroups>
</PredicateValidation>
<PredicateValidation Id="CustomPassword">
<PredicateGroups>
<PredicateGroup Id="DisallowedWhitespaceGroup">
<PredicateReferences>
<PredicateReference Id="DisallowedWhitespace" />
</PredicateReferences>
</PredicateGroup>
<PredicateGroup Id="AllowedAADCharactersGroup">
<PredicateReferences>
<PredicateReference Id="AllowedAADCharacters" />
</PredicateReferences>
</PredicateGroup>
</PredicateGroups>
</PredicateValidation>
</PredicateValidations>
In your claim type, add the PredicateValidationReference element and specify the identifier as one of the
predicate validations, such as SimplePassword, StrongPassword, or CustomPassword.
<ClaimType Id="password">
<DisplayName>Password</DisplayName>
<DataType>string</DataType>
<AdminHelpText>Enter password</AdminHelpText>
<UserHelpText>Enter password</UserHelpText>
<UserInputType>Password</UserInputType>
<PredicateValidationReference Id="StrongPassword" />
</ClaimType>
The following shows how the elements are organized when Azure AD B2C displays the error message:
<Predicates>
<Predicate Id="DateRange" Method="IsDateRange">
<UserHelpText>The date must be between 01-01-1980 and today.</UserHelpText>
<Parameters>
<Parameter Id="Minimum">1980-01-01</Parameter>
<Parameter Id="Maximum">Today</Parameter>
</Parameters>
</Predicate>
</Predicates>
In your claim type, add PredicateValidationReference element and specify the identifier as CustomDateRange .
<ClaimType Id="dateOfBirth">
<DisplayName>Date of Birth</DisplayName>
<DataType>date</DataType>
<AdminHelpText>The user's date of birth.</AdminHelpText>
<UserHelpText>Your date of birth.</UserHelpText>
<UserInputType>DateTimeDropdown</UserInputType>
<PredicateValidationReference Id="CustomDateRange" />
</ClaimType>
ContentDefinitions
9/17/2019 • 5 minutes to read • Edit Online
NOTE
In Azure Active Directory B2C, custom policies are designed primarily to address complex scenarios. For most scenarios, we
recommend that you use built-in user flows.
You can customize the look and feel of any self-asserted technical profile. Azure Active Directory B2C (Azure AD
B2C ) runs code in your customer's browser and uses a modern approach called Cross-Origin Resource Sharing
(CORS ).
To customize the user interface, you specify a URL in the ContentDefinition element with customized HTML
content. In the self-asserted technical profile or OrchestrationStep, you point to that content definition identifier.
The content definition may contain a LocalizedResourcesReferences element that specifies a list of localized
resources to load. Azure AD B2C merges user interface elements with the HTML content that's loaded from your
URL and then displays the page to the user.
The ContentDefinitions element contains URLs to HTML5 templates that can be used in a user journey. The
HTML5 page URI is used for a specified user interface step. For example, the sign-in or sign-up, password reset,
or error pages. You can modify the look and feel by overriding the LoadUri for the HTML5 file. You can create new
content definitions according to your needs. This element may contain a localized resources reference, to the
localization identifier specified in the Localization element.
The following example shows the content definition identifier and the definition of localized resources:
<ContentDefinition Id="api.localaccountsignup">
<LoadUri>~/tenant/default/selfAsserted.cshtml</LoadUri>
<RecoveryUri>~/common/default_page_error.html</RecoveryUri>
<DataUri>urn:com:microsoft:aad:b2c:elements:selfasserted:1.1.0</DataUri>
<Metadata>
<Item Key="DisplayName">Local account sign up page</Item>
</Metadata>
<LoalizedResourcesReferences MergeBehavior="Prepend">
<LocalizedResourcesReference Language="en" LocalizedResourcesReferenceId="api.localaccountsignup.en" />
<LocalizedResourcesReference Language="es" LocalizedResourcesReferenceId="api.localaccountsignup.es" />
...
The metadata of the LocalAccountSignUpWithLogonEmail self-asserted technical profile contains the content
definition identifier ContentDefinitionReferenceId set to api.localaccountsignup
<TechnicalProfile Id="LocalAccountSignUpWithLogonEmail">
<DisplayName>Email signup</DisplayName>
<Protocol Name="Proprietary" Handler="Web.TPEngine.Providers.SelfAssertedAttributeProvider, Web.TPEngine,
Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
<Metadata>
<Item Key="ContentDefinitionReferenceId">api.localaccountsignup</Item>
...
</Metadata>
...
ContentDefinition
The ContentDefinition element contains the following attribute:
DataUri
The DataUri element is used to specify the page identifier. Azure AD B2C uses the page identifier to load and
initiate UI elements and client side JavaScript. The format of the value is
urn:com:microsoft:aad:b2c:elements:page-name:version . The following table lists of the page identifiers you can
use.
VALUE DESCRIPTION
urn:com:microsoft:aad:b2c:elements:idpselection:1.0.0 Lists the identity providers that users can choose from during
sign-in.
urn:com:microsoft:aad:b2c:elements:unifiedssp:1.0.0 Displays a form for signing in with a local account that's based
on an email address or a user name. This value also provides
the “keep me sign-in functionality” and “Forgot your
password?” link.
urn:com:microsoft:aad:b2c:elements:unifiedssd:1.0.0 Displays a form for signing in with a local account that's based
on an email address or a user name.
VALUE DESCRIPTION
LocalizedResourcesReferences
The LocalizedResourcesReferences element contains the following elements:
<ContentDefinition Id="api.signuporsignin">
<LoadUri>~/tenant/default/unified.cshtml</LoadUri>
<RecoveryUri>~/common/default_page_error.html</RecoveryUri>
<DataUri>urn:com:microsoft:aad:b2c:elements:unifiedssp:1.0.0</DataUri>
<Metadata>
<Item Key="DisplayName">Signin and Signup</Item>
</Metadata>
</ContentDefinition>
The following example shows a sign-up or sign-in content definition with a reference to localization for English,
French and Spanish:
<ContentDefinition Id="api.signuporsignin">
<LoadUri>~/tenant/default/unified.cshtml</LoadUri>
<RecoveryUri>~/common/default_page_error.html</RecoveryUri>
<DataUri>urn:com:microsoft:aad:b2c:elements:unifiedssp:1.0.0</DataUri>
<Metadata>
<Item Key="DisplayName">Signin and Signup</Item>
</Metadata>
<LocalizedResourcesReferences MergeBehavior="Prepend">
<LocalizedResourcesReference Language="en" LocalizedResourcesReferenceId="api.signuporsignin.en" />
<LocalizedResourcesReference Language="fr" LocalizedResourcesReferenceId="api.signuporsignin.rf" />
<LocalizedResourcesReference Language="es" LocalizedResourcesReferenceId="api.signuporsignin.es" />
</LocalizedResourcesReferences>
</ContentDefinition>
To learn how to add localization support to your content definitions, see Localization.
Content definition IDs
The ID attribute of the ContentDefinition element specifies the type of page that relates to the content
definition. The element defines the context that a custom HTML5/CSS template is going to apply. The following
table describes the set of content definition IDs that is recognized by the Identity Experience Framework, and the
page types that relate to them. You can create your own content definitions with an arbitrary ID.
NOTE
In Azure Active Directory B2C, custom policies are designed primarily to address complex scenarios. For most scenarios, we
recommend that you use built-in user flows.
The Localization element allows you to support multiple locales or languages in the policy for the user
journeys. The localization support in policies allows you to:
Set up the explicit list of the supported languages in a policy and pick a default language.
Provide language-specific strings and collections.
<Localization Enabled="true">
<SupportedLanguages DefaultLanguage="en" MergeBehavior="ReplaceAll">
<SupportedLanguage>en</SupportedLanguage>
<SupportedLanguage>es</SupportedLanguage>
</SupportedLanguages>
<LocalizedResources Id="api.localaccountsignup.en">
<LocalizedResources Id="api.localaccountsignup.es">
...
SupportedLanguages
The SupportedLanguages element contains the following attributes:
SupportedLanguages
The SupportedLanguages element contains the following elements:
LocalizedResources
The LocalizedResources element contains the following attributes:
LocalizedCollection
The LocalizedCollection element contains the following attributes:
The following example shows the use of the LocalizedCollections element. It contains two
LocalizedCollection elements, one for English and another one for Spanish. Both set the Restriction collection
of the claim Gender with a list of items for English and Spanish.
<LocalizedResources Id="api.selfasserted.en">
<LocalizedCollections>
<LocalizedCollection ElementType="ClaimType" ElementId="Gender" TargetCollection="Restriction">
<Item Text="Female" Value="F" />
<Item Text="Male" Value="M" />
</LocalizedCollection>
</LocalizedCollections>
<LocalizedResources Id="api.selfasserted.es">
<LocalizedCollections>
<LocalizedCollection ElementType="ClaimType" ElementId="Gender" TargetCollection="Restriction">
<Item Text="Femenino" Value="F" />
<Item Text="Masculino" Value="M" />
</LocalizedCollection>
</LocalizedCollections>
LocalizedStrings
The LocalizedStrings element contains the following elements:
The following example shows a localized sign-up page. The first three LocalizedString values set the claim
attribute. The third changes the value of the continue button. The last one changes the error message.
<LocalizedResources Id="api.selfasserted.en">
<LocalizedStrings>
<LocalizedString ElementType="ClaimType" ElementId="email"
StringId="DisplayName">Email</LocalizedString>
<LocalizedString ElementType="ClaimType" ElementId="email" StringId="UserHelpText">Please enter your
email</LocalizedString>
<LocalizedString ElementType="ClaimType" ElementId="email" StringId="PatternHelpText">Please enter a
valid email address</LocalizedString>
<LocalizedString ElementType="UxElement" StringId="button_continue">Create new account</LocalizedString>
<LocalizedString ElementType="ErrorMessage" StringId="UserMessageIfClaimsPrincipalAlreadyExists">The
account you are trying to create already exists, please sign-in.</LocalizedString>
</LocalizedStrings>
</LocalizedResources>
The following example shows a localized the UserHelpText of Predicate with Id IsLengthBetween8And64 . And a
localized UserHelpText of PredicateGroup with Id CharacterClasses of PredicateValidation with Id
StrongPassword .
<PredicateValidation Id="StrongPassword">
<PredicateGroups>
...
<PredicateGroup Id="CharacterClasses">
...
</PredicateGroup>
</PredicateGroups>
</PredicateValidation>
...
Set up localization
This article shows you how to support multiple locales or languages in the policy for user journeys. Localization
requires three steps: set-up the explicit list of the supported languages, provide language-specific strings and
collections, and edit the ContentDefinition for the page.
Set up the explicit list of supported languages
Under the BuildingBlocks element, add the Localization element with the list of supported languages. The
following example shows how to define the localization support for both English (default) and Spanish:
<Localization Enabled="true">
<SupportedLanguages DefaultLanguage="en" MergeBehavior="ReplaceAll">
<SupportedLanguage>en</SupportedLanguage>
<SupportedLanguage>es</SupportedLanguage>
</SupportedLanguages>
</Localization>
<LocalizedResources Id="api.localaccountsignup.en">
<LocalizedCollections>
<LocalizedCollection ElementType="ClaimType" ElementId="Gender" TargetCollection="Restriction">
<Item Text="Female" Value="F" />
<Item Text="Male" Value="M" />
</LocalizedCollection>
<LocalizedCollection ElementType="ClaimType" ElementId="City" TargetCollection="Restriction">
<Item Text="New York" Value="NY" />
<Item Text="Paris" Value="Paris" />
<Item Text="London" Value="London" />
</LocalizedCollection>
</LocalizedCollections>
<LocalizedStrings>
<LocalizedString ElementType="ClaimType" ElementId="email"
StringId="DisplayName">Email</LocalizedString>
<LocalizedString ElementType="ClaimType" ElementId="email" StringId="UserHelpText">Please enter your
email</LocalizedString>
<LocalizedString ElementType="ClaimType" ElementId="email" StringId="PatternHelpText">Please enter a
valid email address</LocalizedString>
<LocalizedString ElementType="UxElement" StringId="button_continue">Create new account</LocalizedString>
<LocalizedString ElementType="ErrorMessage" StringId="UserMessageIfClaimsPrincipalAlreadyExists">The
account you are trying to create already exists, please sign-in.</LocalizedString>
</LocalizedStrings>
</LocalizedResources>
<LocalizedResources Id="api.localaccountsignup.es">
<LocalizedCollections>
<LocalizedCollection ElementType="ClaimType" ElementId="Gender" TargetCollection="Restriction">
<Item Text="Femenino" Value="F" />
<Item Text="Masculino" Value="M" />
</LocalizedCollection>
<LocalizedCollection ElementType="ClaimType" ElementId="City" TargetCollection="Restriction">
<Item Text="Nueva York" Value="NY" />
<Item Text="París" Value="Paris" />
<Item Text="Londres" Value="London" />
</LocalizedCollection>
</LocalizedCollections>
<LocalizedStrings>
<LocalizedString ElementType="ClaimType" ElementId="email" StringId="DisplayName">Dirección de correo
electrónico</LocalizedString>
<LocalizedString ElementType="ClaimType" ElementId="email" StringId="UserHelpText">Dirección de correo
electrónico que puede usarse para ponerse en contacto con usted.</LocalizedString>
<LocalizedString ElementType="ClaimType" ElementId="email" StringId="PatternHelpText">Introduzca una
dirección de correo electrónico.</LocalizedString>
<LocalizedString ElementType="UxElement" StringId="button_continue">Crear</LocalizedString>
<LocalizedString ElementType="ErrorMessage" StringId="UserMessageIfClaimsPrincipalAlreadyExists">Ya
existe un usuario con el id. especificado. Elija otro diferente.</LocalizedString>
</LocalizedStrings>
</LocalizedResources>
Edit the ContentDefinition for the page
For each page that you want to localize, specify the language codes to look for in the ContentDefinition.
In the following example, English (en) and Spanish (es) custom strings are added to the sign-up page. The
LocalizedResourcesReferenceId for each LocalizedResourcesReference is the same as their locale, but you
could use any string as the identifier. For each language and page combination, you point to the corresponding
LocalizedResources you previously created.
<ContentDefinition Id="api.localaccountsignup">
...
<LocalizedResourcesReferences MergeBehavior="Prepend">
<LocalizedResourcesReference Language="en" LocalizedResourcesReferenceId="api.localaccountsignup.en" />
<LocalizedResourcesReference Language="es" LocalizedResourcesReferenceId="api.localaccountsignup.es" />
</LocalizedResourcesReferences>
</ContentDefinition>
<BuildingBlocks>
<ContentDefinitions>
<ContentDefinition Id="api.localaccountsignup">
<!-- Other content definitions elements... -->
<LocalizedResourcesReferences MergeBehavior="Prepend">
<LocalizedResourcesReference Language="en"
LocalizedResourcesReferenceId="api.localaccountsignup.en" />
<LocalizedResourcesReference Language="es"
LocalizedResourcesReferenceId="api.localaccountsignup.es" />
</LocalizedResourcesReferences>
</ContentDefinition>
<!-- More content definitions... -->
</ContentDefinitions>
<Localization Enabled="true">
<LocalizedResources Id="api.localaccountsignup.en">
<LocalizedCollections>
<LocalizedCollection ElementType="ClaimType" ElementId="Gender" TargetCollection="Restriction">
<Item Text="Female" Value="F" />
<Item Text="Male" Value="M" />
<!-- More items... -->
</LocalizedCollection>
<LocalizedCollection ElementType="ClaimType" ElementId="City" TargetCollection="Restriction">
<Item Text="New York" Value="NY" />
<Item Text="Paris" Value="Paris" />
<Item Text="London" Value="London" />
</LocalizedCollection>
<!-- More localized collections... -->
</LocalizedCollections>
<LocalizedStrings>
<LocalizedString ElementType="ClaimType" ElementId="email"
StringId="DisplayName">Email</LocalizedString>
<LocalizedString ElementType="ClaimType" ElementId="email" StringId="UserHelpText">Please enter your
email</LocalizedString>
<LocalizedString ElementType="ClaimType" ElementId="email" StringId="PatternHelpText">Please enter a
valid email address</LocalizedString>
<LocalizedString ElementType="UxElement" StringId="button_continue">Create new
account</LocalizedString>
<LocalizedString ElementType="ErrorMessage" StringId="UserMessageIfClaimsPrincipalAlreadyExists">The
account you are trying to create already exists, please sign-in.</LocalizedString>
account you are trying to create already exists, please sign-in.</LocalizedString>
<!-- More localized strings... -->
</LocalizedStrings>
</LocalizedResources>
<LocalizedResources Id="api.localaccountsignup.es">
<LocalizedCollections>
<LocalizedCollection ElementType="ClaimType" ElementId="Gender" TargetCollection="Restriction">
<Item Text="Femenino" Value="F" />
<Item Text="Masculino" Value="M" />
</LocalizedCollection>
<LocalizedCollection ElementType="ClaimType" ElementId="City" TargetCollection="Restriction">
<Item Text="Nueva York" Value="NY" />
<Item Text="París" Value="Paris" />
<Item Text="Londres" Value="London" />
</LocalizedCollection>
</LocalizedCollections>
<LocalizedStrings>
<LocalizedString ElementType="ClaimType" ElementId="email" StringId="DisplayName">Dirección de
correo electrónico</LocalizedString>
<LocalizedString ElementType="ClaimType" ElementId="email" StringId="UserHelpText">Dirección de
correo electrónico que puede usarse para ponerse en contacto con usted.</LocalizedString>
<LocalizedString ElementType="ClaimType" ElementId="email" StringId="PatternHelpText">Introduzca una
dirección de correo electrónico.</LocalizedString>
<LocalizedString ElementType="UxElement" StringId="button_continue">Crear</LocalizedString>
<LocalizedString ElementType="ErrorMessage" StringId="UserMessageIfClaimsPrincipalAlreadyExists">Ya
existe un usuario con el id. especificado. Elija otro diferente.</LocalizedString>
</LocalizedStrings>
</LocalizedResources>
<!-- More localized resources... -->
</Localization>
</BuildingBlocks>
Localization string IDs
7/12/2019 • 6 minutes to read • Edit Online
NOTE
In Azure Active Directory B2C, custom policies are designed primarily to address complex scenarios. For most scenarios, we
recommend that you use built-in user flows.
The Localization element enables you to support multiple locales or languages in the policy for the user journeys.
This article provides the list of localization IDs that you can use in your policy. To get familiar with UI localization,
see Localization.
ID DEFAULT VALUE
email_pattern ^[a-zA-Z0-9.!#$%&’'+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-
zA-Z0-9-]+)$
logonIdentifier_username Username
password Password
divider_title OR
ID DEFAULT VALUE
button_signin Sign in
unknown_error We are having trouble signing you in. Please try again later.
The following example shows the use of some of the user interface elements in the sign-up or sign-in page:
The ID of the identity providers is configured in the user journey ClaimsExchange element. To localize the title of
the identity provider, the ElementType is set to ClaimsProvider , while the StringId is set to the ID of the
ClaimsExchange .
UserMessageIfUserAccountDisabled Your account has been locked. Contact your support person
to unlock it, then try again.
AADRequestsThrottled There are too many requests at this moment. Please wait for
some time and try again.
ID DEFAULT VALUE
ver_but_default Default
alert_yes Yes
error_fieldIncorrect One or more fields are filled out incorrectly. Please check your
entries and try again.
year Year
button_cancel Cancel
ID DEFAULT VALUE
ver_fail_no_retry You've made too many incorrect attempts. Please try again
later.
month Month
error_requiredFieldMissing A required field is missing. Please fill out all required fields and
try again.
button_continue Create
error_passwordEntryMismatch The password entry fields do not match. Please enter the
same password in both fields and try again.
alert_no No
ver_info_msg Verification code has been sent to your inbox. Please copy it
to the input box below.
day Day
ver_fail_throttled There have been too many requests to verify this email
address. Please wait a while, then try again.
alert_message Are you sure that you want to cancel entering your details?
ID DEFAULT VALUE
ServiceThrottled There are too many requests at this moment. Please wait for
some time and try again.
The following example shows the use of some of the user interface elements in the sign-up page:
The following example shows the use of some of the user interface elements in the sign-up page, after user clicks
on send verification code button:
ID DEFAULT VALUE
button_verify Call Me
code_pattern \d{6}
button_cancel Cancel
button_retry Retry
ID DEFAULT VALUE
intro_entry_sms Enter a number below that we can send a code via SMS to
authenticate you.
intro_sms We have the following number on record for you. We will send
a code via SMS to authenticate you.
intro_entry_mixed Enter a number below that we can send a code via SMS or
phone to authenticate you.
number_pattern ^\+(?:[0-9][\x20-]?){6,14}[0-9]$
error_incorrect_code The verification code you have entered does not match our
records. Please try again, or request a new code.
countryList {"DEFAULT":"Country/Region","AF":"Afghanistan","AX":"Åland
Islands","AL":"Albania","DZ":"Algeria","AS":"American
Samoa","AD":"Andorra","AO":"Angola","AI":"Anguilla","AQ":"Ant
arctica","AG":"Antigua and
Barbuda","AR":"Argentina","AM":"Armenia","AW":"Aruba","AU":
"Australia","AT":"Austria","AZ":"Azerbaijan","BS":"Bahamas","BH"
:"Bahrain","BD":"Bangladesh","BB":"Barbados","BY":"Belarus","BE
":"Belgium","BZ":"Belize","BJ":"Benin","BM":"Bermuda","BT":"Bhu
tan","BO":"Bolivia","BQ":"Bonaire","BA":"Bosnia and
Herzegovina","BW":"Botswana","BV":"Bouvet
Island","BR":"Brazil","IO":"British Indian Ocean
Island","BR":"Brazil","IO":"British Indian Ocean
ID Territory","VG":"British
DEFAULT VALUE Virgin
Islands","BN":"Brunei","BG":"Bulgaria","BF":"Burkina
Faso","BI":"Burundi","CV":"Cabo
Verde","KH":"Cambodia","CM":"Cameroon","CA":"Canada","KY":
"Cayman Islands","CF":"Central African
Republic","TD":"Chad","CL":"Chile","CN":"China","CX":"Christmas
Island","CC":"Cocos (Keeling)
Islands","CO":"Colombia","KM":"Comoros","CG":"Congo","CD":"
Congo (DRC)","CK":"Cook Islands","CR":"Costa Rica","CI":"Côte
d’Ivoire","HR":"Croatia","CU":"Cuba","CW":"Curaçao","CY":"Cypr
us","CZ":"Czech
Republic","DK":"Denmark","DJ":"Djibouti","DM":"Dominica","DO
":"Dominican Republic","EC":"Ecuador","EG":"Egypt","SV":"El
Salvador","GQ":"Equatorial
Guinea","ER":"Eritrea","EE":"Estonia","ET":"Ethiopia","FK":"Falklan
d Islands","FO":"Faroe
Islands","FJ":"Fiji","FI":"Finland","FR":"France","GF":"French
Guiana","PF":"French Polynesia","TF":"French Southern
Territories","GA":"Gabon","GM":"Gambia","GE":"Georgia","DE":"
Germany","GH":"Ghana","GI":"Gibraltar","GR":"Greece","GL":"Gr
eenland","GD":"Grenada","GP":"Guadeloupe","GU":"Guam","GT"
:"Guatemala","GG":"Guernsey","GN":"Guinea","GW":"Guinea-
Bissau","GY":"Guyana","HT":"Haiti","HM":"Heard Island and
McDonald Islands","HN":"Honduras","HK":"Hong Kong
SAR","HU":"Hungary","IS":"Iceland","IN":"India","ID":"Indonesia",
"IR":"Iran","IQ":"Iraq","IE":"Ireland","IM":"Isle of
Man","IL":"Israel","IT":"Italy","JM":"Jamaica","JP":"Japan","JE":"Jer
sey","JO":"Jordan","KZ":"Kazakhstan","KE":"Kenya","KI":"Kiribati",
"KR":"Korea","KW":"Kuwait","KG":"Kyrgyzstan","LA":"Laos","LV":"
Latvia","LB":"Lebanon","LS":"Lesotho","LR":"Liberia","LY":"Libya",
"LI":"Liechtenstein","LT":"Lithuania","LU":"Luxembourg","MO":"
Macao SAR","MK":"North
Macedonia","MG":"Madagascar","MW":"Malawi","MY":"Malaysi
a","MV":"Maldives","ML":"Mali","MT":"Malta","MH":"Marshall
Islands","MQ":"Martinique","MR":"Mauritania","MU":"Mauritius
","YT":"Mayotte","MX":"Mexico","FM":"Micronesia","MD":"Mold
ova","MC":"Monaco","MN":"Mongolia","ME":"Montenegro","M
S":"Montserrat","MA":"Morocco","MZ":"Mozambique","MM":"
Myanmar","NA":"Namibia","NR":"Nauru","NP":"Nepal","NL":"Net
herlands","NC":"New Caledonia","NZ":"New
Zealand","NI":"Nicaragua","NE":"Niger","NG":"Nigeria","NU":"Niu
e","NF":"Norfolk Island","KP":"North Korea","MP":"Northern
Mariana
Islands","NO":"Norway","OM":"Oman","PK":"Pakistan","PW":"Pal
au","PS":"Palestinian Authority","PA":"Panama","PG":"Papua
New
Guinea","PY":"Paraguay","PE":"Peru","PH":"Philippines","PN":"Pit
cairn Islands","PL":"Poland","PT":"Portugal","PR":"Puerto
Rico","QA":"Qatar","RE":"Réunion","RO":"Romania","RU":"Russia"
,"RW":"Rwanda","BL":"Saint Barthélemy","KN":"Saint Kitts and
Nevis","LC":"Saint Lucia","MF":"Saint Martin","PM":"Saint Pierre
and Miquelon","VC":"Saint Vincent and the
Grenadines","WS":"Samoa","SM":"San Marino","ST":"São Tomé
and Príncipe","SA":"Saudi
Arabia","SN":"Senegal","RS":"Serbia","SC":"Seychelles","SL":"Sierr
a Leone","SG":"Singapore","SX":"Sint
Maarten","SK":"Slovakia","SI":"Slovenia","SB":"Solomon
Islands","SO":"Somalia","ZA":"South Africa","GS":"South Georgia
and South Sandwich Islands","SS":"South
Sudan","ES":"Spain","LK":"Sri Lanka","SH":"St Helena, Ascension,
Tristan da
Cunha","SD":"Sudan","SR":"Suriname","SJ":"Svalbard","SZ":"Swaz
iland","SE":"Sweden","CH":"Switzerland","SY":"Syria","TW":"Taiwa
n","TJ":"Tajikistan","TZ":"Tanzania","TH":"Thailand","TL":"Timor-
Leste","TG":"Togo","TK":"Tokelau","TO":"Tonga","TT":"Trinidad
Leste","TG":"Togo","TK":"Tokelau","TO":"Tonga","TT":"Trinidad
ID and
DEFAULT VALUE
Tobago","TN":"Tunisia","TR":"Turkey","TM":"Turkmenistan","TC":
"Turks and Caicos Islands","TV":"Tuvalu","UM":"U.S. Outlying
Islands","VI":"U.S. Virgin
Islands","UG":"Uganda","UA":"Ukraine","AE":"United Arab
Emirates","GB":"United Kingdom","US":"United
States","UY":"Uruguay","UZ":"Uzbekistan","VU":"Vanuatu","VA":
"Vatican City","VE":"Venezuela","VN":"Vietnam","WF":"Wallis
and Futuna","YE":"Yemen","ZM":"Zambia","ZW":"Zimbabwe"}
The following example shows the use of some of the user interface elements in the MFA enrollment page:
The following example shows the use of some of the user interface elements in the MFA validation page:
ClaimsProviders
6/4/2019 • 2 minutes to read • Edit Online
NOTE
In Azure Active Directory B2C, custom policies are designed primarily to address complex scenarios. For most scenarios, we
recommend that you use built-in user flows.
A claims provider contains a set of technical profiles. Every claims provider must have one or more technical
profiles that determine the endpoints and the protocols needed to communicate with the claims provider. A claims
provider can have multiple technical profiles. For example, multiple technical profiles may be defined because the
claims provider supports multiple protocols, various endpoints with different capabilities, or releases different
claims at different assurance levels. It may be acceptable to release sensitive claims in one user journey, but not in
another.
<ClaimsProviders>
<ClaimsProvider>
<Domain>Domain name</Domain>
<DisplayName>Display name</DisplayName>
<TechnicalProfiles>
</TechnicalProfile>
...
</TechnicalProfile>
...
</TechnicalProfiles>
</ClaimsProvider>
...
</ClaimsProviders>
ClaimsProvider
The ClaimsProvider element contains the following child elements:
ClaimsProvider organizes how your technical profiles relate to the claims provider. The following example shows
the Azure Active Directory claims provider with the Azure Active Directory technical profiles:
<ClaimsProvider>
<DisplayName>Azure Active Directory</DisplayName>
<TechnicalProfiles>
<TechnicalProfile Id="AAD-Common">
...
</TechnicalProfile>
<TechnicalProfile Id="AAD-UserWriteUsingAlternativeSecurityId">
...
</TechnicalProfile>
<TechnicalProfile Id="AAD-UserReadUsingAlternativeSecurityId">
...
</TechnicalProfile>
<TechnicalProfile Id="AAD-UserReadUsingAlternativeSecurityId-NoError">
...
</TechnicalProfile>
<TechnicalProfile Id="AAD-UserReadUsingEmailAddress">
...
</TechnicalProfile>
...
<TechnicalProfile Id="AAD-UserWritePasswordUsingObjectId">
...
</TechnicalProfile>
<TechnicalProfile Id="AAD-UserWriteProfileUsingObjectId">
...
</TechnicalProfile>
<TechnicalProfile Id="AAD-UserReadUsingObjectId">
...
</TechnicalProfile>
<TechnicalProfile Id="AAD-UserWritePhoneNumberUsingObjectId">
...
</TechnicalProfile>
</TechnicalProfiles>
</ClaimsProvider>
The following example shows the Facebook claims provider with the Facebook-OAUTH technical profile.
<ClaimsProvider>
<Domain>facebook.com</Domain>
<DisplayName>Facebook</DisplayName>
<TechnicalProfiles>
<TechnicalProfile Id="Facebook-OAUTH">
<DisplayName>Facebook</DisplayName>
<Protocol Name="OAuth2" />
...
</TechnicalProfile>
</TechnicalProfiles>
</ClaimsProvider>
TechnicalProfiles
12/12/2019 • 9 minutes to read • Edit Online
NOTE
In Azure Active Directory B2C, custom policies are designed primarily to address complex scenarios. For most scenarios, we
recommend that you use built-in user flows.
A TechnicalProfiles element contains a set of technical profiles supported by the claim provider. Every claims
provider must have one or more technical profiles that determine the endpoints and the protocols needed to
communicate with the claims provider. A claims provider can have multiple technical profiles.
<ClaimsProvider>
<DisplayName>Display name</DisplayName>
<TechnicalProfiles>
<TechnicalProfile Id="Technical profile identifier">
<DisplayName>Display name of technical profile</DisplayName>
<Protocol Name="Proprietary" Handler="Web.TPEngine.Providers.RestfulProvider, Web.TPEngine,
Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
<Metadata>
<Item Key="ServiceUrl">URL of service</Item>
<Item Key="AuthenticationType">None</Item>
<Item Key="SendClaimsIn">Body</Item>
</Metadata>
<InputTokenFormat>JWT</InputTokenFormat>
<OutputTokenFormat>JWT</OutputTokenFormat>
<CryptographicKeys>
<Key ID="Key identifier" StorageReferenceId="Storage key container identifier"/>
...
</CryptographicKeys>
<InputClaimsTransformations>
<InputClaimsTransformation ReferenceId="Claims transformation identifier" />
...
<InputClaimsTransformations>
<InputClaims>
<InputClaim ClaimTypeReferenceId="givenName" DefaultValue="givenName" PartnerClaimType="firstName" />
...
</InputClaims>
<PersistedClaims>
<PersistedClaim ClaimTypeReferenceId="givenName" DefaultValue="givenName" PartnerClaimType="firstName"
/>
...
</PersistedClaims>
<OutputClaims>
<OutputClaim ClaimTypeReferenceId="loyaltyNumber" DefaultValue="loyaltyNumber"
PartnerClaimType="loyaltyNumber" />
</OutputClaims>
<OutputClaimsTransformations>
<OutputClaimsTransformation ReferenceId="Claims transformation identifier" />
...
<OutputClaimsTransformations>
<ValidationTechnicalProfiles>
<ValidationTechnicalProfile ReferenceId="Technical profile identifier" />
...
</ValidationTechnicalProfiles>
<SubjectNamingInfo ClaimType="Claim type identifier" />
<IncludeTechnicalProfile ReferenceId="Technical profile identifier" />
<UseTechnicalProfileForSessionManagement ReferenceId="Technical profile identifier" />
</TechnicalProfile>
</TechnicalProfiles>
</ClaimsProvider>
Protocol
The Protocol element contains the following attributes:
Metadata
Item
The Item element of the Metadata element contains the following attributes:
CryptographicKeys
The CryptographicKeys element contains the following element:
Key
The Key element contains the following attribute:
InputClaimsTransformations
The InputClaimsTransformations element contains the following element:
InputClaimsTransformation
The InputClaimsTransformation element contains the following attribute:
InputClaims
The InputClaims element contains the following element:
InputClaim
The InputClaim element contains the following attributes:
DisplayClaims
The DisplayClaims element contains the following element:
PersistedClaim
The PersistedClaim element contains the following attributes:
ATTRIBUTE REQUIRED DESCRIPTION
OutputClaims
The OutputClaims element contains the following element:
OutputClaim
The OutputClaim element contains the following attributes:
OutputClaimsTransformations
The OutputClaimsTransformations element contains the following element:
OutputClaimsTransformation
The OutputClaimsTransformation element contains the following attribute:
ValidationTechnicalProfiles
The ValidationTechnicalProfiles element contains the following element:
ValidationTechnicalProfile
The ValidationTechnicalProfile element contains the following attribute:
ATTRIBUTE REQUIRED DESCRIPTION
SubjectNamingInfo
The SubjectNamingInfo contains the following attribute:
IncludeTechnicalProfile
The IncludeTechnicalProfile element contains the following attribute:
UseTechnicalProfileForSessionManagement
The UseTechnicalProfileForSessionManagement element contains the following attribute:
EnabledForUserJourneys
The ClaimsProviderSelections in a user journey defines the list of claims provider selection options and their
order. With the EnabledForUserJourneys element you filter, which claims provider is available to the user. The
EnabledForUserJourneys element contains one of the following values:
Always, execute the technical profile.
Never, skip the technical profile.
OnClaimsExistence execute only when a certain claim, specified in the technical profile exists.
OnItemExistenceInStringCollectionClaim, execute only when an item exists in a string collection claim.
OnItemAbsenceInStringCollectionClaim execute only when an item does not exist in a string collection
claim.
Using OnClaimsExistence, OnItemExistenceInStringCollectionClaim or
OnItemAbsenceInStringCollectionClaim, requires you to provide the following metadata:
ClaimTypeOnWhichToEnable specifies the claim's type that is to be evaluated,
ClaimValueOnWhichToEnable specifies the value that is to be compared.
The following technical profile is executed only if the identityProviders string collection contains the value of
facebook.com :
<TechnicalProfile Id="UnLink-Facebook-OAUTH">
<DisplayName>Unlink Facebook</DisplayName>
...
<Metadata>
<Item Key="ClaimTypeOnWhichToEnable">identityProviders</Item>
<Item Key="ClaimValueOnWhichToEnable">facebook.com</Item>
</Metadata>
...
<EnabledForUserJourneys>OnItemExistenceInStringCollectionClaim</EnabledForUserJourneys>
</TechnicalProfile>
About technical profiles in Azure Active Directory
B2C custom policies
12/9/2019 • 5 minutes to read • Edit Online
NOTE
In Azure Active Directory B2C, custom policies are designed primarily to address complex scenarios. For most scenarios, we
recommend that you use built-in user flows.
A technical profile provides a framework with a built-in mechanism to communicate with different type of parties
using a custom policy in Azure Active Directory B2C (Azure AD B2C ). Technical profiles are used to communicate
with your Azure AD B2C tenant, to create a user, or read a user profile. A technical profile can be self-asserted to
enable interaction with the user. For example, collect the user's credential to sign in and then render the sign-up
page or password reset page.
<TechnicalProfile Id="AAD-UserReadUsingAlternativeSecurityId-NoError">
<Metadata>
<Item Key="RaiseErrorIfClaimsPrincipalDoesNotExist">false</Item>
</Metadata>
<IncludeTechnicalProfile ReferenceId="AAD-UserReadUsingAlternativeSecurityId" />
</TechnicalProfile>
<TechnicalProfile Id="AAD-UserReadUsingAlternativeSecurityId">
<Metadata>
<Item Key="Operation">Read</Item>
<Item Key="RaiseErrorIfClaimsPrincipalDoesNotExist">true</Item>
<Item Key="UserMessageIfClaimsPrincipalDoesNotExist">User does not exist. Please sign up before you can
sign in.</Item>
</Metadata>
<InputClaims>
<InputClaim ClaimTypeReferenceId="AlternativeSecurityId" PartnerClaimType="alternativeSecurityId"
Required="true" />
</InputClaims>
<OutputClaims>
<OutputClaim ClaimTypeReferenceId="objectId" />
<OutputClaim ClaimTypeReferenceId="userPrincipalName" />
<OutputClaim ClaimTypeReferenceId="displayName" />
<OutputClaim ClaimTypeReferenceId="otherMails" />
<OutputClaim ClaimTypeReferenceId="givenName" />
<OutputClaim ClaimTypeReferenceId="surname" />
</OutputClaims>
<IncludeTechnicalProfile ReferenceId="AAD-Common" />
</TechnicalProfile>
<TechnicalProfile Id="AAD-Common">
<DisplayName>Azure Active Directory</DisplayName>
<Protocol Name="Proprietary" Handler="Web.TPEngine.Providers.AzureActiveDirectoryProvider, Web.TPEngine,
Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
...
</TechnicalProfile>
A technical profile may include or inherit another technical profile, which may include another one. There is no limit
on the number of levels. Depending on the business requirements, your user journey may call AAD -
UserReadUsingAlternativeSecurityId that raises an error if a user social account doesn't exist, or AAD -
UserReadUsingAlternativeSecurityId-NoError which doesn't raise an error.
About claim resolvers in Azure Active Directory B2C
custom policies
12/9/2019 • 4 minutes to read • Edit Online
Claim resolvers in Azure Active Directory B2C (Azure AD B2C ) custom policies provide context information about
an authorization request, such as the policy name, request correlation ID, user interface language, and more.
To use a claim resolver in an input or output claim, you define a string ClaimType, under the ClaimsSchema
element, and then you set the DefaultValue to the claim resolver in the input or output claim element. Azure AD
B2C reads the value of the claim resolver and uses the value in the technical profile.
In the following example, a claim type named correlationId is defined with a DataType of string .
<ClaimType Id="correlationId">
<DisplayName>correlationId</DisplayName>
<DataType>string</DataType>
<UserHelpText>Request correlation Id</UserHelpText>
</ClaimType>
In the technical profile, map the claim resolver to the claim type. Azure AD B2C populates the value of the claim
resolver {Context:CorrelationId} into the claim correlationId and sends the claim to the technical profile.
Policy
CLAIM DESCRIPTION EXAMPLE
OpenID Connect
CLAIM DESCRIPTION EXAMPLE
Context
CLAIM DESCRIPTION EXAMPLE
Non-protocol parameters
Any parameter name included as part of an OIDC or OAuth2 request can be mapped to a claim in the user
journey. For example, the request from the application might include a query string parameter with a name of
app_session , loyalty_number , or any custom query string.
CLAIM DESCRIPTION EXAMPLE
OAuth2
CLAIM DESCRIPTION EXAMPLE
<TechnicalProfile Id="REST">
<DisplayName>Validate user input data and return loyaltyNumber claim</DisplayName>
<Protocol Name="Proprietary" Handler="Web.TPEngine.Providers.RestfulProvider, Web.TPEngine, Version=1.0.0.0,
Culture=neutral, PublicKeyToken=null" />
<Metadata>
<Item Key="ServiceUrl">https://your-app.azurewebsites.net/api/identity</Item>
<Item Key="AuthenticationType">None</Item>
<Item Key="SendClaimsIn">Body</Item>
</Metadata>
<InputClaims>
<InputClaim ClaimTypeReferenceId="userLanguage" DefaultValue="{Culture:LCID}" />
<InputClaim ClaimTypeReferenceId="policyName" DefaultValue="{Policy:PolicyId}" />
<InputClaim ClaimTypeReferenceId="scope" DefaultValue="{OIDC:scope}" />
<InputClaim ClaimTypeReferenceId="clientId" DefaultValue="{OIDC:ClientId}" />
</InputClaims>
<UseTechnicalProfileForSessionManagement ReferenceId="SM-Noop" />
</TechnicalProfile>
Direct sign-in
Using claim resolvers, you can prepopulate the sign-in name or direct sign-in to a specific social identity provider,
such as Facebook, LinkedIn, or a Microsoft account. For more information, see Set up direct sign-in using Azure
Active Directory B2C.
Dynamic UI customization
Azure AD B2C enables you to pass query string parameters to your HTML content definition endpoints so that
you can dynamically render the page content. For example, you can change the background image on the Azure
AD B2C sign-up or sign-in page based on a custom parameter that you pass from your web or mobile application.
For more information, see Dynamically configure the UI by using custom policies in Azure Active Directory B2C.
You can also localize your HTML page based on a language parameter, or you can change the content based on the
client ID.
The following example passes in the query string a parameter named campaignId with a value of hawaii ,a
language code of en-US , and app representing the client ID:
<UserJourneyBehaviors>
<ContentDefinitionParameters>
<Parameter Name="campaignId">{OAUTH-KV:campaignId}</Parameter>
<Parameter Name="language">{Culture:RFC5646}</Parameter>
<Parameter Name="app">{OIDC:ClientId}</Parameter>
</ContentDefinitionParameters>
</UserJourneyBehaviors>
As a result Azure AD B2C sends the above parameters to the HTML content page:
/selfAsserted.aspx?campaignId=hawaii&language=en-US&app=0239a9cc-309c-4d41-87f1-31288feb2e82
<TechnicalProfile Id="AzureInsights-Common">
<DisplayName>Alternate Email</DisplayName>
<Protocol Name="Proprietary" Handler="Web.TPEngine.Providers.Insights.AzureApplicationInsightsProvider,
Web.TPEngine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
...
<InputClaims>
<InputClaim ClaimTypeReferenceId="PolicyId" PartnerClaimType="{property:Policy}" DefaultValue="
{Policy:PolicyId}" />
<InputClaim ClaimTypeReferenceId="CorrelationId" PartnerClaimType="{property:CorrelationId}"
DefaultValue="{Context:CorrelationId}" />
<InputClaim ClaimTypeReferenceId="language" PartnerClaimType="{property:language}" DefaultValue="
{Culture:RFC5646}" />
<InputClaim ClaimTypeReferenceId="AppId" PartnerClaimType="{property:App}" DefaultValue="{OIDC:ClientId}"
/>
</InputClaims>
</TechnicalProfile>
Define an Azure Active Directory technical profile in
an Azure Active Directory B2C custom policy
12/9/2019 • 6 minutes to read • Edit Online
NOTE
In Azure Active Directory B2C, custom policies are designed primarily to address complex scenarios. For most scenarios, we
recommend that you use built-in user flows.
Azure Active Directory B2C (Azure AD B2C ) provides support for the Azure Active Directory user management.
This article describes the specifics of a technical profile for interacting with a claims provider that supports this
standardized protocol.
Protocol
The Name attribute of the Protocol element needs to be set to Proprietary . The handler attribute must contain
the fully qualified name of the protocol handler assembly
Web.TPEngine.Providers.AzureActiveDirectoryProvider, Web.TPEngine, Version=1.0.0.0, Culture=neutral,
PublicKeyToken=null
.
All Azure AD technical profiles include the AAD -Common technical profile. The following technical profiles don't
specify the protocol because the protocol is configured in the AAD -Common technical profile:
AAD -UserReadUsingAlternativeSecurityId and AAD -UserReadUsingAlternativeSecurityId-NoError -
Look up a social account in the directory.
AAD -UserWriteUsingAlternativeSecurityId - Create a new social account.
AAD -UserReadUsingEmailAddress - Look up a local account in the directory.
AAD -UserWriteUsingLogonEmail - Create a new local account.
AAD -UserWritePasswordUsingObjectId - Update a password of a local account.
AAD -UserWriteProfileUsingObjectId - Update a user profile of a local or social account.
AAD -UserReadUsingObjectId - Read a user profile of a local or social account.
AAD -UserWritePhoneNumberUsingObjectId - Write the MFA phone number of a local or social account
The following example shows the AAD -Common technical profile:
<TechnicalProfile Id="AAD-Common">
<DisplayName>Azure Active Directory</DisplayName>
<Protocol Name="Proprietary" Handler="Web.TPEngine.Providers.AzureActiveDirectoryProvider, Web.TPEngine,
Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
<CryptographicKeys>
<Key Id="issuer_secret" StorageReferenceId="B2C_1A_TokenSigningKeyContainer" />
</CryptographicKeys>
<!-- We need this here to suppress the SelfAsserted provider from invoking SSO on validation profiles. -->
<IncludeInSso>false</IncludeInSso>
<UseTechnicalProfileForSessionManagement ReferenceId="SM-Noop" />
</TechnicalProfile>
Input claims
The following technical profiles include InputClaims for social and local accounts:
The social account technical profiles AAD -UserReadUsingAlternativeSecurityId and AAD -
UserWriteUsingAlternativeSecurityId includes the AlternativeSecurityId claim. This claim contains the
social account user identifier.
The local account technical profiles AAD -UserReadUsingEmailAddress and AAD -
UserWriteUsingLogonEmail includes the email claim. This claim contains the sign-in name of the local
account.
The unified (local and social) technical profiles AAD -UserReadUsingObjectId, AAD -
UserWritePasswordUsingObjectId, AAD -UserWriteProfileUsingObjectId, and AAD -
UserWritePhoneNumberUsingObjectId includes the objectId claim. The unique identifier of an account.
The InputClaimsTransformations element may contain a collection of InputClaimsTransformation elements
that are used to modify the input claims or generate new ones.
Output claims
The OutputClaims element contains a list of claims returned by the Azure AD technical profile. You may need to
map the name of the claim defined in your policy to the name defined in Azure Active Directory. You can also
include claims that aren't returned by the Azure Active Directory, as long as you set the DefaultValue attribute.
The OutputClaimsTransformations element may contain a collection of OutputClaimsTransformation
elements that are used to modify the output claims or generate new ones.
For example, the AAD -UserWriteUsingLogonEmail technical profile creates a local account and returns the
following claims:
objectId, which is identifier of the new account
newUser, which indicates whether the user is new
authenticationSource, which sets authentication to localAccountAuthentication
userPrincipalName, which is the user principal name of the new account
signInNames.emailAddress, which is the account sign-in name, similar to the email input claim
<OutputClaims>
<OutputClaim ClaimTypeReferenceId="objectId" />
<OutputClaim ClaimTypeReferenceId="newUser" PartnerClaimType="newClaimsPrincipalCreated" />
<OutputClaim ClaimTypeReferenceId="authenticationSource" DefaultValue="localAccountAuthentication" />
<OutputClaim ClaimTypeReferenceId="userPrincipalName" />
<OutputClaim ClaimTypeReferenceId="signInNames.emailAddress" />
</OutputClaims>
PersistedClaims
The PersistedClaims element contains all of the values that should be persisted by Azure AD with possible
mapping information between a claim type already defined in the ClaimsSchema section in the policy and the
Azure AD attribute name.
The AAD -UserWriteUsingLogonEmail technical profile, which creates new local account, persists following
claims:
<PersistedClaims>
<!-- Required claims -->
<PersistedClaim ClaimTypeReferenceId="email" PartnerClaimType="signInNames.emailAddress" />
<PersistedClaim ClaimTypeReferenceId="newPassword" PartnerClaimType="password"/>
<PersistedClaim ClaimTypeReferenceId="displayName" DefaultValue="unknown" />
<PersistedClaim ClaimTypeReferenceId="passwordPolicies" DefaultValue="DisablePasswordExpiration" />
The name of the claim is the name of the Azure AD attribute unless the PartnerClaimType attribute is specified,
which contains the Azure AD attribute name.
Requirements of an operation
There must be exactly one InputClaim element in the claims bag for all Azure AD technical profiles.
If the operation is Write or DeleteClaims , then it must also appear in a PersistedClaims element.
The value of the userPrincipalName claim must be in the format of user@tenant.onmicrosoft.com .
The displayName claim is required and cannot be an empty string.
<TechnicalProfile Id="AAD-UserReadUsingObjectId">
<Metadata>
<Item Key="Operation">Read</Item>
<Item Key="RaiseErrorIfClaimsPrincipalDoesNotExist">true</Item>
</Metadata>
<IncludeInSso>false</IncludeInSso>
<InputClaims>
<InputClaim ClaimTypeReferenceId="objectId" Required="true" />
</InputClaims>
<OutputClaims>
Write
The Write operation creates or updates a single user account. To write a user account, you need to provide a key
as an input claim, such as objectId, userPrincipalName, signInNames.emailAddress, or
alternativeSecurityId.
The following technical profile creates new social account:
<TechnicalProfile Id="AAD-UserWriteUsingAlternativeSecurityId">
<Metadata>
<Item Key="Operation">Write</Item>
<Item Key="RaiseErrorIfClaimsPrincipalAlreadyExists">true</Item>
<Item Key="UserMessageIfClaimsPrincipalAlreadyExists">You are already registered, please press the back
button and sign in instead.</Item>
</Metadata>
<IncludeInSso>false</IncludeInSso>
<InputClaimsTransformations>
<InputClaimsTransformation ReferenceId="CreateOtherMailsFromEmail" />
</InputClaimsTransformations>
<InputClaims>
<InputClaim ClaimTypeReferenceId="AlternativeSecurityId" PartnerClaimType="alternativeSecurityId"
Required="true" />
</InputClaims>
<PersistedClaims>
<!-- Required claims -->
<PersistedClaim ClaimTypeReferenceId="alternativeSecurityId" />
<PersistedClaim ClaimTypeReferenceId="userPrincipalName" />
<PersistedClaim ClaimTypeReferenceId="mailNickName" DefaultValue="unknown" />
<PersistedClaim ClaimTypeReferenceId="displayName" DefaultValue="unknown" />
DeleteClaims
The DeleteClaims operation clears the information from a provided list of claims. To delete information from
claims, you need to provide a key as an input claim, such as objectId, userPrincipalName,
signInNames.emailAddress or alternativeSecurityId.
The following technical profile deletes claims:
<TechnicalProfile Id="AAD-DeleteClaimsUsingObjectId">
<Metadata>
<Item Key="Operation">DeleteClaims</Item>
</Metadata>
<InputClaims>
<InputClaim ClaimTypeReferenceId="objectId" Required="true" />
</InputClaims>
<PersistedClaims>
<PersistedClaim ClaimTypeReferenceId="objectId" />
<PersistedClaim ClaimTypeReferenceId="Verified.strongAuthenticationPhoneNumber"
PartnerClaimType="strongAuthenticationPhoneNumber" />
</PersistedClaims>
<OutputClaims />
<IncludeTechnicalProfile ReferenceId="AAD-Common" />
</TechnicalProfile>
DeleteClaimsPrincipal
The DeleteClaimsPrincipal operation deletes a single user account from the directory. To delete a user account,
you need to provide a key as an input claim, such as objectId, userPrincipalName,
signInNames.emailAddress or alternativeSecurityId.
The following technical profile deletes a user account from the directory using the user principal name:
<TechnicalProfile Id="AAD-DeleteUserUsingObjectId">
<Metadata>
<Item Key="Operation">DeleteClaimsPrincipal</Item>
</Metadata>
<InputClaims>
<InputClaim ClaimTypeReferenceId="objectId" Required="true" />
</InputClaims>
<OutputClaims/>
<IncludeTechnicalProfile ReferenceId="AAD-Common" />
</TechnicalProfile>
The following technical profile deletes a social user account using alternativeSecurityId:
<TechnicalProfile Id="AAD-DeleteUserUsingAlternativeSecurityId">
<Metadata>
<Item Key="Operation">DeleteClaimsPrincipal</Item>
</Metadata>
<InputClaims>
<InputClaim ClaimTypeReferenceId="alternativeSecurityId" Required="true" />
</InputClaims>
<OutputClaims/>
<IncludeTechnicalProfile ReferenceId="AAD-Common" />
</TechnicalProfile>
Metadata
NOTE
In Azure Active Directory B2C, custom policies are designed primarily to address complex scenarios. For most scenarios, we
recommend that you use built-in user flows.
A claims transformation technical profile enables you to call output claims transformations to manipulate claims
values, validate claims, or set default values for a set of output claims.
Protocol
The Name attribute of the Protocol element needs to be set to Proprietary . The handler attribute must contain
the fully qualified name of the protocol handler assembly that is used by Azure AD B2C:
Web.TPEngine.Providers.ClaimsTransformationProtocolProvider, Web.TPEngine, Version=1.0.0.0, Culture=neutral,
PublicKeyToken=null
.
The following example shows a claims transformation technical profile:
<TechnicalProfile Id="Facebook-OAUTH-UnLink">
<DisplayName>Unlink Facebook</DisplayName>
<Protocol Name="Proprietary" Handler="Web.TPEngine.Providers.ClaimsTransformationProtocolProvider,
Web.TPEngine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
...
Output claims
The OutputClaims element is mandatory. You should provide at least one output claim returned by the technical
profile. The following example shows how to set default values in the output claims:
<OutputClaims>
<OutputClaim ClaimTypeReferenceId="ageGroup" DefaultValue="Undefined" />
<OutputClaim ClaimTypeReferenceId="ageGroupValueChanged" DefaultValue="false" />
</OutputClaims>
The claims transformation technical profile enables you to execute a claims transformation from any user journey's
orchestration step. In the following example, the orchestration step calls one of the unlink technical profiles, such as
UnLink-Facebook-OAUTH. This technical profile calls the claims transformation technical profile
RemoveAlternativeSecurityIdByIdentityProvider, which generates a new AlternativeSecurityIds2 claim
that contains the list of user social identities, while removing the Facebook identity from the collections.
<UserJourney Id="AccountUnLink">
<OrchestrationSteps>
...
<OrchestrationStep Order="8" Type="ClaimsExchange">
<ClaimsExchanges>
<ClaimsExchange Id="UnLinkFacebookExchange" TechnicalProfileReferenceId="UnLink-Facebook-OAUTH" />
<ClaimsExchange Id="UnLinkMicrosoftExchange" TechnicalProfileReferenceId="UnLink-Microsoft-OAUTH" />
<ClaimsExchange Id="UnLinkGitHubExchange" TechnicalProfileReferenceId="UnLink-GitHub-OAUTH" />
</ClaimsExchanges>
</OrchestrationStep>
...
</OrchestrationSteps>
</UserJourney>
The claims transformation technical profile calls the AssertEmailAreEqual claims transformation, which asserts
that emails provided by the user are same.
<TechnicalProfile Id="Validate-Email">
<DisplayName>Unlink Facebook</DisplayName>
<Protocol Name="Proprietary" Handler="Web.TPEngine.Providers.ClaimsTransformationProtocolProvider,
Web.TPEngine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
<InputClaims>
<InputClaim ClaimTypeReferenceId="emailRepeat" />
</InputClaims>
<OutputClaims>
<OutputClaim ClaimTypeReferenceId="email" />
</OutputClaims>
<OutputClaimsTransformations>
<OutputClaimsTransformation ReferenceId="AssertEmailAreEqual" />
</OutputClaimsTransformations>
<UseTechnicalProfileForSessionManagement ReferenceId="SM-Noop" />
</TechnicalProfile>
A self-asserted technical profile can call the validation technical profile and show the error message as specified in
the UserMessageIfClaimsTransformationStringsAreNotEqual metadata.
<TechnicalProfile Id="LocalAccountSignUpWithLogonEmail">
<DisplayName>User ID signup</DisplayName>
<Protocol Name="Proprietary" Handler="Web.TPEngine.Providers.SelfAssertedAttributeProvider, Web.TPEngine,
Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
<Metadata>
...
<Item Key="UserMessageIfClaimsTransformationStringsAreNotEqual">The email addresses you provided are not
the same</Item>
</Metadata>
<OutputClaims>
<OutputClaim ClaimTypeReferenceId="email" />
<OutputClaim ClaimTypeReferenceId="emailRepeat" />
...
</OutputClaims>
<ValidationTechnicalProfiles>
<ValidationTechnicalProfile ReferenceId="Validate-Email" />
</ValidationTechnicalProfiles>
</TechnicalProfile>
Define a technical profile for a JWT token issuer in an
Azure Active Directory B2C custom policy
12/9/2019 • 3 minutes to read • Edit Online
NOTE
In Azure Active Directory B2C, custom policies are designed primarily to address complex scenarios. For most scenarios, we
recommend that you use built-in user flows.
Azure Active Directory B2C (Azure AD B2C ) emits several types of security tokens as it processes each authentication
flow. A technical profile for a JWT token issuer emits a JWT token that is returned back to the relying party application.
Usually this technical profile is the last orchestration step in the user journey.
Protocol
The Name attribute of the Protocol element needs to be set to None . Set the OutputTokenFormat element to JWT .
The following example shows a technical profile for JwtIssuer :
<TechnicalProfile Id="JwtIssuer">
<DisplayName>JWT Issuer</DisplayName>
<Protocol Name="None" />
<OutputTokenFormat>JWT</OutputTokenFormat>
...
</TechnicalProfile>
Metadata
Cryptographic keys
The CryptographicKeys element contains the following attributes:
NOTE
In Azure Active Directory B2C, custom policies are designed primarily to address complex scenarios. For most scenarios, we
recommend that you use built-in user flows.
Azure Active Directory B2C (Azure AD B2C ) provides support for the OAuth 1.0 protocol identity provider. This
article describes the specifics of a technical profile for interacting with a claims provider that supports this
standardized protocol. With an OAuth1 technical profile, you can federate with an OAuth1 based identity provider,
such as Twitter. Federating with the identity provider allows users to sign in with their existing social or enterprise
identities.
Protocol
The Name attribute of the Protocol element needs to be set to OAuth1 . For example, the protocol for the Twitter-
OAUTH1 technical profile is OAuth1 .
<TechnicalProfile Id="Twitter-OAUTH1">
<DisplayName>Twitter</DisplayName>
<Protocol Name="OAuth1" />
...
Input claims
The InputClaims and InputClaimsTransformations elements are empty or absent.
Output claims
The OutputClaims element contains a list of claims returned by the OAuth1 identity provider. You may need to
map the name of the claim defined in your policy to the name defined in the identity provider. You can also include
claims that aren't returned by the identity provider as long as you set the DefaultValue attribute.
The OutputClaimsTransformations element may contain a collection of OutputClaimsTransformation
elements that are used to modify the output claims or generate new ones.
The following example shows the claims returned by the Twitter identity provider:
The user_id claim that is mapped to the issuerUserId claim.
The screen_name claim that is mapped to the displayName claim.
The email claim without name mapping.
The technical profile also returns claims that aren't returned by the identity provider:
The identityProvider claim that contains the name of the identity provider.
The authenticationSource claim with a default value of socialIdpAuthentication .
<OutputClaims>
<OutputClaim ClaimTypeReferenceId="issuerUserId" PartnerClaimType="user_id" />
<OutputClaim ClaimTypeReferenceId="displayName" PartnerClaimType="screen_name" />
<OutputClaim ClaimTypeReferenceId="email" />
<OutputClaim ClaimTypeReferenceId="identityProvider" DefaultValue="twitter.com" />
<OutputClaim ClaimTypeReferenceId="authenticationSource" DefaultValue="socialIdpAuthentication" />
</OutputClaims>
Metadata
Cryptographic keys
The CryptographicKeys element contains the following attribute:
Redirect URI
When you configure the redirect URL of your identity provider, enter
https://login.microsoftonline.com/te/tenant/policyId/oauth1/authresp . Make sure to replace tenant with your
tenant name (for example, contosob2c.onmicrosoft.com) and policyId with the identifier of your policy (for
example, b2c_1a_policy). The redirect URI needs to be in all lowercase. Add a redirect URL for all policies that use
the identity provider login.
If you are using the b2clogin.com domain instead of login.microsoftonline.com Make sure to use
b2clogin.com instead of login.microsoftonline.com.
Examples:
Add Twitter as an OAuth1 identity provider by using custom policies
Define an OAuth2 technical profile in an Azure Active
Directory B2C custom policy
12/9/2019 • 4 minutes to read • Edit Online
NOTE
In Azure Active Directory B2C, custom policies are designed primarily to address complex scenarios. For most scenarios, we
recommend that you use built-in user flows.
Azure Active Directory B2C (Azure AD B2C ) provides support for the OAuth2 protocol identity provider. OAuth2 is
the primary protocol for authorization and delegated authentication. For more information, see the RFC 6749 The
OAuth 2.0 Authorization Framework. With an OAuth2 technical profile, you can federate with an OAuth2 based
identity provider, such as Facebook. Federating with an identity provider allows users to sign in with their existing
social or enterprise identities.
Protocol
The Name attribute of the Protocol element needs to be set to OAuth2 . For example, the protocol for the
Facebook-OAUTH technical profile is OAuth2 :
<TechnicalProfile Id="Facebook-OAUTH">
<DisplayName>Facebook</DisplayName>
<Protocol Name="OAuth2" />
...
Input claims
The InputClaims and InputClaimsTransformations elements are not required. But you may want to send
additional parameters to your identity provider. The following example adds the domain_hint query string
parameter with the value of contoso.com to the authorization request.
<InputClaims>
<InputClaim ClaimTypeReferenceId="domain_hint" DefaultValue="contoso.com" />
</InputClaims>
Output claims
The OutputClaims element contains a list of claims returned by the OAuth2 identity provider. You may need to
map the name of the claim defined in your policy to the name defined in the identity provider. You can also include
claims that aren't returned by the identity provider as long as you set the DefaultValue attribute.
The OutputClaimsTransformations element may contain a collection of OutputClaimsTransformation
elements that are used to modify the output claims or generate new ones.
The following example shows the claims returned by the Facebook identity provider:
The first_name claim is mapped to the givenName claim.
The last_name claim is mapped to the surname claim.
The displayName claim without name-mapping.
The email claim without name mapping.
The technical profile also returns claims that aren't returned by the identity provider:
The identityProvider claim that contains the name of the identity provider.
The authenticationSource claim with a default value of socialIdpAuthentication.
<OutputClaims>
<OutputClaim ClaimTypeReferenceId="issuerUserId" PartnerClaimType="id" />
<OutputClaim ClaimTypeReferenceId="givenName" PartnerClaimType="first_name" />
<OutputClaim ClaimTypeReferenceId="surname" PartnerClaimType="last_name" />
<OutputClaim ClaimTypeReferenceId="displayName" PartnerClaimType="name" />
<OutputClaim ClaimTypeReferenceId="email" PartnerClaimType="email" />
<OutputClaim ClaimTypeReferenceId="identityProvider" DefaultValue="facebook.com" />
<OutputClaim ClaimTypeReferenceId="authenticationSource" DefaultValue="socialIdpAuthentication" />
</OutputClaims>
Metadata
Cryptographic keys
The CryptographicKeys element contains the following attribute:
Redirect URI
When you configure the redirect URL of your identity provider, enter
https://login.microsoftonline.com/te/tenant/policyId/oauth2/authresp . Make sure to replace tenant with your
tenant's name for example, contosob2c.onmicrosoft.com and policyId with the identifier of your policy (for
( )
example, b2c_1a_policy). The redirect URI needs to be in all lowercase.
If you are using the b2clogin.com domain instead of login.microsoftonline.com Make sure to use
b2clogin.com instead of login.microsoftonline.com.
Examples:
Add Google+ as an OAuth2 identity provider using custom policies
Define a one-time password technical profile in an
Azure AD B2C custom policy
12/12/2019 • 4 minutes to read • Edit Online
NOTE
In Azure Active Directory B2C, custom policies are designed primarily to address complex scenarios. For most scenarios, we
recommend that you use built-in user flows.
Azure Active Directory B2C (Azure AD B2C ) provides support for managing the generation and verification of a
one-time password. Use a technical profile to generate a code, and then verify that code later.
The one-time password technical profile can also return an error message during code verification. Design the
integration with the one-time password by using a Validation technical profile. A validation technical profile
calls the one-time password technical profile to verify a code. The validation technical profile validates the user-
provided data before the user journey continues. With the validation technical profile, an error message is
displayed on a self-asserted page.
Protocol
The Name attribute of the Protocol element needs to be set to Proprietary . The handler attribute must contain
the fully qualified name of the protocol handler assembly that is used by Azure AD B2C:
<TechnicalProfile Id="VerifyCode">
<DisplayName>Validate user input verification code</DisplayName>
<Protocol Name="Proprietary" Handler="Web.TPEngine.Providers.OneTimePasswordProtocolProvider, Web.TPEngine,
Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
...
Generate code
The first mode of this technical profile is to generate a code. Below are the options that can be configured for this
mode.
Input claims
The InputClaims element contains a list of claims required to send to the one-time password protocol provider.
You can also map the name of your claim to the name defined below.
The following settings can be used to configure code generation and maintenance:
<TechnicalProfile Id="GenerateCode">
<DisplayName>Generate Code</DisplayName>
<Protocol Name="Proprietary" Handler="Web.TPEngine.Providers.OneTimePasswordProtocolProvider,
Web.TPEngine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
<Metadata>
<Item Key="Operation">GenerateCode</Item>
<Item Key="CodeExpirationInSeconds">600</Item>
<Item Key="CodeLength">6</Item>
<Item Key="CharacterSet">0-9</Item>
<Item Key="NumRetryAttempts">5</Item>
<Item Key="ReuseSameCode">false</Item>
</Metadata>
<InputClaims>
<InputClaim ClaimTypeReferenceId="identifier" PartnerClaimType="identifier" />
</InputClaims>
<OutputClaims>
<OutputClaim ClaimTypeReferenceId="otpGenerated" PartnerClaimType="otpGenerated" />
</OutputClaims>
</TechnicalProfile>
Verify code
The second mode of this technical profile is to verify a code. Below are the options that can be configured for this
mode.
Input claims
The InputClaims element contains a list of claims required to send to the one-time password protocol provider.
You can also map the name of your claim to the name defined below.
Example
The following example TechnicalProfile is used for verifying a code:
<TechnicalProfile Id="VerifyCode">
<DisplayName>Verify Code</DisplayName>
<Protocol Name="Proprietary" Handler="Web.TPEngine.Providers.OneTimePasswordProtocolProvider,
Web.TPEngine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
<Metadata>
<Item Key="Operation">VerifyCode</Item>
<Item Key="UserMessageIfInvalidCode">Wrong code has been entered.</Item>
<Item Key="UserMessageIfSessionDoesNotExist">Code has expired.</Item>
<Item Key="UserMessageIfMaxRetryAttempted">You've tried too many times.</Item>
</Metadata>
<InputClaims>
<InputClaim ClaimTypeReferenceId="identifier" PartnerClaimType="identifier" />
<InputClaim ClaimTypeReferenceId="otpGenerated" PartnerClaimType="otpToVerify" />
</InputClaims>
</TechnicalProfile>
Define an OpenID Connect technical profile in an
Azure Active Directory B2C custom policy
12/9/2019 • 3 minutes to read • Edit Online
NOTE
In Azure Active Directory B2C, custom policies are designed primarily to address complex scenarios. For most scenarios, we
recommend that you use built-in user flows.
Azure Active Directory B2C (Azure AD B2C ) provides support for the OpenID Connect protocol identity provider.
OpenID Connect 1.0 defines an identity layer on top of OAuth 2.0 and represents the state of the art in modern
authentication protocols. With an OpenID Connect technical profile, you can federate with an OpenID Connect
based identity provider, such as Azure AD. Federating with an identity provider allows users to sign in with their
existing social or enterprise identities.
Protocol
The Name attribute of the Protocol element needs to be set to OpenIdConnect . For example, the protocol for the
MSA -OIDC technical profile is OpenIdConnect :
<TechnicalProfile Id="MSA-OIDC">
<DisplayName>Microsoft Account</DisplayName>
<Protocol Name="OpenIdConnect" />
...
Input claims
The InputClaims and InputClaimsTransformations elements are not required. But you may want to send
additional parameters to your identity provider. The following example adds the domain_hint query string
parameter with the value of contoso.com to the authorization request.
<InputClaims>
<InputClaim ClaimTypeReferenceId="domain_hint" DefaultValue="contoso.com" />
</InputClaims>
Output claims
The OutputClaims element contains a list of claims returned by the OpenID Connect identity provider. You may
need to map the name of the claim defined in your policy to the name defined in the identity provider. You can also
include claims that aren't returned by the identity provider, as long as you set the DefaultValue attribute.
The OutputClaimsTransformations element may contain a collection of OutputClaimsTransformation
elements that are used to modify the output claims or generate new ones.
The following example shows the claims returned by the Microsoft Account identity provider:
The sub claim that is mapped to the issuerUserId claim.
The name claim that is mapped to the displayName claim.
The email without name mapping.
The technical profile also returns claims that aren't returned by the identity provider:
The identityProvider claim that contains the name of the identity provider.
The authenticationSource claim with a default value of socialIdpAuthentication.
<OutputClaims>
<OutputClaim ClaimTypeReferenceId="identityProvider" DefaultValue="live.com" />
<OutputClaim ClaimTypeReferenceId="authenticationSource" DefaultValue="socialIdpAuthentication" />
<OutputClaim ClaimTypeReferenceId="issuerUserId" PartnerClaimType="sub" />
<OutputClaim ClaimTypeReferenceId="displayName" PartnerClaimType="name" />
<OutputClaim ClaimTypeReferenceId="email" />
</OutputClaims>
Metadata
Cryptographic keys
The CryptographicKeys element contains the following attribute:
Redirect Uri
When you configure the redirect URI of your identity provider, enter
https://{your-tenant-name}.b2clogin.com/{your-tenant-name}.onmicrosoft.com/oauth2/authresp . Make sure to replace
{your-tenant-name} with your tenant's name. The redirect URI needs to be in all lowercase.
Examples:
Add Microsoft Account (MSA) as an identity provider using custom policies
Sign in by using Azure AD accounts
Allow users to sign in to a multi-tenant Azure AD identity provider using custom policies
Define a RESTful technical profile in an Azure Active
Directory B2C custom policy
12/12/2019 • 8 minutes to read • Edit Online
NOTE
In Azure Active Directory B2C, custom policies are designed primarily to address complex scenarios. For most scenarios, we
recommend that you use built-in user flows.
Azure Active Directory B2C (Azure AD B2C ) provides support for your own RESTful service. Azure AD B2C
sends data to the RESTful service in an input claims collection and receives data back in an output claims
collection. With RESTful service integration, you can:
Validate user input data - Prevents malformed data from persisting into Azure AD B2C. If the value from
the user is not valid, your RESTful service returns an error message that instructs the user to provide an
entry. For example, you can verify that the email address provided by the user exists in your customer's
database.
Overwrite input claims - Enables you to reformat values in input claims. For example, if a user enters the
first name in all lowercase or all uppercase letters, you can format the name with only the first letter
capitalized.
Enrich user data - Enables you to further integrate with corporate line-of-business applications. For
example, your RESTful service can receive the user's email address, query the customer's database, and
return the user's loyalty number to Azure AD B2C. The return claims can be stored, evaluated in the next
Orchestration Steps, or included in the access token.
Run custom business logic - Enables you to send push notifications, update corporate databases, run a user
migration process, manage permissions, audit databases, and perform other actions.
Your policy may send input claims to your REST API. The REST API may also return output claims that you can
use later in your policy, or it can throw an error message. You can design the integration with the RESTful
services in the following ways:
Validation technical profile - A validation technical profile calls the RESTful service. The validation
technical profile validates the user-provided data before the user journey continues. With the validation
technical profile, an error message is display on a self-asserted page and returned in output claims.
Claims exchange - A call is made to the RESTful service through an orchestration step. In this scenario,
there is no user-interface to render the error message. If your REST API returns an error, the user is
redirected back to the relying party application with the error message.
Protocol
The Name attribute of the Protocol element needs to be set to Proprietary . The handler attribute must
contain the fully qualified name of the protocol handler assembly that is used by Azure AD B2C:
Web.TPEngine.Providers.RestfulProvider, Web.TPEngine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null .
The following example shows a RESTful technical profile:
<TechnicalProfile Id="REST-UserMembershipValidator">
<DisplayName>Validate user input data and return loyaltyNumber claim</DisplayName>
<Protocol Name="Proprietary" Handler="Web.TPEngine.Providers.RestfulProvider, Web.TPEngine,
Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
...
Input claims
The InputClaims element contains a list of claims to send to the REST API. You can also map the name of your
claim to the name defined in the REST API. Following example shows the mapping between your policy and the
REST API. The givenName claim is sent to the REST API as firstName, while surname is sent as lastName.
The email claim is set as is.
<InputClaims>
<InputClaim ClaimTypeReferenceId="email" />
<InputClaim ClaimTypeReferenceId="givenName" PartnerClaimType="firstName" />
<InputClaim ClaimTypeReferenceId="surname" PartnerClaimType="lastName" />
</InputClaims>
Output claims
The OutputClaims element contains a list of claims returned by the REST API. You may need to map the name
of the claim defined in your policy to the name defined in the REST API. You can also include claims that aren't
returned by the REST API identity provider, as long as you set the DefaultValue attribute.
The OutputClaimsTransformations element may contain a collection of OutputClaimsTransformation
elements that are used to modify the output claims or generate new ones.
The following example shows the claim returned by the REST API:
The MembershipId claim that is mapped to the loyaltyNumber claim name.
The technical profile also returns claims, that aren't returned by the identity provider:
The loyaltyNumberIsNew claim that has a default value set to true .
<OutputClaims>
<OutputClaim ClaimTypeReferenceId="loyaltyNumber" PartnerClaimType="MembershipId" />
<OutputClaim ClaimTypeReferenceId="loyaltyNumberIsNew" DefaultValue="true" />
</OutputClaims>
Metadata
<TechnicalProfile Id="REST-API-SignUp">
<DisplayName>Validate user's input data and return loyaltyNumber claim</DisplayName>
<Protocol Name="Proprietary" Handler="Web.TPEngine.Providers.RestfulProvider, Web.TPEngine,
Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
<Metadata>
<Item Key="ServiceUrl">https://your-app-name.azurewebsites.NET/api/identity/signup</Item>
<Item Key="AuthenticationType">None</Item>
<Item Key="SendClaimsIn">Body</Item>
</Metadata>
</TechnicalProfile>
If the type of authentication is set to Basic , the CryptographicKeys element contains the following attributes:
<TechnicalProfile Id="REST-API-SignUp">
<DisplayName>Validate user's input data and return loyaltyNumber claim</DisplayName>
<Protocol Name="Proprietary" Handler="Web.TPEngine.Providers.RestfulProvider, Web.TPEngine,
Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
<Metadata>
<Item Key="ServiceUrl">https://your-app-name.azurewebsites.NET/api/identity/signup</Item>
<Item Key="AuthenticationType">Basic</Item>
<Item Key="SendClaimsIn">Body</Item>
</Metadata>
<CryptographicKeys>
<Key Id="BasicAuthenticationUsername" StorageReferenceId="B2C_1A_B2cRestClientId" />
<Key Id="BasicAuthenticationPassword" StorageReferenceId="B2C_1A_B2cRestClientSecret" />
</CryptographicKeys>
</TechnicalProfile>
If the type of authentication is set to ClientCertificate , the CryptographicKeys element contains the following
attribute:
If the type of authentication is set to Bearer , the CryptographicKeys element contains the following attribute:
<TechnicalProfile Id="REST-API-SignUp">
<DisplayName>Validate user's input data and return loyaltyNumber claim</DisplayName>
<Protocol Name="Proprietary" Handler="Web.TPEngine.Providers.RestfulProvider, Web.TPEngine,
Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
<Metadata>
<Item Key="ServiceUrl">https://your-app-name.azurewebsites.NET/api/identity/signup</Item>
<Item Key="AuthenticationType">Bearer</Item>
<Item Key="SendClaimsIn">Body</Item>
</Metadata>
<CryptographicKeys>
<Key Id="BearerAuthenticationToken" StorageReferenceId="B2C_1A_B2cRestClientAccessToken" />
</CryptographicKeys>
</TechnicalProfile>
The following example shows a REST API that returns an error message formatted in JSON:
{
"version": "1.0.0",
"status": 409,
"code": "API12345",
"requestId": "50f0bd91-2ff4-4b8f-828f-00f170519ddb",
"userMessage": "Message for the user",
"developerMessage": "Verbose description of problem and how to fix it.",
"moreInfo": "https://restapi/error/API12345/moreinfo"
}
Next steps
See the following articles for examples of using a RESTful technical profile:
Integrate REST API claims exchanges in your Azure AD B2C user journey as validation of user input
Secure your RESTful services by using HTTP basic authentication
Secure your RESTful service by using client certificates
Walkthrough: Integrate REST API claims exchanges in your Azure AD B2C user journey as validation on user
input
Define a SAML technical profile in an Azure Active
Directory B2C custom policy
12/9/2019 • 10 minutes to read • Edit Online
NOTE
In Azure Active Directory B2C, custom policies are designed primarily to address complex scenarios. For most scenarios, we
recommend that you use built-in user flows.
Azure Active Directory B2C (Azure AD B2C ) provides support for the SAML 2.0 identity provider. This article describes
the specifics of a technical profile for interacting with a claims provider that supports this standardized protocol. With a
SAML technical profile you can federate with a SAML-based identity provider, such as ADFS and Salesforce. This
federation allows your users to sign in with their existing social or enterprise identities.
Metadata exchange
Metadata is information used in the SAML protocol to expose the configuration of a SAML party, such as a service
provider or identity provider. Metadata defines the location of the services, such as sign-in and sign-out, certificates,
sign-in method, and more. The identity provider uses the metadata to know how to communicate with Azure AD B2C.
The metadata is configured in XML format and may be signed with a digital signature so that the other party can
validate the integrity of the metadata. When Azure AD B2C federates with a SAML identity provider, it acts as a service
provider initiating a SAML request and waiting for a SAML response. And, in some cases, accepts unsolicited SAML
authentication, which is also known as identity provider initiated.
The metadata can be configured in both parties as "Static Metadata" or "Dynamic Metadata". In static mode, you copy
the entire metadata from one party and set it in the other party. In dynamic mode, you set the URL to the metadata
while the other party reads the configuration dynamically. The principles are the same, you set the metadata of the Azure
AD B2C technical profile in your identity provider and set the metadata of the identity provider in Azure AD B2C.
Each SAML identity provider has different steps to expose and set the service provider, in this case Azure AD B2C, and
set the Azure AD B2C metadata in the identity provider. Look at your identity provider’s documentation for guidance on
how to do so.
The following example shows a URL address to the SAML metadata of an Azure AD B2C technical profile:
https://your-tenant-name.b2clogin.com/your-tenant-name/your-policy/samlp/metadata?idptp=your-technical-profile
Digital encryption
To encrypt the SAML response assertion, the identity provider always uses a public key of an encryption certificate in an
Azure AD B2C technical profile. When Azure AD B2C needs to decrypt the data, it uses the private portion of the
encryption certificate.
To encrypt the SAML response assertion:
1. Upload a valid X509 certificate with the private key (.pfx file) to the Azure AD B2C policy key store.
2. Add a CryptographicKey element with an identifier of SamlAssertionDecryption to the technical profile
CryptographicKeys collection. Set the StorageReferenceId to the name of the policy key you created in step 1.
3. Set the technical profile metadata WantsEncryptedAssertions to true .
4. Update the identity provider with the new Azure AD B2C technical profile metadata. You should see the
KeyDescriptor with the use property set to encryption containing the public key of your certificate.
The following example shows the Azure AD B2C technical profile encryption section of the metadata:
<KeyDescriptor use="encryption">
<KeyInfo xmlns="https://www.w3.org/2000/09/xmldsig#">
<X509Data>
<X509Certificate>valid certificate</X509Certificate>
</X509Data>
</KeyInfo>
</KeyDescriptor>
Protocol
The Name attribute of the Protocol element needs to be set to SAML2 .
Output claims
The OutputClaims element contains a list of claims returned by the SAML identity provider under the
AttributeStatement section. You may need to map the name of the claim defined in your policy to the name defined in
the identity provider. You can also include claims that aren't returned by the identity provider as long as you set the
DefaultValue attribute.
To read the SAML assertion NamedId in Subject as a normalized claim, set the claim PartnerClaimType to
assertionSubjectName . Make sure the NameId is the first value in assertion XML. When you define more than one
assertion, Azure AD B2C picks the subject value from the last assertion.
The OutputClaimsTransformations element may contain a collection of OutputClaimsTransformation elements
that are used to modify the output claims or generate new ones.
The following example shows the claims returned by the Facebook identity provider:
The issuerUserId claim is mapped to the assertionSubjectName claim.
The first_name claim is mapped to the givenName claim.
The last_name claim is mapped to the surname claim.
The displayName claim without name mapping.
The email claim without name mapping.
The technical profile also returns claims that aren't returned by the identity provider:
The identityProvider claim that contains the name of the identity provider.
The authenticationSource claim with a default value of socialIdpAuthentication.
<OutputClaims>
<OutputClaim ClaimTypeReferenceId="issuerUserId" PartnerClaimType="assertionSubjectName" />
<OutputClaim ClaimTypeReferenceId="givenName" PartnerClaimType="first_name" />
<OutputClaim ClaimTypeReferenceId="surname" PartnerClaimType="last_name" />
<OutputClaim ClaimTypeReferenceId="displayName" PartnerClaimType="name" />
<OutputClaim ClaimTypeReferenceId="email" />
<OutputClaim ClaimTypeReferenceId="identityProvider" DefaultValue="contoso.com" />
<OutputClaim ClaimTypeReferenceId="authenticationSource" DefaultValue="socialIdpAuthentication" />
</OutputClaims>
Metadata
Cryptographic keys
The CryptographicKeys element contains the following attributes:
Next steps
See the following articles for examples of working with SAML identity providers in Azure AD B2C:
Add ADFS as a SAML identity provider using custom policies
Sign in by using Salesforce accounts via SAML
Define a self-asserted technical profile in an Azure
Active Directory B2C custom policy
12/12/2019 • 7 minutes to read • Edit Online
NOTE
In Azure Active Directory B2C, custom policies are designed primarily to address complex scenarios. For most scenarios,
we recommend that you use built-in user flows.
All interactions in Azure Active Directory B2C (Azure AD B2C ) where the user is expected to provide input are
self-asserted technical profiles. For example, a sign-up page, sign-in page, or password reset page.
Protocol
The Name attribute of the Protocol element needs to be set to Proprietary . The handler attribute must
contain the fully qualified name of the protocol handler assembly that is used by Azure AD B2C, for self-
asserted:
Web.TPEngine.Providers.SelfAssertedAttributeProvider, Web.TPEngine, Version=1.0.0.0, Culture=neutral,
PublicKeyToken=null
The following example shows a self-asserted technical profile for email sign-up:
<TechnicalProfile Id="LocalAccountSignUpWithLogonEmail">
<DisplayName>Email signup</DisplayName>
<Protocol Name="Proprietary" Handler="Web.TPEngine.Providers.SelfAssertedAttributeProvider, Web.TPEngine,
Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
Input claims
In a self-asserted technical profile, you can use the InputClaims and InputClaimsTransformations elements
to prepopulate the value of the claims that appear on the self-asserted page (display claims). For example, in the
edit profile policy, the user journey first reads the user profile from the Azure AD B2C directory service, then the
self-asserted technical profile sets the input claims with the user data stored in the user profile. These claims are
collected from the user profile and then presented to the user who can then edit the existing data.
<TechnicalProfile Id="SelfAsserted-ProfileUpdate">
...
<InputClaims>
<InputClaim ClaimTypeReferenceId="alternativeSecurityId" />
<InputClaim ClaimTypeReferenceId="userPrincipalName" />
<InputClaim ClaimTypeReferenceId="givenName" />
<InputClaim ClaimTypeReferenceId="surname" />
</InputClaims>
Display claims
The display claims feature is currently in preview.
The DisplayClaims element contains a list of claims to be presented on the screen for collecting data from the
user. To prepopulate the values of output claims, use the input claims that were previously described. The
element may also contain a default value.
The order of the claims in DisplayClaims specifies the order in which Azure AD B2C renders the claims on the
screen. To force the user to provide a value for a specific claim, set the Required attribute of the DisplayClaim
element to true .
The ClaimType element in the DisplayClaims collection needs to set the UserInputType element to any user
input type supported by Azure AD B2C. For example, TextBox or DropdownSingleSelect .
Add a reference to a DisplayControl
In the display claims collection, you can include a reference to a DisplayControl that you've created. A display
control is a user interface element that has special functionality and interacts with the Azure AD B2C back-end
service. It allows the user to perform actions on the page that invoke a validation technical profile at the back
end. For example, verifying an email address, phone number, or customer loyalty number.
The following example TechnicalProfile illustrates the use of display claims with display controls.
The first display claim makes a reference to the emailVerificationControl display control which collects and
verifies the email address.
The fifth display claim makes a reference to the phoneVerificationControl display control which collects and
verifies a phone number.
The other display claims are ClaimTypes to be collected from the user.
<TechnicalProfile Id="Id">
<DisplayClaims>
<DisplayClaim DisplayControlReferenceId="emailVerificationControl" />
<DisplayClaim ClaimTypeReferenceId="displayName" Required="true" />
<DisplayClaim ClaimTypeReferenceId="givenName" Required="true" />
<DisplayClaim ClaimTypeReferenceId="surName" Required="true" />
<DisplayClaim DisplayControlReferenceId="phoneVerificationControl" />
<DisplayClaim ClaimTypeReferenceId="newPassword" Required="true" />
<DisplayClaim ClaimTypeReferenceId="reenterPassword" Required="true" />
</DisplayClaims>
</TechnicalProfile>
As mentioned, a display claim with a reference to a display control may run its own validation, for example
verifying the email address. In addition, the self-asserted page supports using a validation technical profile to
validate the entire page, including any user input (claim types or display controls), before moving on to the next
orchestration step.
Combine usage of display claims and output claims carefully
If you specify one or more DisplayClaim elements in a self-asserted technical profile, you must use a
DisplayClaim for every claim that you want to display on-screen and collect from the user. No output claims are
displayed by a self-asserted technical profile that contains at least one display claim.
Consider the following example in which an age claim is defined as an output claim in a base policy. Before
adding any display claims to the self-asserted technical profile, the age claim is displayed on the screen for data
collection from the user:
<TechnicalProfile Id="id">
<OutputClaims>
<OutputClaim ClaimTypeReferenceId="age" />
</OutputClaims>
</TechnicalProfile>
If a leaf policy that inherits that base subsequently specifies officeNumber as a display claim:
<TechnicalProfile Id="id">
<DisplayClaims>
<DisplayClaim ClaimTypeReferenceId="officeNumber" />
</DisplayClaims>
<OutputClaims>
<OutputClaim ClaimTypeReferenceId="officeNumber" />
</OutputClaims>
</TechnicalProfile>
The age claim in the base policy is no longer presented on the screen to the user - it's effectively "hidden." To
display the age claim and collect the age value from the user, you must add an age DisplayClaim.
Output claims
The OutputClaims element contains a list of claims to be returned to the next orchestration step. The
DefaultValue attribute takes effect only if the claim has never been set. If it was set in a previous orchestration
step, the default value does not take effect even if the user leaves the value empty. To force the use of a default
value, set the AlwaysUseDefaultValue attribute to true .
NOTE
In previous versions of the Identity Experience Framework (IEF), output claims were used to collect data from the user. To
collect data from the user, use a DisplayClaims collection instead.
Persist claims
If the PersistedClaims element is absent, the self-asserted technical profile doesn't persist the data to Azure AD
B2C. Instead, a call is made to a validation technical profile that's responsible for persisting the data. For
example, the sign-up policy uses the LocalAccountSignUpWithLogonEmail self-asserted technical profile to collect
the new user profile. The LocalAccountSignUpWithLogonEmail technical profile calls the validation technical profile
to create the account in Azure AD B2C.
Metadata
ATTRIBUTE REQUIRED DESCRIPTION
Cryptographic keys
The CryptographicKeys element is not used.
Single sign-on session management in Azure Active
Directory B2C
12/9/2019 • 3 minutes to read • Edit Online
NOTE
In Azure Active Directory B2C, custom policies are designed primarily to address complex scenarios. For most scenarios, we
recommend that you use built-in user flows.
Single sign-on (SSO ) session management in Azure Active Directory B2C (Azure AD B2C ) enables an
administrator to control interaction with a user after the user has already authenticated. For example, the
administrator can control whether the selection of identity providers is displayed, or whether local account details
need to be entered again. This article describes how to configure the SSO settings for Azure AD B2C.
SSO session management has two parts. The first deals with the user's interactions directly with Azure AD B2C
and the other deals with the user's interactions with external parties such as Facebook. Azure AD B2C does not
override or bypass SSO sessions that might be held by external parties. Rather the route through Azure AD B2C
to get to the external party is “remembered”, avoiding the need to reprompt the user to select their social or
enterprise identity provider. The ultimate SSO decision remains with the external party.
SSO session management uses the same semantics as any other technical profile in custom policies. When an
orchestration step is executed, the technical profile associated with the step is queried for a
UseTechnicalProfileForSessionManagement reference. If one exists, the referenced SSO session provider is then
checked to see if the user is a session participant. If so, the SSO session provider is used to repopulate the session.
Similarly, when the execution of an orchestration step is complete, the provider is used to store information in the
session if an SSO session provider has been specified.
Azure AD B2C has defined a number of SSO session providers that can be used:
NoopSSOSessionProvider
DefaultSSOSessionProvider
ExternalLoginSSOSessionProvider
SamlSSOSessionProvider
SSO management classes are specified using the <UseTechnicalProfileForSessionManagement ReferenceId=“{ID}" />
element of a technical profile.
NoopSSOSessionProvider
As the name dictates, this provider does nothing. This provider can be used for suppressing SSO behavior for a
specific technical profile.
DefaultSSOSessionProvider
This provider can be used for storing claims in a session. This provider is typically referenced in a technical profile
used for managing local accounts. When using the DefaultSSOSessionProvider to store claims in a session, you
need to ensure that any claims that need to be returned to the application or used by pre-conditions in subsequent
steps, are stored in the session or augmented by a read from the users profile in directory. This will ensure that
your authentication journey’s will not fail on missing claims.
<TechnicalProfile Id="SM-AAD">
<DisplayName>Session Mananagement Provider</DisplayName>
<Protocol Name="Proprietary" Handler="Web.TPEngine.SSO.DefaultSSOSessionProvider, Web.TPEngine,
Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
<PersistedClaims>
<PersistedClaim ClaimTypeReferenceId="objectId" />
<PersistedClaim ClaimTypeReferenceId="newUser" />
<PersistedClaim ClaimTypeReferenceId="executed-SelfAsserted-Input" />
</PersistedClaims>
<OutputClaims>
<OutputClaim ClaimTypeReferenceId="objectIdFromSession" DefaultValue="true" />
</OutputClaims>
</TechnicalProfile>
To add claims in the session, use the <PersistedClaims> element of the technical profile. When the provider is used
to repopulate the session, the persisted claims are added to the claims bag. <OutputClaims> is used for retrieving
claims from the session.
ExternalLoginSSOSessionProvider
This provider is used to suppress the “choose identity provider” screen. It is typically referenced in a technical
profile configured for an external identity provider, such as Facebook.
<TechnicalProfile Id="SM-SocialLogin">
<DisplayName>Session Mananagement Provider</DisplayName>
<Protocol Name="Proprietary" Handler="Web.TPEngine.SSO.ExternalLoginSSOSessionProvider, Web.TPEngine,
Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
</TechnicalProfile>
SamlSSOSessionProvider
This provider is used for managing the Azure AD B2C SAML sessions between apps as well as external SAML
identity providers.
<TechnicalProfile Id="SM-Reflector-SAML">
<DisplayName>Session Management Provider</DisplayName>
<Protocol Name="Proprietary" Handler="Web.TPEngine.SSO.SamlSSOSessionProvider, Web.TPEngine, Version=1.0.0.0,
Culture=neutral, PublicKeyToken=null" />
<Metadata>
<Item Key="IncludeSessionIndex">false</Item>
<Item Key="RegisterServiceProviders">false</Item>
</Metadata>
</TechnicalProfile>
NOTE
In Azure Active Directory B2C, custom policies are designed primarily to address complex scenarios. For most scenarios, we
recommend that you use built-in user flows.
A validation technical profile is an ordinary technical profile from any protocol, such as Azure Active Directory or
a REST API. The validation technical profile returns output claims or returns an HTTP 409 error message
(Conflict response status code), with the following data:
{
"version": "1.0.0",
"status": 409,
"userMessage": "Your error message"
}
Claims that are returned from a validation technical profile are added back to the claims bag. You can use those
claims in the next validation technical profiles.
Validation technical profiles are executed in the sequence that they appear in the ValidationTechnicalProfiles
element. You can configure in a validation technical profile whether the execution of any subsequent validation
technical profiles should continue if the validation technical profile raises an error or is successful.
A validation technical profile can be conditionally executed based on preconditions defined in the
ValidationTechnicalProfile element. For example, you can check whether a specific claims exists, or if a claim is
equal or not to the specified value.
A self-asserted technical profile may define a validation technical profile to be used for validating some or all of
its output claims. All of the input claims of the referenced technical profile must appear in the output claims of
the referencing validation technical profile.
NOTE
Only self-asserted technical profiles can use validation technical profiles. If you need to validate the output claims from
non-self-asserted technical profiles, consider using an additional orchestration step in your user journey to accommodate
the technical profile in charge of the validation.
ValidationTechnicalProfiles
The ValidationTechnicalProfiles element contains the following elements:
Example
Following example uses these validation technical profiles:
1. The first validation technical profile checks user credentials and doesn't continue if an error occurs, such as
invalid username or bad password.
2. The next validation technical profile, doesn't execute if the userType claim does not exist, or if the value of the
userType is Partner . The validation technical profile tries to read the user profile from the internal customer
database and continue if an error occurs, such as REST API service not available, or any internal error.
3. The last validation technical profile, doesn't execute if the userType claim has not existed, or if the value of the
userType is Customer . The validation technical profile tries to read the user profile from the internal partner
database and continues if an error occurs, such as REST API service not available, or any internal error.
<ValidationTechnicalProfiles>
<ValidationTechnicalProfile ReferenceId="login-NonInteractive" ContinueOnError="false" />
<ValidationTechnicalProfile ReferenceId="REST-ReadProfileFromCustomertsDatabase" ContinueOnError="true" >
<Preconditions>
<Precondition Type="ClaimsExist" ExecuteActionsIf="false">
<Value>userType</Value>
<Action>SkipThisValidationTechnicalProfile</Action>
</Precondition>
<Precondition Type="ClaimEquals" ExecuteActionsIf="true">
<Value>userType</Value>
<Value>Partner</Value>
<Action>SkipThisValidationTechnicalProfile</Action>
</Precondition>
</Preconditions>
</ValidationTechnicalProfile>
<ValidationTechnicalProfile ReferenceId="REST-ReadProfileFromPartnersDatabase" ContinueOnError="true" >
<Preconditions>
<Precondition Type="ClaimsExist" ExecuteActionsIf="false">
<Value>userType</Value>
<Action>SkipThisValidationTechnicalProfile</Action>
</Precondition>
<Precondition Type="ClaimEquals" ExecuteActionsIf="true">
<Value>userType</Value>
<Value>Customer</Value>
<Action>SkipThisValidationTechnicalProfile</Action>
</Precondition>
</Preconditions>
</ValidationTechnicalProfile>
</ValidationTechnicalProfiles>
Display controls
12/12/2019 • 3 minutes to read • Edit Online
NOTE
In Azure Active Directory B2C, custom policies are designed primarily to address complex scenarios. For most scenarios, we
recommend that you use built-in user flows.
A display control is a user interface element that has special functionality and interacts with the Azure Active
Directory B2C (Azure AD B2C ) back-end service. It allows the user to perform actions on the page that invoke a
validation technical profile at the back end. Display controls are displayed on the page and are referenced by a
self-asserted technical profile.
The following image illustrates a self-asserted sign-up page with two display controls that validate a primary and
secondary email address.
NOTE
This feature is in public preview.
Prerequisites
In the Metadata section of a self-asserted technical profile, the referenced ContentDefinition needs to have
DataUri set to page contract version 2.0.0 or higher. For example:
<ContentDefinition Id="api.selfasserted">
<LoadUri>~/tenant/default/selfAsserted.cshtml</LoadUri>
<RecoveryUri>~/common/default_page_error.html</RecoveryUri>
<DataUri>urn:com:microsoft:aad:b2c:elements:selfasserted:2.0.0</DataUri>
...
Input claims
In a display control, you can use InputClaims elements to prepopulate the value of claims to collect from the
user on the page. Any InputClaimsTransformations can be defined in the self-asserted technical profile which
references this display control.
The following example prepopulates the email address to be verified with the address already present.
Display claims
Each type of display control requires a different set of display claims, output claims, and actions to be performed.
Similar to the display claims defined in a self-asserted technical profile, the display claims represent the claims
to be collected from the user within the display control. The ClaimType element referenced needs to specify the
UserInputType element for a user input type supported by Azure AD B2C, such as TextBox or
DropdownSingleSelect . If a display claim value is required by an Action, set the Required attribute to true to
force the user to provide a value for that specific display claim.
Certain display claims are required for certain types of display control. For example, VerificationCode is
required for the display control of type VerificationControl. Use the attribute ControlClaimType to specify
which DisplayClaim is designated for that required claim. For example:
Output claims
The output claims of a display control are not sent to the next orchestration step. They are saved temporarily
only for the current display control session. These temporary claims can be shared between the different actions
of the same display control.
To bubble up the output the claims to the next orchestration step, use the OutputClaims of the actual self-
asserted technical profile which references this display control.
Display control Actions
The Actions of a display control are procedures that occur in the Azure AD B2C back end when a user performs
a certain action on the client side (the browser). For example, the validations to perform when the user selects a
button on the page.
An action defines a list of validation technical profiles. They are used for validating some or all of the display
claims of the display control. The validation technical profile validates the user input and may return an error to
the user. You can use ContinueOnError, ContinueOnSuccess, and Preconditions in the display control Action
similar to the way they're used in validation technical profiles in a self asserted technical profile.
The following example sends a code either in email or SMS based on the user's selection of the mfaType claim.
<Action Id="SendCode">
<ValidationClaimsExchange>
<ValidationClaimsExchangeTechnicalProfile TechnicalProfileReferenceId="AzureMfa-SendSms">
<Preconditions>
<Precondition Type="ClaimEquals" ExecuteActionsIf="true">
<Value>mfaType</Value>
<Value>email</Value>
<Action>SkipThisValidationTechnicalProfile</Action>
</Precondition>
</Preconditions>
</ValidationClaimsExchangeTechnicalProfile>
<ValidationClaimsExchangeTechnicalProfile TechnicalProfileReferenceId="AadSspr-SendEmail">
<Preconditions>
<Precondition Type="ClaimEquals" ExecuteActionsIf="true">
<Value>mfaType</Value>
<Value>phone</Value>
<Action>SkipThisValidationTechnicalProfile</Action>
</Precondition>
</Preconditions>
</ValidationClaimsExchangeTechnicalProfile>
</ValidationClaimsExchange>
</Action>
<TechnicalProfile Id="SelfAsserted-ProfileUpdate">
...
<DisplayClaims>
<DisplayClaim DisplayControlReferenceId="emailVerificationControl" />
<DisplayClaim DisplayControlReferenceId="PhoneVerificationControl" />
<DisplayClaim ClaimTypeReferenceId="displayName" Required="true" />
<DisplayClaim ClaimTypeReferenceId="givenName" Required="true" />
<DisplayClaim ClaimTypeReferenceId="surName" Required="true" />
Verification display control
12/12/2019 • 2 minutes to read • Edit Online
Use a verification display control to verify a claim, for example an email address or phone number, with a
verification code sent to the user.
VerificationControl actions
The verification display control consists of two steps (actions):
1. Request a destination from the user, such as an email address or phone number, to which the verification
code should be sent. When the user selects the Send Code button, the SendCode Action of the
verification display control is executed. The SendCode Action generates a code, constructs the content to
be sent, and sends it to the user. The value of the address can be pre-populated and serve as a second-factor
authentication.
2. After the code has been sent, the user reads the message, enters the verification code into the control
provided by the display control, and selects Verify Code. By selecting Verify Code, the VerifyCode
Action is executed to verify the code associated with the address. If the user selects Send New Code, the
first action is executed again.
NOTE
This feature is in public preview.
NOTE
In Azure Active Directory B2C, custom policies are designed primarily to address complex scenarios. For most scenarios, we
recommend that you use built-in user flows.
User journeys specify explicit paths through which a policy allows a relying party application to obtain the desired
claims for a user. The user is taken through these paths to retrieve the claims that are to be presented to the
relying party. In other words, user journeys define the business logic of what an end user goes through as the
Azure AD B2C Identity Experience Framework processes the request.
These user journeys can be considered as templates available to satisfy the core need of the various relying parties
of the community of interest. User journeys facilitate the definition of the relying party part of a policy. A policy
can define multiple user journeys. Each user journey is a sequence of orchestration steps.
To define the user journeys supported by the policy, a UserJourneys element is added under the top-level
element of the policy file.
The UserJourneys element contains the following element:
OrchestrationSteps
A user journey is represented as an orchestration sequence that must be followed through for a successful
transaction. If any step fails, the transaction fails. These orchestration steps reference both the building blocks and
the claims providers allowed in the policy file. Any orchestration step that is responsible to show or render a user
experience also has a reference to the corresponding content definition identifier.
Orchestration steps can be conditionally executed based on preconditions defined in the orchestration step
element. For example, you can check to perform an orchestration step only if a specific claims exists, or if a claim is
equal or not to the specified value.
To specify the ordered list of orchestration steps, an OrchestrationSteps element is added as part of the policy.
This element is required.
The OrchestrationSteps element contains the following element:
Preconditions
The Preconditions element contains the following element:
Precondition
The Precondition element contains the following attributes:
Preconditions examples
The following preconditions checks whether the user's objectId exists. In the user journey, the user has selected to
sign in using local account. If the objectId exists, skip this orchestration step.
The following preconditions checks whether the user signed in with a social account. An attempt is made to find
the user account in the directory. If the user signs in or signs up with a local account, skip this orchestration step.
<OrchestrationStep Order="3" Type="ClaimsExchange">
<Preconditions>
<Precondition Type="ClaimEquals" ExecuteActionsIf="true">
<Value>authenticationSource</Value>
<Value>localAccountAuthentication</Value>
<Action>SkipThisOrchestrationStep</Action>
</Precondition>
</Preconditions>
<ClaimsExchanges>
<ClaimsExchange Id="AADUserReadUsingAlternativeSecurityId" TechnicalProfileReferenceId="AAD-
UserReadUsingAlternativeSecurityId-NoError" />
</ClaimsExchanges>
</OrchestrationStep>
Preconditions can check multiple preconditions. The following example checks whether 'objectId' or 'email' exists.
If the first condition is true, the journey skips to the next orchestration step.
ClaimsProviderSelection
An orchestration step of type ClaimsProviderSelection or CombinedSignInAndSignUp may contain a list of claims
providers that a user can sign in with. The order of the elements inside the ClaimsProviderSelections elements
controls the order of the identity providers presented to the user.
The ClaimsProviderSelection element contains the following element:
ClaimsProviderSelection example
In the following orchestration step, the user can choose to sign in with Facebook, LinkedIn, Twitter, Google, or a
local account. If the user selects one of the social identity providers, the second orchestration step executes with
the selected claim exchange specified in the TargetClaimsExchangeId attribute. The second orchestration step
redirects the user to the social identity provider to complete the sign-in process. If the user chooses to sign in with
the local account, Azure AD B2C stays on the same orchestration step (the same sign-up page or sign-in page)
and skips the second orchestration step.
ClaimsExchanges
The ClaimsExchanges element contains the following element:
NOTE
In Azure Active Directory B2C, custom policies are designed primarily to address complex scenarios. For most scenarios, we recommend
that you use built-in user flows.
The RelyingParty element specifies the user journey to enforce for the current request to Azure Active Directory B2C (Azure
AD B2C ). It also specifies the list of claims that the relying party (RP ) application needs as part of the issued token. An RP
application, such as a web, mobile, or desktop application, calls the RP policy file. The RP policy file executes a specific task,
such as signing in, resetting a password, or editing a profile. Multiple applications can use the same RP policy and a single
application can use multiple policies. All RP applications receive the same token with claims, and the user goes through the
same user journey.
The following example shows a RelyingParty element in the B2C_1A_signup_signin policy file:
<BasePolicy>
<TenantId>your-tenant.onmicrosoft.com</TenantId>
<PolicyId>B2C_1A_TrustFrameworkExtensions</PolicyId>
</BasePolicy>
<RelyingParty>
<DefaultUserJourney ReferenceId="SignUpOrSignIn" />
<UserJourneyBehaviors>
<SingleSignOn Scope="TrustFramework" KeepAliveInDays="7"/>
<SessionExpiryType>Rolling</SessionExpiryType>
<SessionExpiryInSeconds>300</SessionExpiryInSeconds>
<JourneyInsights TelemetryEngine="ApplicationInsights" InstrumentationKey="your-application-insights-key"
DeveloperMode="true" ClientEnabled="false" ServerEnabled="true" TelemetryVersion="1.0.0" />
<ContentDefinitionParameters>
<Parameter Name="campaignId">{OAUTH-KV:campaignId}</Parameter>
</ContentDefinitionParameters>
</UserJourneyBehaviors>
<TechnicalProfile Id="PolicyProfile">
<DisplayName>PolicyProfile</DisplayName>
<Description>The policy profile</Description>
<Protocol Name="OpenIdConnect" />
<Metadata>collection of key/value pairs of data</Metadata>
<OutputClaims>
<OutputClaim ClaimTypeReferenceId="displayName" />
<OutputClaim ClaimTypeReferenceId="givenName" />
<OutputClaim ClaimTypeReferenceId="surname" />
<OutputClaim ClaimTypeReferenceId="email" />
<OutputClaim ClaimTypeReferenceId="objectId" PartnerClaimType="sub"/>
<OutputClaim ClaimTypeReferenceId="identityProvider" />
<OutputClaim ClaimTypeReferenceId="loyaltyNumber" />
</OutputClaims>
<SubjectNamingInfo ClaimType="sub" />
</TechnicalProfile>
</RelyingParty>
...
DefaultUserJourney
The DefaultUserJourney element specifies a reference to the identifier of the user journey that is usually defined in the Base or
Extensions policy. The following examples show the sign-up or sign-in user journey specified in the RelyingParty element:
B2C_1A_signup_signin policy:
<RelyingParty>
<DefaultUserJourney ReferenceId="SignUpOrSignIn">
...
B2C_1A_TrustFrameWorkBase or B2C_1A_TrustFrameworkExtensionPolicy:
<UserJourneys>
<UserJourney Id="SignUpOrSignIn">
...
UserJourneyBehaviors
The UserJourneyBehaviors element contains the following elements:
SingleSignOn
The SingleSignOn element contains in the following attribute:
JourneyInsights
The JourneyInsights element contains the following attributes:
ContentDefinitionParameters
By using custom policies in Azure AD B2C, you can send a parameter in a query string. By passing the parameter to your
HTML endpoint, you can dynamically change the page content. For example, you can change the background image on the
Azure AD B2C sign-up or sign-in page, based on a parameter that you pass from your web or mobile application. Azure AD
B2C passes the query string parameters to your dynamic HTML file, such as aspx file.
The following example passes a parameter named campaignId with a value of hawaii in the query string:
https://login.microsoft.com/contoso.onmicrosoft.com/oauth2/v2.0/authorize?pB2C_1A_signup_signin&client_id=a415078a-0402-4ce3-a9c6-
ec1947fcfb3f&nonce=defaultNonce&redirect_uri=http%3A%2F%2Fjwt.io%2F&scope=openid&response_type=id_token&prompt=login&campaignId=hawaii
For more information, see Configure the UI with dynamic content by using custom policies
TechnicalProfile
The TechnicalProfile element contains the following attribute:
ATTRIBUTE REQUIRED DESCRIPTION
OutputClaims
The OutputClaims element contains the following element:
SubjectNamingInfo
With the SubjectNameingInfo element, you control the value of the token subject:
JWT token - the sub claim. This is a principal about which the token asserts information, such as the user of an
application. This value is immutable and cannot be reassigned or reused. It can be used to perform safe authorization
checks, such as when the token is used to access a resource. By default, the subject claim is populated with the object ID of
the user in the directory. For more information, see Token, session and single sign-on configuration.
SAML token - the <Subject><NameID> element which identifies the subject element.
The SubjectNamingInfo element contains the following attribute:
The following example shows how to define an OpenID Connect relying party. The subject name info is configured as the
objectId :
<RelyingParty>
<DefaultUserJourney ReferenceId="SignUpOrSignIn" />
<TechnicalProfile Id="PolicyProfile">
<DisplayName>PolicyProfile</DisplayName>
<Protocol Name="OpenIdConnect" />
<OutputClaims>
<OutputClaim ClaimTypeReferenceId="displayName" />
<OutputClaim ClaimTypeReferenceId="givenName" />
<OutputClaim ClaimTypeReferenceId="surname" />
<OutputClaim ClaimTypeReferenceId="email" />
<OutputClaim ClaimTypeReferenceId="objectId" PartnerClaimType="sub"/>
<OutputClaim ClaimTypeReferenceId="identityProvider" />
</OutputClaims>
<SubjectNamingInfo ClaimType="sub" />
</TechnicalProfile>
</RelyingParty>
The JWT token includes the sub claim with the user objectId:
{
...
"sub": "6fbbd70d-262b-4b50-804c-257ae1706ef2",
...
}
Set redirect URLs to b2clogin.com for Azure Active
Directory B2C
12/11/2019 • 3 minutes to read • Edit Online
When you set up an identity provider for sign-up and sign-in in your Azure Active Directory B2C (Azure AD
B2C ) application, you need to specify a redirect URL. You should no longer reference login.microsoftonline.com
in your applications and APIs. Instead, use b2clogin.com for all new applications, and migrate existing
applications from login.microsoftonline.com to b2clogin.com.
Deprecation of login.microsoftonline.com
On 04 December 2019, we announced the scheduled retirement of login.microsoftonline.com support in Azure
AD B2C on 04 December 2020:
Azure Active Directory B2C is deprecating login.microsoftonline.com
The deprecation of login.microsoftonline.com goes into effect for all Azure AD B2C tenants on 04 December
2020, providing existing tenants one (1) year to migrate to b2clogin.com. New tenants created after 04
December 2019 will not accept requests from login.microsoftonline.com. All functionality remains the same on
the b2clogin.com endpoint.
The deprecation of login.microsoftonline.com does not impact Azure Active Directory tenants. Only Azure Active
Directory B2C tenants are affected by this change.
Benefits of b2clogin.com
When you use b2clogin.com as your redirect URL:
Space consumed in the cookie header by Microsoft services is reduced.
Your redirect URLs no longer need to include a reference to Microsoft.
JavaScript client-side code is supported (currently in preview ) in customized pages. Due to security
restrictions, JavaScript code and HTML form elements are removed from custom pages if you use
login.microsoftonline.com.
There are two formats you can use for your b2clogin.com redirect URLs. The first provides the benefit of not
having "Microsoft" appear anywhere in the URL by using the Tenant ID (a GUID ) in place of your tenant domain
name:
https://{your-tenant-name}.b2clogin.com/{your-tenant-id}/oauth2/authresp
The second option uses your tenant domain name in the form of your-tenant-name.onmicrosoft.com . For
example:
https://{your-tenant-name}.b2clogin.com/{your-tenant-name}.onmicrosoft.com/oauth2/authresp
https://contosob2c.b2clogin.com/00000000-0000-0000-0000-000000000000/B2C_1_signupsignin1
For information about migrating OWIN -based web applications to b2clogin.com, see Migrate an OWIN -based
web API to b2clogin.com.
For migrating Azure API Management APIs protected by Azure AD B2C, see the Migrate to b2clogin.com
section of Secure an Azure API Management API with Azure AD B2C.
This article describes a technique for enabling support for multiple token issuers in web APIs that implement the
Open Web Interface for .NET (OWIN ). Supporting multiple token endpoints is useful when you're migrating Azure
Active Directory B2C (Azure AD B2C ) APIs and their applications from login.microsoftonline.com to b2clogin.com.
By adding support in your API for accepting tokens issued by both b2clogin.com and login.microsoftonline.com,
you can migrate your web applications in a staged manner before removing support for
login.microsoftonline.com-issued tokens from the API.
The following sections present an example of how to enable multiple issuers in a web API that uses the Microsoft
OWIN middleware components (Katana). Although the code examples are specific to the Microsoft OWIN
middleware, the general technique should be applicable to other OWIN libraries.
NOTE
This article is intended for Azure AD B2C customers with currently deployed APIs and applications that reference
login.microsoftonline.com and who want to migrate to the recommended b2clogin.com endpoint. If you're setting up
a new application, use b2clogin.com as directed.
Prerequisites
You need the following Azure AD B2C resources in place before continuing with the steps in this article:
User flows or custom policies created in your tenant
5. In the page that opens in your browser, record the issuer value, for example:
https://your-b2c-tenant.b2clogin.com/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/v2.0/
6. Use the Select domain drop-down to select the other domain, then perform the previous two steps once
again and record its issuer value.
You should now have two URIs recorded that are similar to:
https://login.microsoftonline.com/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/v2.0/
https://your-b2c-tenant.b2clogin.com/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/v2.0/
Custom policies
If you have custom policies instead of user flows, you can use a similar process to get the issuer URIs.
1. Navigate to your Azure AD B2C tenant
2. Select Identity Experience Framework
3. Select one of your relying party policies, for example, B2C_1A_signup_signin
4. Use the Select domain drop-down to select a domain, for example yourtenant.b2clogin.com
5. Select the hyperlink displayed under OpenID Connect discovery endpoint
6. Record the issuer value
7. Perform the steps 4-6 for the other domain, for example login.microsoftonline.com
4. Add the ValidIssuers property to the TokenValidationParameters definition and specify both URIs you
recorded in the previous section:
TokenValidationParameters tvps = new TokenValidationParameters
{
// Accept only those tokens where the audience of the token is equal to the client ID of this app
ValidAudience = ClientId,
AuthenticationType = Startup.DefaultPolicy,
ValidIssuers = new List<string> {
"https://login.microsoftonline.com/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/v2.0/",
"https://{your-b2c-tenant}.b2clogin.com/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/v2.0/"
}
};
TokenValidationParameters is provided by MSAL.NET and is consumed by the OWIN middleware in the next
section of code in Startup.Auth.cs. With multiple valid issuers specified, the OWIN application pipeline is made
aware that both token endpoints are valid issuers.
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions
{
// This SecurityTokenProvider fetches the Azure AD B2C metadata & from the OpenID Connect metadata
endpoint
AccessTokenFormat = new JwtFormat(tvps, new tCachingSecurityTokenProvider(String.Format(AadInstance,
ultPolicy)))
});
As mentioned previously, other OWIN libraries typically provide a similar facility for supporting multiple issuers.
Although providing examples for every library is outside the scope of this article, you can use a similar technique
for most libraries.
Before:
When the endpoint strings are constructed during execution of the web app, the b2clogin.com-based endpoints
are used when it requests tokens.
Next steps
This article presented a method of configuring a web API implementing the Microsoft OWIN middleware (Katana)
to accept tokens from multiple issuer endpoints. As you might notice, there are several other strings in the
Web.Config files of both the TaskService and TaskWebApp projects that would need to be changed if you want to
build and run these projects against your own tenant. You're welcome to modify the projects appropriately if you
want to see them in action, however, a full walk-through of doing so is outside the scope of this article.
For more information about the different types of security tokens emitted by Azure AD B2C, see Overview of
tokens in Azure Active Directory B2C.
Accessing usage reports in Azure AD B2C via the
reporting API
12/9/2019 • 4 minutes to read • Edit Online
Azure Active Directory B2C (Azure AD B2C ) provides authentication based on user sign-in and Azure Multi-Factor
Authentication. Authentication is provided for end users of your application family across identity providers. When
you know the number of users registered in the tenant, the providers they used to register, and the number of
authentications by type, you can answer questions like:
How many users from each type of identity provider (for example, a Microsoft or LinkedIn account) have
registered in the last 10 days?
How many authentications using Multi-Factor Authentication have completed successfully in the last month?
How many sign-in-based authentications were completed this month? Per day? Per application?
How can I estimate the expected monthly cost of my Azure AD B2C tenant activity?
This article focuses on reports tied to billing activity, which is based on the number of users, billable sign-in-based
authentications, and multi-factor authentications.
Prerequisites
Before you get started, you need to complete the steps in Prerequisites to access the Azure AD reporting APIs.
Create an application, obtain a secret for it, and grant it access rights to your Azure AD B2C tenant’s reports. Bash
script and Python script examples are also provided here.
PowerShell script
This script demonstrates the creation of four usage reports by using the TimeStamp parameter and the
ApplicationId filter.
# This script will require the Web Application and permissions setup in Azure Active Directory
# Constants
$ClientID = "your-client-application-id-here"
$ClientSecret = "your-client-application-secret-here"
$loginURL = "https://login.microsoftonline.com"
$tenantdomain = "your-b2c-tenant-domain.onmicrosoft.com"
# Get an Oauth 2 access token based on client id, secret and tenant domain
$body =
@{grant_type="client_credentials";resource=$resource;client_id=$ClientID;client_secret=$ClientSecret}
$oauth = Invoke-RestMethod -Method Post -Uri $loginURL/$tenantdomain/oauth2/token?api-version=1.0 -Body
$body
if ($oauth.access_token -ne $null) {
$headerParams = @{'Authorization'="$($oauth.token_type) $($oauth.access_token)"}
} else {
Write-Host "ERROR: No Access Token"
}
Limitations
User count data is refreshed every 24 to 48 hours. Authentications are updated several times a day. When using
the ApplicationId filter, an empty report response can be due to one of following conditions:
The application ID does not exist in the tenant. Make sure it is correct.
The application ID exists, but no data was found in the reporting period. Review your date/time parameters.
Next steps
Monthly bill estimates for Azure AD
When combined with the most current Azure AD B2C pricing available, you can estimate daily, weekly, and
monthly Azure consumption. An estimate is especially useful when you plan for changes in tenant behavior that
might impact overall cost. You can review actual costs in your linked Azure subscription.
Options for other output formats
The following code shows examples of sending output to JSON, a name value list, and XML:
Azure Active Directory B2C (Azure AD B2C ) tenants can have thousands or millions of users. This means that
many common tenant management tasks need to be performed programmatically. A primary example is user
management.
You might need to migrate an existing user store to a B2C tenant. You may want to host user registration on your
own page and create user accounts in your Azure AD B2C directory behind the scenes. These kinds of tasks
require the ability to create, read, update, and delete user accounts. You can perform such tasks by using the Azure
AD Graph API.
For B2C tenants, there are two primary modes of communicating with the Graph API:
For interactive, run-once tasks, you should act as an administrator account in the B2C tenant when you
perform the tasks. This mode requires an administrator to sign in with credentials before that admin can
perform any calls to the Graph API.
For automated, continuous tasks, you should use some type of service account that you provide with the
necessary privileges to perform management tasks. In Azure AD, you can do this by registering an application
and authenticating to Azure AD. This is done by using an Application ID that uses the OAuth 2.0 client
credentials grant. In this case, the application acts as itself, not as a user, to call the Graph API.
In this article, you learn how to perform the automated use case. You'll build a .NET 4.5 B2CGraphClient that
performs user create, read, update, and delete (CRUD ) operations. The client will have a Windows command-line
interface (CLI) that allows you to invoke various methods. However, the code is written to behave in a non-
interactive, automated fashion.
IMPORTANT
You must use the Azure AD Graph API to manage users in an Azure AD B2C directory. The Azure AD Graph API is different
from the Microsoft Graph API. Learn more in this MSDN blog post: Microsoft Graph or Azure AD Graph.
Prerequisites
Before you can create applications or users, you need an Azure AD B2C tenant. If you don't already have one,
Create an Azure Active Directory B2C tenant.
Register an application
Once you have an Azure AD B2C tenant, you need to register your management application by using the Azure
portal. You also need to grant it the permissions required for performing management tasks on behalf of your
automated script or management application.
Register application in Azure Active Directory
To use the Azure AD Graph API with your B2C tenant, you need to register an application by using the Azure
Active Directory application registration workflow.
To register an application in your Azure AD B2C tenant, you can use the current Applications experience, or our
new unified App registrations (Preview) experience. Learn more about the new experience.
Applications
App registrations (Preview )
1. Sign in to the Azure portal.
2. Select the Directory + subscription filter in the top menu, and then select the directory that contains your
Azure AD B2C tenant.
3. In the left menu, select Azure Active Directory (not Azure AD B2C ). Or, select All services and then search
for and select Azure Active Directory.
4. Under Manage, select App registrations (Legacy).
5. Select New application registration.
6. Enter a name for the application. For example, managementapp1.
7. For Application type, select Web app / API.
8. Enter any valid URL in Sign-on URL. For example, https://localhost . The endpoint doesn't need to be
reachable, but must be a valid URL.
9. Select Create.
10. Record the Application ID that appears on the Registered app overview page. You use this value in a later
step.
Assign API access permissions
Applications
App registrations (Preview )
1. On the Registered app overview page, select Settings.
2. Under API ACCESS, select Required permissions.
3. Select Windows Azure Active Directory.
4. Under APPLICATION PERMISSIONS, select Read and write directory data.
5. Select Save.
6. Select Grant permissions, and then select Yes. It might take a few minutes to for the permissions to fully
propagate.
Create client secret
Applications
App registrations (Preview )
1. Under API ACCESS, select Keys.
2. Enter a description for the key in the Key description box. For example, clientsecret1.
3. Select a validity Duration and then select Save.
4. Record the key's VALUE. You use this value for configuration in a later step.
You now have an application that has permission to create, read, and update users in your Azure AD B2C tenant.
Continue to the next section to add user delete and password update permissions.
After you've obtained the code sample, configure it for your environment and then build the project:
1. Open the B2CGraphClient\B2CGraphClient.sln solution in Visual Studio.
2. In the B2CGraphClient project, open the App.config file.
3. Replace the <appSettings> section with the following XML. Then replace {your-b2c-tenant} with the name
of your tenant, and {Application ID} and {Client secret} with the values you recorded earlier.
<appSettings>
<add key="b2c:Tenant" value="{your-b2c-tenant}.onmicrosoft.com" />
<add key="b2c:ClientId" value="{Application ID}" />
<add key="b2c:ClientSecret" value="{Client secret}" />
</appSettings>
4. Build the solution. Right-click on the B2CGraphClient solution in the Solution Explorer, and then select
Rebuild Solution.
If the build is successful, the B2C.exe console application can be found in B2CGraphClient\bin\Debug .
cd B2CGraphClient\bin\Debug
B2C Help
The B2C Help command displays a brief description of the available subcommands. Each time you invoke one of
its subcommands, B2CGraphClient sends a request to the Azure AD Graph API.
The following sections discuss how the application's code makes calls to the Azure AD Graph API.
Get an access token
Any request to the Azure AD Graph API requires an access token for authentication. B2CGraphClient uses the
open-source Active Directory Authentication Library (ADAL ) to assist in obtaining access tokens. ADAL makes
token acquisition easier by providing a helper API and taking care of a few important details like caching access
tokens. You don't have to use ADAL to get tokens, however. You could instead get tokens by manually crafting
HTTP requests.
NOTE
You must use ADAL v2 or higher to get access tokens that can be used with the Azure AD Graph API. You cannot use ADAL
v1.
When B2CGraphClient executes, it creates an instance of the B2CGraphClient class. The constructor for this class
sets up the ADAL authentication scaffolding:
// The AuthenticationContext is ADAL's primary class, in which you indicate the tenant to use.
this.authContext = new AuthenticationContext("https://login.microsoftonline.com/" + tenant);
// The ClientCredential is where you pass in your client_id and client_secret, which are
// provided to Azure AD in order to receive an access_token by using the app's identity.
this.credential = new ClientCredential(clientId, clientSecret);
}
You can get an access token for the Graph API by calling the ADAL AuthenticationContext.AcquireToken()
method. ADAL then returns an access_token that represents the application's identity.
Read users
When you want to get a list of users or get a particular user from the Azure AD Graph API, you can send an HTTP
GET request to the /users endpoint. A request for all of the users in a tenant looks like this:
GET https://graph.windows.net/contosob2c.onmicrosoft.com/users?api-version=1.6
Authorization: Bearer
eyJhbGciOiJSUzI1NiIsIng1dCI6IjdkRC1nZWNOZ1gxWmY3R0xrT3ZwT0IyZGNWQSIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJod...
// For B2C user management, be sure to use the 1.6 Graph API version.
HttpClient http = new HttpClient();
string url = "https://graph.windows.net/" + tenant + api + "?" + "api-version=1.6";
if (!string.IsNullOrEmpty(query))
{
url += "&" + query;
}
// Append the access token for the Graph API to the Authorization header of the request by using the
Bearer scheme.
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, url);
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
HttpResponseMessage response = await http.SendAsync(request);
...
{
// All of these properties are required to create consumer users.
"accountEnabled": true,
"signInNames": [ // controls which identifier the user uses to sign in to the
account
{
"type": "emailAddress", // can be 'emailAddress' or 'userName'
"value": "consumer@fabrikam.com"
}
],
"creationType": "LocalAccount", // always set to 'LocalAccount'
"displayName": "Consumer User", // a value that can be used for displaying to the end user
"mailNickname": "cuser", // an email alias for the user
"passwordProfile": {
"password": "P@ssword!",
"forceChangePasswordNextLogin": false // always set to false
},
"passwordPolicies": "DisablePasswordExpiration"
}
The Create-User command takes as an input parameter a JSON file that contains a JSON representation of a
user object. There are two sample JSON files in the code sample: usertemplate-email.json and
usertemplate-username.json . You can modify these files to suit your needs. In addition to the required fields above,
several optional fields are included in the files.
For more information on required and optional fields, see the Entity and complex type reference | Graph API
reference.
You can see how the POST request is constructed in B2CGraphClient.SendGraphPostRequest() :
It attaches an access token to the Authorization header of the request.
It sets api-version=1.6 .
It includes the JSON user object in the body of the request.
NOTE
If the accounts that you want to migrate from an existing user store have a lower password strength than the strong
password strength enforced by Azure AD B2C, you can disable the strong password requirement by using the
DisableStrongPassword value in the passwordPolicies property. For example, you can modify the previous create user
request as follows: "passwordPolicies": "DisablePasswordExpiration, DisableStrongPassword" .
{
"displayName": "Joe Consumer" // this request updates only the user's displayName
}
Try updating a user by modifying some values in your JSON files, and then use the B2CGraphClient to run one of
these commands:
Inspect the B2CGraphClient.SendGraphPatchRequest() method for details on how to send this request.
Search users
You can search for users in your B2C tenant in the following ways:
Reference the user's object ID.
Reference their sign-in identifer, the signInNames property.
Reference any of the valid OData parameters. For example, 'givenName', 'surname', 'displayName' etc.
Run one of the following commands to search for a user:
For example:
Delete users
To delete users, use the HTTP DELETE method, and construct the URL with the user's object ID:
DELETE https://graph.windows.net/contosob2c.onmicrosoft.com/users/<user-object-id>?api-version=1.6
Authorization: Bearer
eyJhbGciOiJSUzI1NiIsIng1dCI6IjdkRC1nZWNOZ1gxWmY3R0xrT3ZwT0IyZGNWQSIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJod...
To see an example, enter this command and view the delete request that is printed to the console:
Inspect the B2CGraphClient.SendGraphDeleteRequest() method for details on how to send this request.
You can perform many other actions with the Azure AD Graph API in addition to user management. The Azure
AD Graph API reference provides details on each action, along with sample requests.
Use custom attributes
Most consumer applications need to store some type of custom user profile information. One way you can do so
is to define a custom attribute in your B2C tenant. You can then treat that attribute in the same way you treat any
other property on a user object. You can update the attribute, delete the attribute, query by the attribute, send the
attribute as a claim in sign-in tokens, and more.
To define a custom attribute in your B2C tenant, see the B2C custom attribute reference.
You can view the custom attributes defined in your B2C tenant by using the following B2CGraphClient commands:
B2C Get-B2C-Application
B2C Get-Extension-Attribute <object-id-in-the-output-of-the-above-command>
The output reveals the details of each custom attribute. For example:
{
"odata.type": "Microsoft.DirectoryServices.ExtensionProperty",
"objectType": "ExtensionProperty",
"objectId": "cec6391b-204d-42fe-8f7c-89c2b1964fca",
"deletionTimestamp": null,
"appDisplayName": "",
"name": "extension_55dc0861f9a44eb999e0a8a872204adb_Jersey_Number",
"dataType": "Integer",
"isSyncedFromOnPremises": false,
"targetObjects": [
"User"
]
}
Next steps
By using B2CGraphClient , you have a service application that can manage your B2C tenant users
programmatically. B2CGraphClient uses its own application identity to authenticate to the Azure AD Graph API. It
also acquires tokens by using a client secret.
As you incorporate this functionality into your own application, remember a few key points for B2C applications:
Grant the application the required permissions in the tenant.
When you call the Graph API, use api-version=1.6 .
When you create and update consumer users, a few properties are required, as described above.
Accessing Azure AD B2C audit logs
12/9/2019 • 9 minutes to read • Edit Online
Azure Active Directory B2C (Azure AD B2C ) emits audit logs containing activity information about B2C resources,
tokens issued, and administrator access. This article provides a brief overview of the information available in audit
logs and instructions on how to access this data for your Azure AD B2C tenant.
Audit log events are only retained for seven days. Plan to download and store your logs using one of the methods
shown below if you require a longer retention period.
NOTE
You can't see user sign-ins for individual Azure AD B2C applications under the Users section of the Azure Active Directory
or Azure AD B2C pages in the Azure portal. The sign-in events there show user activity, but can't be correlated back to the
B2C application that the user signed in to. You must use the audit logs for that, as explained further in this article.
For user object CRUD activities, refer to the Core Directory category.
Example activity
This example image from the Azure portal shows the data captured when a user signs in with an external identity
provider, in this case, Facebook:
The activity details panel contains the following relevant information:
# This script requires the registration of a Web Application in Azure Active Directory:
# https://docs.microsoft.com/azure/active-directory/reports-monitoring/concept-reporting-api
# Constants
$ClientID = "your-client-application-id-here" # Insert your application's client ID, a GUID
(registered by Global Admin)
$ClientSecret = "your-client-application-secret-here" # Insert your application's client secret
$tenantdomain = "your-b2c-tenant.onmicrosoft.com" # Insert your Azure AD B2C tenant; for example,
contoso.onmicrosoft.com
$loginURL = "https://login.microsoftonline.com"
$resource = "https://graph.microsoft.com" # Microsoft Graph API resource URI
$7daysago = "{0:s}" -f (get-date).AddDays(-7) + "Z" # Use 'AddMinutes(-5)' to decrement minutes, for
example
Write-Output "Searching for events starting $7daysago"
# Create HTTP header, get an OAuth2 access token based on client id, secret and tenant domain
$body =
@{grant_type="client_credentials";resource=$resource;client_id=$ClientID;client_secret=$ClientSecret}
$oauth = Invoke-RestMethod -Method Post -Uri $loginURL/$tenantdomain/oauth2/token?api-version=1.0 -Body
$body
# Parse audit report items, save output to file(s): auditX.json, where X = 0 thru n for number of nextLink
pages
if ($oauth.access_token -ne $null) {
$i=0
$headerParams = @{'Authorization'="$($oauth.token_type) $($oauth.access_token)"}
$url = "https://graph.microsoft.com/v1.0/auditLogs/directoryAudits?`$filter=loggedByService eq 'B2C' and
activityDateTime gt " + $7daysago
Here's the JSON representation of the example activity event shown earlier in the article:
{
"id": "B2C_DQO3J_4984536",
"category": "Authentication",
"correlationId": "00000000-0000-0000-0000-000000000000",
"result": "success",
"resultReason": "N/A",
"activityDisplayName": "Issue an id_token to the application",
"activityDateTime": "2019-09-14T18:13:17.0618117Z",
"loggedByService": "B2C",
"operationType": "",
"initiatedBy": {
"user": null,
"app": {
"appId": "00000000-0000-0000-0000-000000000000",
"displayName": null,
"servicePrincipalId": null,
"servicePrincipalName": "00000000-0000-0000-0000-000000000000"
}
},
"targetResources": [
{
"id": "00000000-0000-0000-0000-000000000000",
"displayName": null,
"type": "User",
"userPrincipalName": null,
"groupType": null,
"modifiedProperties": []
}
],
"additionalDetails": [
{
"key": "TenantId",
"value": "test.onmicrosoft.com"
},
{
"key": "PolicyId",
"value": "B2C_1A_signup_signin"
},
{
"key": "ApplicationId",
"value": "00000000-0000-0000-0000-000000000000"
},
{
"key": "Client",
"value": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko)
Chrome/76.0.3809.132 Safari/537.36"
},
{
"key": "IdentityProviderName",
"value": "facebook"
},
{
"key": "IdentityProviderApplicationId",
"value": "0000000000000000"
},
{
"key": "ClientIpAddress",
"value": "127.0.0.1"
}
]
}
Next steps
You can automate other administration tasks, for example, manage users with .NET.
Use the Azure portal to create and delete consumer
users in Azure AD B2C
11/12/2019 • 2 minutes to read • Edit Online
There might be scenarios in which you want to manually create consumer accounts in your Azure Active Directory
B2C (Azure AD B2C ) directory. Although consumer accounts in an Azure AD B2C directory are most commonly
created when users sign up to use one of your applications, you can create them programmatically and by using
the Azure portal. This article focuses on the Azure portal method of user creation and deletion.
To add or delete users, your account must be assigned the User administrator or Global administrator role.
NOTE
This feature is in public preview.
Next steps
For automated user management scenarios, for example migrating users from another identity provider to your
Azure AD B2C directory, see Azure AD B2C: User migration.
Secure an Azure API Management API with Azure
AD B2C
11/5/2019 • 7 minutes to read • Edit Online
Learn how to restrict access to your Azure API Management (APIM ) API to clients that have authenticated with
Azure Active Directory B2C (Azure AD B2C ). Follow the steps in this article to create and test an inbound policy in
APIM that restricts access to only those requests that include a valid Azure AD B2C -issued access token.
Prerequisites
You need the following resources in place before continuing with the steps in this article:
Azure AD B2C tenant
Application registered in your tenant
User flows created in your tenant
Published API in Azure API Management
Postman to test secured access (optional)
5. Select the hyperlink to browse to the OpenID Connect well-known configuration page.
6. In the page that opens in your browser, record the issuer value, for example:
https://your-b2c-tenant.b2clogin.com/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/v2.0/
You use this value in the next section when you configure your API in Azure API Management.
You should now have two URLs recorded for use in the next section: the OpenID Connect well-known
configuration endpoint URL and the issuer URI. For example:
https://yourb2ctenant.b2clogin.com/yourb2ctenant.onmicrosoft.com/v2.0/.well-known/openid-configuration?
p=B2C_1_signupsignin1
https://yourb2ctenant.b2clogin.com/99999999-0000-0000-0000-999999999999/v2.0/
KEY VALUE
Your GET request URL and Headers should appear similar to:
3. Select the Send button in Postman to execute the request. If you've configured everything correctly, you
should be presented with a JSON response with a collection of conference speakers (shown here
truncated):
{
"collection": {
"version": "1.0",
"href": "https://conferenceapi.azurewebsites.net:443/speakers",
"links": [],
"items": [
{
"href": "https://conferenceapi.azurewebsites.net/speaker/1",
"data": [
{
"name": "Name",
"value": "Scott Guthrie"
}
],
"links": [
{
"rel": "http://tavis.net/rels/sessions",
"href": "https://conferenceapi.azurewebsites.net/speaker/1/sessions"
}
]
},
[...]
2. Select the Send button to execute the request. With an invalid token, the expected result is a 401
unauthorized status code:
{
"statusCode": 401,
"message": "Unauthorized. Access token is missing or invalid."
}
If you see the 401 status code, you've verified that only callers with a valid access token issued by Azure AD B2C
can make successful requests to your Azure API Management API.
Similarly, to support multiple token issuers, add their endpoint URIs to the <issuers> element in the APIM
inbound policy.
Migrate to b2clogin.com
If you have an APIM API that validates tokens issued by the legacy login.microsoftonline.com endpoint, you
should migrate the API and the applications that call it to use tokens issued by b2clogin.com.
You can follow this general process to perform a staged migration:
1. Add support in your APIM inbound policy for tokens issued by both b2clogin.com and
login.microsoftonline.com.
2. Update your applications one at a time to obtain tokens from the b2clogin.com endpoint.
3. Once all of your applications are correctly obtaining tokens from b2clogin.com, remove support for
login.microsoftonline.com-issued tokens from the API.
The following example APIM inbound policy illustrates how to accept tokens issued by both b2clogin.com and
login.microsoftonline.com. Additionally, it supports API requests from two applications.
<policies>
<inbound>
<validate-jwt header-name="Authorization" failed-validation-httpcode="401" failed-validation-error-
message="Unauthorized. Access token is missing or invalid.">
<openid-config url="https://yourb2ctenant.b2clogin.com/yourb2ctenant.onmicrosoft.com/v2.0/.well-
known/openid-configuration?p=B2C_1_signupsignin1" />
<audiences>
<audience>44444444-0000-0000-0000-444444444444</audience>
<audience>66666666-0000-0000-0000-666666666666</audience>
</audiences>
<issuers>
<issuer>https://login.microsoftonline.com/99999999-0000-0000-0000-999999999999/v2.0/</issuer>
<issuer>https://yourb2ctenant.b2clogin.com/99999999-0000-0000-0000-999999999999/v2.0/</issuer>
</issuers>
</validate-jwt>
<base />
</inbound>
<backend> <base /> </backend>
<outbound> <base /> </outbound>
<on-error> <base /> </on-error>
</policies>
Next steps
For additional details on Azure API Management policies, see the APIM policy reference index.
You can find information about migrating OWIN -based web APIs and their applications to b2clogin.com in
Migrate an OWIN -based web API to b2clogin.com.
Manage user access in Azure Active Directory B2C
9/17/2019 • 9 minutes to read • Edit Online
This article discusses how to manage user access to your applications by using Azure Active Directory B2C (Azure
AD B2C ). Access management in your application includes:
Identifying minors and controlling user access to your application.
Requiring parental consent for minors to use your applications.
Gathering birth and country/region data from users.
Capturing a terms-of-use agreement and gating access.
NOTE
In Azure Active Directory B2C, custom policies are designed primarily to address complex scenarios. For most scenarios, we
recommend that you use built-in user flows.
<ClaimsTransformations>
<ClaimsTransformation Id="GetNewUserAgreeToTermsOfUseConsentDateTime"
TransformationMethod="GetCurrentDateTime">
<OutputClaims>
<OutputClaim ClaimTypeReferenceId="extension_termsOfUseConsentDateTime"
TransformationClaimType="currentDateTime" />
</OutputClaims>
</ClaimsTransformation>
<ClaimsTransformation Id="IsTermsOfUseConsentRequired" TransformationMethod="IsTermsOfUseConsentRequired">
<InputClaims>
<InputClaim ClaimTypeReferenceId="extension_termsOfUseConsentDateTime"
TransformationClaimType="termsOfUseConsentDateTime" />
</InputClaims>
<InputParameters>
<InputParameter Id="termsOfUseTextUpdateDateTime" DataType="dateTime" Value="2098-01-30T23:03:45" />
</InputParameters>
<OutputClaims>
<OutputClaim ClaimTypeReferenceId="termsOfUseConsentRequired" TransformationClaimType="result" />
</OutputClaims>
</ClaimsTransformation>
</ClaimsTransformations>
Next steps
To learn how to delete and export user data, see Manage user data.
Manage user data in Azure Active Directory B2C
9/17/2019 • 3 minutes to read • Edit Online
This article discusses how you can manage the user data in Azure Active Directory B2C (Azure AD B2C ) by using
the operations that are provided by the Azure Active Directory Graph API. Managing user data includes deleting or
exporting data from audit logs.
NOTE
This article provides steps for how to delete personal data from the device or service and can be used to support your
obligations under the GDPR. If you’re looking for general info about GDPR, see the GDPR section of the Service Trust portal.
Next steps
To learn how to manage how users access your application, see Manage user access.
Migrate users to Azure Active Directory B2C
12/9/2019 • 14 minutes to read • Edit Online
When you migrate your identity provider to Azure Active Directory B2C (Azure AD B2C ), you might also need to
migrate the user accounts. This article explains how to migrate existing user accounts from any identity provider
to Azure AD B2C. The article is not meant to be prescriptive, but rather, it describes a few scenarios. The developer
is responsible for the suitability of each approach.
Password policy
The Azure AD B2C password policy (for local accounts) is based on Azure AD policy. The Azure AD B2C sign-up
or sign-in and password reset policies use the "strong" password strength and don't expire any passwords. For
more information, see Azure AD password policy.
If the accounts that you want to migrate use a weaker password strength than the strong password strength
enforced by Azure AD B2C, you can disable the strong password requirement. To change the default password
policy, set the passwordPolicies property to DisableStrongPassword . For example, you can modify the create user
request as follows:
IMPORTANT
You must use a B2C tenant administrator account that is local to the B2C tenant. The account name syntax is
admin@contosob2c.onmicrosoft.com.
In this PowerShell script, which requires the Azure AD PowerShell V2 module, do the following:
1. Connect to your online service. To do so, run the Connect-AzureAD cmdlet at the Windows PowerShell
command prompt, and provide your credentials.
2. Use the Application ID to assign the application the user account administrator role. These roles have
well-known identifiers, so all you need to do is enter your Application ID in the script.
Connect-AzureAD
# If role instance does not exist, instantiate it based on the role template
if ($role -eq $null) {
# Instantiate an instance of the role template
$roleTemplate = Get-AzureADDirectoryRoleTemplate | Where-Object {$_.displayName -eq 'User Account
Administrator'}
Enable-AzureADDirectoryRole -RoleTemplateId $roleTemplate.ObjectId
As you can see, the file contains a list of user entities. Each user entity has the following properties:
email
displayName
firstName
lastName
password (can be empty)
NOTE
At compile time, Visual Studio copies the file to the bin directory.
<appSettings>
<add key="b2c:Tenant" value="{Your Tenant Name}" />
<add key="b2c:ClientId" value="{The ApplicationID from above}" />
<add key="b2c:ClientSecret" value="{The Client Secret Key from above}" />
<add key="MigrationFile" value="{Name of a JSON file containing the users' data; for example,
UsersData.json}" />
<add key="BlobStorageConnectionString" value="{Your connection Azure table string}" />
</appSettings>
NOTE
The use of an Azure table connection string is described in the next sections.
Your B2C tenant name is the domain that you entered during tenant creation, and it is displayed in the Azure portal. The
tenant name usually ends with the suffix .onmicrosoft.com (for example, contosob2c.onmicrosoft.com).
Step 2.3: Run the pre -migration process
Right-click the AADB2C.UserMigration solution, and then rebuild the sample. If you are successful, you should now
have a UserMigration.exe executable file located in AADB2C.UserMigration\bin\Debug\net461 . To run the migration
process, use one of the following command-line parameters:
To migrate users with password, use the UserMigration.exe 1 command.
To migrate users with random password, use the UserMigration.exe 2 command. This operation also
creates an Azure table entity. Later, you configure the policy to call the REST API service. The service uses
an Azure table to track and manage the migration process.
TIP
You can also retrieve a user by display name by using the following command:
UserMigration.exe 4 "<Display name>" .
NOTE
To clean up your tenant, configure User Account Administrator permissions for your application.
The sample migration app cleans up all users who are listed in the JSON file.
6. Copy the URL shown in the Run now endpoint text box, and then send it to your users.
Step 4: (Optional) Change your policy to check and set the user
migration status
NOTE
To check and change the user migration status, you must use a custom policy. The set-up instructions from Get started with
custom policies must be completed.
When users try to sign in without resetting the password first, your policy should return a friendly error message.
For example:
Your password has expired. To reset it, select the Reset Password link.
This optional step requires the use of Azure AD B2C custom policies, as described in the Getting started with
custom policies article.
In this section, you change the policy to check the user migration status on sign-in. If the user didn't change the
password, return an HTTP 409 error message that asks the user to select the Forgot your password? link.
To track the password change, you use an Azure table. When you run the pre-migration process with the
command-line parameter 2 , you create a user entity in an Azure table. Your service does the following:
On sign-in, the Azure AD B2C policy invokes your migration RESTful service, sending an email message as
an input claim. The service searches for the email address in the Azure table. If the address exists, the
service throws an error message: You must change password.
After the user successfully changes the password, remove the entity from the Azure table.
NOTE
We use an Azure table to simplify the sample. You can store the migration status in any database or as a custom property in
the Azure AD B2C account.
{
"BlobStorageConnectionString": "{The Azure Blob storage connection string}",
...
}
<TechnicalProfile Id="LocalAccountSignIn">
<DisplayName>Local account just in time migration</DisplayName>
<Protocol Name="Proprietary" Handler="Web.TPEngine.Providers.RestfulProvider, Web.TPEngine,
Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
<Metadata>
<Item Key="ServiceUrl">http://{your-
app}.azurewebsites.net/api/PrePasswordReset/LoalAccountSignIn</Item>
<Item Key="AuthenticationType">None</Item>
<Item Key="SendClaimsIn">Body</Item>
</Metadata>
<InputClaims>
<InputClaim ClaimTypeReferenceId="signInName" PartnerClaimType="email" />
</InputClaims>
<UseTechnicalProfileForSessionManagement ReferenceId="SM-Noop" />
</TechnicalProfile>
<TechnicalProfile Id="LocalAccountPasswordReset">
<DisplayName>Local account just in time migration</DisplayName>
<Protocol Name="Proprietary" Handler="Web.TPEngine.Providers.RestfulProvider, Web.TPEngine,
Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
<Metadata>
<Item Key="ServiceUrl">http://{your-
app}.azurewebsites.net/api/PrePasswordReset/PasswordUpdated</Item>
<Item Key="AuthenticationType">None</Item>
<Item Key="SendClaimsIn">Body</Item>
</Metadata>
<InputClaims>
<InputClaim ClaimTypeReferenceId="email" PartnerClaimType="email" />
</InputClaims>
<UseTechnicalProfileForSessionManagement ReferenceId="SM-Noop" />
</TechnicalProfile>
</TechnicalProfiles>
</ClaimsProvider>
The preceding technical profile defines one input claim: signInName (send as email). On sign-in, the claim is sent
to your RESTful endpoint.
After you define the technical profile for your RESTful API, configure the existing
SelfAsserted-LocalAccountSignin-Email technical profile to additionally call your REST API technical profile by
overriding it within your TrustFrameworkExtensions.xml file:
<TechnicalProfile Id="SelfAsserted-LocalAccountSignin-Email">
<ValidationTechnicalProfiles>
<ValidationTechnicalProfile ReferenceId="LocalAccountUserMigration" />
</ValidationTechnicalProfiles>
</TechnicalProfile>
IMPORTANT
Use the diagnostics logs only during development and testing. The RESTful API output might contain confidential
information that should not be exposed in production.
When you plan to migrate your identity provider to Azure AD B2C, you may also need to migrate users with social
identities. This article explains how to migrate existing social identities accounts, such as: Facebook, LinkedIn,
Microsoft, and Google accounts to Azure AD B2C. This article also applies to federated identities, however these
migrations are less common. For the remainder of this article, consider anything that applies to social accounts to
also apply to other types of federated accounts.
Prerequisites
This article is a continuation of the user migration article, and focuses on social identity migration. Before you start,
read user migration.
"userIdentities": [{
"issuer": "Facebook.com",
"issuerUserId": "MTIzNDU2Nzg5MA=="
}
]
Depending on the identity provider, the Issuer User ID is a unique value for a given user per application or
development account. Configure the Azure AD B2C policy with the same application ID that was previously
assigned by the social provider or another application within the same development account.
Required properties
The following list shows the properties that are required when you create a user.
accountEnabled - true
displayName - The name to display in the address book for the user.
passwordProfile - The password profile for the user.
NOTE
For social accounts only (without local account credentials), you still must specify the password. Azure AD B2C ignores the
password you specify for social accounts.
userPrincipalName - The user principal name (someuser@contoso.com). The user principal name must
contain one of the verified domains for the tenant. To specify the UPN, generate new GUID value, concatenate
with @ and your tenant name.
mailNickname - The mail alias for the user. This value can be the same ID that you use for the
userPrincipalName.
signInNames - One or more SignInName records that specify the sign-in names for the user. Each sign-in
name must be unique across the company/tenant. For social account only, this property can be left empty.
userIdentities - One or more UserIdentity records that specify the social account type and the unique user
identifier from the social identity provider.
[optional] otherMails - For social account only, the user's email addresses
{
"objectId": null,
"accountEnabled": true,
"mailNickname": "5164db16-3eee-4629-bfda-dcc3326790e9",
"signInNames": [{
"type": "emailAddress",
"value": "david@contoso.com"
}
],
"creationType": "LocalAccount",
"displayName": "David Hor",
"givenName": "David",
"surname": "Hor",
"passwordProfile": {
"password": "1234567",
"forceChangePasswordNextLogin": false
},
"passwordPolicies": "DisablePasswordExpiration,DisableStrongPassword",
"userIdentities": [{
"issuer": "contoso.com",
"issuerUserId": "ZGF2aWRAY29udG9zby5jb20="
}
],
"otherMails": [],
"userPrincipalName": "5164db16-3eee-4629-bfda-dcc3326790e9@tenant-name.onmicrosoft.com"
}
NOTE
Use a B2C tenant administrator account that is local to the B2C tenant. The account name syntax is admin@tenant-
name.onmicrosoft.com.
{
"userIdentities": [
{
"issuer": "Facebook.com",
"issuerUserId": "MTIzNDU2Nzg5MA=="
}
]
}
NOTE
If you don't update the UsersData.json file in the sample with your data, you can sign-in with the sample local account
credentials but not with the social account examples. To migrate your social accounts, provide real data.
For more information, how to use the sample app, see Azure Active Directory B2C: User migration
Developer notes for custom policies in Azure Active
Directory B2C
12/9/2019 • 4 minutes to read • Edit Online
Custom policy configuration in Azure Active Directory B2C is now generally available. This method of
configuration is targeted at advanced identity developers building complex identity solutions. Custom policies
make the power of the Identity Experience Framework available in Azure AD B2C tenants. Advanced identity
developers using custom policies should plan to invest some time completing walk-throughs and reading reference
documents.
While most of the custom policy options available are now generally available, there are underlying capabilities,
such as technical profile types and content definition APIs that are at different stages in the software lifecycle. Many
more are coming. The table below specifies the level of availability at a more granular level.
IDP-WSFED X
Relying Party X
OAUTH2
Component Support
FEATURE DEVELOPMENT PREVIEW GA NOTES
Azure Email X
subsystem for email
verification
Multi-language X
support
Content Definition
FEATURE DEVELOPMENT PREVIEW GA NOTES
Forgot Password, X
api.localaccountpassw
ordreset
MFA page, X
api.phonefactor
Self-asserted social X
account sign-up,
api.selfasserted
Self-asserted profile X
update,
api.selfasserted.profile
update
FEATURE DEVELOPMENT PREVIEW GA NOTES
Unified signup or X
sign-in page,
api.signuporsignin,
with parameter
"disableSignup"
JavaScript / Page X
layout
App-IEF integration
FEATURE DEVELOPMENT PREVIEW GA NOTES
Session Management
FEATURE DEVELOPMENT PREVIEW GA NOTES
Security
FEATURE DEVELOPMENT PREVIEW GA NOTES
Policy upload X
Developer interface
FEATURE DEVELOPMENT PREVIEW GA NOTES
Azure Portal-IEF UX X
Next steps
Learn more about custom policies and the differences with user flows.
Cookies definitions for Azure Active Directory B2C
7/5/2019 • 2 minutes to read • Edit Online
The following table lists the cookies used in Azure Active Directory B2C.
x-ms-cpim-rc login.microsoftonline.com, End of browser session Used for storing the relay
b2clogin.com, branded cookie.
domain
Azure Active Directory B2C: Region availability &
data residency
12/9/2019 • 2 minutes to read • Edit Online
Region availability and data residency are two very different concepts that apply differently to Azure AD B2C from
the rest of Azure. This article explains the differences between these two concepts, and compares how they apply to
Azure versus Azure AD B2C.
Azure AD B2C is generally available worldwide with the option for data residency in the United States,
Europe, or Asia Pacific.
Region availability refers to where a service is available for use.
Data residency refers to where user data is stored.
Region availability
Azure AD B2C is available worldwide via the Azure public cloud.
This differs from the model followed by most other Azure services, which typically couple availability with data
residency. You can see examples of this in both Azure's Products Available By Region page and the Active Directory
B2C pricing calculator.
Data residency
Azure AD B2C stores user data in either United States, Europe, or the Asia Pacific region.
Data residency is determined by the country/region you select when you create an Azure AD B2C tenant:
United States, Canada, Costa Rica, Dominican Republic, El Salvador, Guatemala, Mexico, Panama, Puerto Rico
and Trinidad & Tobago
Data resides in Europe for the following countries/regions:
Algeria, Austria, Azerbaijan, Bahrain, Belarus, Belgium, Bulgaria, Croatia, Cyprus, Czech Republic, Denmark,
Egypt, Estonia, Finland, France, Germany, Greece, Hungary, Iceland, Ireland, Israel, Italy, Jordan, Kazakhstan,
Kenya, Kuwait, Latvia, Lebanon, Liechtenstein, Lithuania, Luxembourg, North Macedonia, Malta, Montenegro,
Morocco, Netherlands, Nigeria, Norway, Oman, Pakistan, Poland, Portugal, Qatar, Romania, Russia, Saudi
Arabia, Serbia, Slovakia, Slovenia, South Africa, Spain, Sweden, Switzerland, Tunisia, Turkey, Ukraine, United
Arab Emirates and United Kingdom.
Afghanistan, Hong Kong SAR, India, Indonesia, Japan, Korea, Malaysia, Philippines, Singapore, Sri Lanka,
Taiwan, and Thailand.
The following countries/regions are in the process of being added to the list. For now, you can still use Azure AD
B2C by picking any of the countries/regions above.
Argentina, Australia, Brazil, Chile, Colombia, Ecuador, Iraq, New Zealand, Paraguay, Peru, Uruguay, and
Venezuela.
Preview tenant
If you had created a B2C tenant during Azure AD B2C's preview period, it's likely that your Tenant type says
Preview tenant.
If this is the case, you must use your tenant ONLY for development and testing purposes. DO NOT use a preview
tenant for production applications.
There is no migration path from a preview B2C tenant to a production-scale B2C tenant. You must create a new
B2C tenant for your production applications.
There are known issues when you delete a preview B2C tenant and create a production-scale B2C tenant with the
same domain name. You must create a production-scale B2C tenant with a different domain name.
Billing model for Azure Active Directory B2C
10/27/2019 • 7 minutes to read • Edit Online
Azure Active Directory B2C (Azure AD B2C ) usage is billed to a linked Azure subscription and uses a monthly
active users (MAU ) billing model. Learn how to link an Azure AD B2C resource to a subscription and how the
MAU billing model works in the following sections.
IMPORTANT
This article does not contain pricing information. For the latest information about usage billing and pricing, see Azure Active
Directory B2C pricing.
5. On the Overview page of the Azure AD B2C resource, under Billable Units, select the Per Authentication
(Change to MAU ) link.
After you complete these steps for an Azure AD B2C tenant, your Azure subscription is billed in accordance with
your Azure Direct or Enterprise Agreement details, if applicable.
Manage your Azure AD B2C tenant resources
After you create the Azure AD B2C resource in an Azure subscription, you should see a new resource of the type
"B2C tenant" appear with your other Azure resources.
You can use this resource to:
Navigate to the subscription to review billing information
Get the Azure AD B2C tenant's tenant ID in GUID format
Go to your Azure AD B2C tenant
Submit a support request
Move your Azure AD B2C tenant resource to another Azure subscription or resource group
Regional restrictions
If you've established regional restrictions for Azure resource creation in your subscription, that restriction may
prevent you from creating the Azure AD B2C resource.
To mitigate this issue, relax your regional restrictions.
Next steps
In addition to reviewing the usage and billing details within a selected Azure subscription, you can review detailed
day-by-day usage reports by using the usage reporting API.
Manage threats to resources and data in Azure
Active Directory B2C
12/9/2019 • 2 minutes to read • Edit Online
Azure Active Directory B2C (Azure AD B2C ) has built-in features that can help you protect against threats to your
resources and data. These threats include denial-of-service attacks and password attacks. Denial-of-service attacks
might make resources unavailable to intended users. Password attacks lead to unauthorized access to resources.
Denial-of-service attacks
Azure AD B2C defends against SYN flood attacks using a SYN cookie. Azure AD B2C also protects against denial-
of-service attacks by using limits for rates and connections.
Password attacks
Passwords that are set by users are required to be reasonably complex. Azure AD B2C has mitigation techniques
in place for password attacks. Mitigation includes detection of brute-force password attacks and dictionary
password attacks. By using various signals, Azure AD B2C analyzes the integrity of requests. Azure AD B2C is
designed to intelligently differentiate intended users from hackers and botnets.
Azure AD B2C uses a sophisticated strategy to lock accounts. The accounts are locked based on the IP of the
request and the passwords entered. The duration of the lockout also increases based on the likelihood that it's an
attack. After a password is tried 10 times unsuccessfully (the default attempt threshold), a one-minute lockout
occurs. The next time a login is unsuccessful after the account is unlocked (that is, after the account has been
automatically unlocked by the service once the lockout period expires), another one-minute lockout occurs and
continues for each unsuccessful login. Entering the same password repeatedly doesn't count as multiple
unsuccessful logins.
The first 10 lockout periods are one minute long. The next 10 lockout periods are slightly longer and increase in
duration after every 10 lockout periods. The lockout counter resets to zero after a successful login when the
account isn’t locked. Lockout periods can last up to five hours.
To learn about viewing the sign-in activity report in Azure Active Directory, see Sign-in activity report error codes.
Azure AD B2C: Extensions app
7/8/2019 • 2 minutes to read • Edit Online
IMPORTANT
Do not delete the b2c-extensions-app unless you are planning to immediately delete your tenant. If the app remains deleted
for more than 30 days, user information will be permanently lost.
NOTE
An application can only be restored if it has been deleted within the last 30 days. If it has been more than 30 days, data will
be permanently lost. For more assistance, file a support ticket.
User flow versions in Azure Active Directory B2C
9/24/2019 • 2 minutes to read • Edit Online
User flows in Azure Active Directory B2C (Azure AD B2C ) help you to set up common policies that fully describe
customer identity experiences. These experiences include sign-up, sign-in, password reset, or profile editing. In
Azure AD B2C, you can select from a collection of both recommended user flows and preview user flows.
New user flows are added as new versions. As user flows become stable, they'll be recommended for use. User
flows are marked as Recommended if they've been thoroughly tested. User flows will be considered in preview
until marked as recommended. Use a recommended user flow for any production application, but choose from
other versions to test new functionality as it becomes available. You shouldn't use older versions of recommended
user flows.
IMPORTANT
Unless a user flow is identified as Recommended, it is considered to be in preview. You should use only recommended user
flows for your production applications.
V1
USER FLOW RECOMMENDED DESCRIPTION
V1.1
USER FLOW RECOMMENDED DESCRIPTION
V2
USER FLOW RECOMMENDED DESCRIPTION
USER FLOW RECOMMENDED DESCRIPTION
This page answers frequently asked questions about the Azure Active Directory B2C (Azure AD B2C ). Keep
checking back for updates.
Why can't I access the Azure AD B2C extension in the Azure portal?
There are two common reasons for why the Azure AD extension is not working for you. Azure AD B2C requires
your user role in the directory to be global administrator. Please contact your administrator if you think you should
have access. If you have global administrator privileges, make sure that you are in an Azure AD B2C directory and
not an Azure Active Directory directory. You can see instructions for creating an Azure AD B2C tenant.
Can I use Azure AD B2C features in my existing, employee -based Azure AD tenant?
Azure AD and Azure AD B2C are separate product offerings and cannot coexist in the same tenant. An Azure AD
tenant represents an organization. An Azure AD B2C tenant represents a collection of identities to be used with
relying party applications. With custom policies, Azure AD B2C can federate to Azure AD allowing authentication
of employees in an organization.
Can I use Azure AD B2C to provide social login (Facebook and Google+) into Office 365?
Azure AD B2C can't be used to authenticate users for Microsoft Office 365. Azure AD is Microsoft's solution for
managing employee access to SaaS apps and it has features designed for this purpose such as licensing and
Conditional Access. Azure AD B2C provides an identity and access management platform for building web and
mobile applications. When Azure AD B2C is configured to federate to an Azure AD tenant, the Azure AD tenant
manages employee access to applications that rely on Azure AD B2C.
What are local accounts in Azure AD B2C? How are they different from work or school accounts in Azure AD?
In an Azure AD tenant, users that belong to the tenant sign-in with an email address of the form
<xyz>@<tenant domain> . The <tenant domain> is one of the verified domains in the tenant or the initial
<...>.onmicrosoft.com domain. This type of account is a work or school account.
In an Azure AD B2C tenant, most apps want the user to sign-in with any arbitrary email address (for example,
joe@comcast.net, bob@gmail.com, sarah@contoso.com, or jim@live.com). This type of account is a local account.
We also support arbitrary user names as local accounts (for example, joe, bob, sarah, or jim). You can choose one of
these two local account types when configuring identity providers for Azure AD B2C in the Azure portal. In your
Azure AD B2C tenant, select Identity providers, select Local account, and then select Username.
User accounts for applications must always be created through a sign-up user flow, sign-up or sign-in user flow, or
by using the Azure AD Graph API. User accounts created in the Azure portal are only used for administering the
tenant.
Which social identity providers do you support now? Which ones do you plan to support in the future?
We currently support several social identity providers including Amazon, Facebook, GitHub (preview ), Google,
LinkedIn, Microsoft Account (MSA), QQ (preview ), Twitter, WeChat (preview ), and Weibo (preview ). We evaluate
adding support for other popular social identity providers based on customer demand.
Azure AD B2C also supports custom policies. Custom policies allow you to create your own policy for any identity
provider that supports OpenID Connect or SAML. Get started with custom policies by checking out our custom
policy starter pack.
Can I configure scopes to gather more information about consumers from various social identity providers?
No. The default scopes used for our supported set of social identity providers are:
Facebook: email
Google+: email
Microsoft account: openid email profile
Amazon: profile
LinkedIn: r_emailaddress, r_basicprofile
Does my application have to be run on Azure for it work with Azure AD B2C?
No, you can host your application anywhere (in the cloud or on-premises). All it needs to interact with Azure AD
B2C is the ability to send and receive HTTP requests on publicly accessible endpoints.
I have multiple Azure AD B2C tenants. How can I manage them on the Azure portal?
Before opening 'Azure AD B2C' in the left side menu of the Azure portal, you must switch into the directory you
want to manage. Switch directories by clicking your identity in the upper right of the Azure portal, then choose a
directory in the drop down that appears.
How do I customize verification emails (the content and the "From:" field) sent by Azure AD B2C?
You can use the company branding feature to customize the content of verification emails. Specifically, these two
elements of the email can be customized:
Banner logo: Shown at the bottom-right.
Background color: Shown at the top.
The email signature contains the Azure AD B2C tenant's name that you provided when you first created the Azure
AD B2C tenant. You can change the name using these instructions:
1. Sign in to the Azure portal as the Global Administrator.
2. Open the Azure Active Directory blade.
3. Click the Properties tab.
4. Change the Name field.
5. Click Save at the top of the page.
Currently there is no way to change the "From:" field on the email.
How can I migrate my existing user names, passwords, and profiles from my database to Azure AD B2C?
You can use the Azure AD Graph API to write your migration tool. See the User migration guide for details.
What password user flow is used for local accounts in Azure AD B2C?
The Azure AD B2C password user flow for local accounts is based on the policy for Azure AD. Azure AD B2C's
sign-up, sign-up or sign-in and password reset user flows use the "strong" password strength and don't expire any
passwords. Read the Azure AD password policy for more details. For information about account lockouts and
passwords, see Manages threats to resources and data in Azure Active Directory B2C.
Can I use Azure AD Connect to migrate consumer identities that are stored on my on-premises Active Directory
to Azure AD B2C?
No, Azure AD Connect is not designed to work with Azure AD B2C. Consider using the Azure AD Graph API for
user migration. See the User migration guide for details.
Can my app open up Azure AD B2C pages within an iFrame?
No, for security reasons, Azure AD B2C pages cannot be opened within an iFrame. Our service communicates with
the browser to prohibit iFrames. The security community in general and the OAUTH2 specification, recommend
against using iFrames for identity experiences due to the risk of click-jacking.
Does Azure AD B2C work with CRM systems such as Microsoft Dynamics?
Integration with Microsoft Dynamics 365 Portal is available. See Configuring Dynamics 365 Portal to use Azure
AD B2C for authentication.
Does Azure AD B2C work with SharePoint on-premises 2016 or earlier?
Azure AD B2C is not meant for the SharePoint external partner-sharing scenario; see Azure AD B2B instead.
Should I use Azure AD B2C or B2B to manage external identities?
Read this article about external identities to learn more about applying the appropriate features to your external
identity scenarios.
What reporting and auditing features does Azure AD B2C provide? Are they the same as in Azure AD Premium?
No, Azure AD B2C does not support the same set of reports as Azure AD Premium. However there are many
commonalities:
Sign-in reports provide a record of each sign-in with reduced details.
Audit reports include both admin activity as well as application activity.
Usage reports include the number of users, number of logins, and volume of MFA.
Can I localize the UI of pages served by Azure AD B2C? What languages are supported?
Yes, see language customization. We provide translations for 36 languages, and you can override any string to suit
your needs.
Can I use my own URLs on my sign-up and sign-in pages that are served by Azure AD B2C? For instance, can I
change the URL from contoso.b2clogin.com to login.contoso.com?
Not currently. This feature is on our roadmap. Verifying your domain in the Domains tab in the Azure portal does
not accomplish this goal. However, with b2clogin.com, we offer a neutral top level domain, and thus the external
appearance can be implemented without the mention of Microsoft.
How do I delete my Azure AD B2C tenant?
Follow these steps to delete your Azure AD B2C tenant.
You can use the current Applications experience or our new unified App registrations (Preview) experience.
Learn more about the new experience.
Applications
App registrations (Preview )
1. Sign in to the Azure portal as the Subscription Administrator. Use the same work or school account or the same
Microsoft account that you used to sign up for Azure.
2. Select the Directory + subscription filter in the top menu, and then select the directory that contains your
Azure AD B2C tenant.
3. In the left menu, select Azure AD B2C. Or, select All services and search for and select Azure AD B2C.
4. Delete all the User flows (policies) in your Azure AD B2C tenant.
5. Delete all the Applications you registered in your Azure AD B2C tenant.
6. Select Azure Active Directory on the left-hand menu.
7. Under Manage, select Users.
8. Select each user in turn (exclude the Subscription Administrator user you are currently signed in as). Select
Delete at the bottom of the page and select YES when prompted.
9. Under Manage, select App registrations (or App registrations (Legacy)).
10. Select View all applications
11. Select the application named b2c-extensions-app, select Delete, and then select Yes when prompted.
12. Under Manage, select User settings.
13. If present, under LinkedIn account connections, select No, then select Save.
14. Under Manage, select Properties
15. Under Access management for Azure resources, select Yes, and then select Save.
16. Sign out of the Azure portal and then sign back in to refresh your access.
17. Select Azure Active Directory on the left-hand menu.
18. On the Overview page, select Delete directory. Follow the on-screen instructions to complete the process.
Can I get Azure AD B2C as part of Enterprise Mobility Suite?
No, Azure AD B2C is a pay-as-you-go Azure service and is not part of Enterprise Mobility Suite.
How do I report issues with Azure AD B2C?
See File support requests for Azure Active Directory B2C.
Solutions and Training for Azure Active Directory B2C
9/17/2019 • 2 minutes to read • Edit Online
Azure Active Directory B2C (Azure AD B2C ) enables organizations to implement business solutions that help them
connect with their customers. The following solution guides and training are downloadable documents that will
walk you through these solutions.
TITLE DESCRIPTION
Customer Identity Management with Azure AD B2C In this overview of the service, Parakh Jain ( @jainparakh) from
the Azure AD B2C team provides us an overview of how the
service works, and also show how we can quickly connect B2C
to an ASP.NET Core application.
Benefits of using Azure AD B2C Understand the benefits and common scenarios of Azure AD
B2C, and how your application(s) can leverage this CIAM
service.
Gaining Expertise in Azure AD B2C: A Course for Developers This end-to-end course takes developers through a complete
journey on developing applications with Azure AD B2C as the
authentication mechanism. Ten in-depth modules with labs
cover everything from setting up an Azure subscription to
creating custom policies that define the journeys that engage
your customers.
Enabling partners, Suppliers, and Customers to Access Every organization’s success, regardless of its size, industry, or
Applications with Azure active Directory compliance and security posture, relies on organizational
ability to collaborate with other organizations and connect
with customers.
Migrating Application Authentication to Azure AD B2C in a In today’s modern organizations, digital transformation and
Hybrid Environment moving to the cloud happens in stages, requiring most
organizations to at least temporarily operate in a hybrid
identity environment.
General Data protection Regulation (GDPR) Considerations for For any customer facing applications, GDPR must be taken
Customer Facing Applications into consideration by all organizations that embark on projects
that hold personal data and serve EU citizens.
Working with custom policies: This series of documents provides an end-to-end journey with
Custom policies introduction the custom policies in Azure AD B2C, presenting in-depth the
Leverage custom policies in your tenant most common advanced identity scenarios.
Structure policies and manage keys
Bring your own identity and migrate users It includes how to implement and manage custom policies for
these scenarios and how to diagnose them with the available
Troubleshoot policies and audit access
tooling. It also provides an in-depth understanding of how
Deep dive on custom policy schema custom policies work and details how to fine-tune them to
accommodate your own specific requirements.
Azure Active Directory B2C: File Support Requests
9/17/2019 • 2 minutes to read • Edit Online
You can file support requests for Azure Active Directory B2C (Azure AD B2C ) on the Azure portal using the
following steps:
1. Switch from your B2C tenant to another tenant that has an Azure subscription associated with it. Typically,
the latter is your employee tenant or the default tenant created for you when you signed up for an Azure
subscription. To learn more, see how an Azure subscription is related to Azure AD.
IMPORTANT
Don't attempt to sign up for a new Azure subscription in your B2C tenant.