Gaining Expertise With Azure AD B2C Microsoft Master Manual

User Manual:

Open the PDF directly: View PDF PDF.
Page Count: 214 [warning: Documents this large are best viewed by clicking the View PDF Link!]

Microsoft
Identity
Version 1.5, July 2018
Gaining Expertise with
Azure AD B2C
A course for developers
1 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
Contents
About this course ............................................................................................................................................................ 4
Course Elements ......................................................................................................................................................... 5
Course Prerequisites .................................................................................................................................................. 5
Module 0: AAD B2C Environment Setup ................................................................................................................ 6
Introduction .................................................................................................................................................................. 6
Accounts, tenants, and subscriptions ................................................................................................................. 7
Create an Azure Tenant ............................................................................................................................................ 7
Create an Azure co-admin and test user ........................................................................................................... 8
Create a B2C tenant ................................................................................................................................................ 10
Link the B2C Tenant to the Azure Subscription ........................................................................................... 11
Enable the B2CAdmin account to manage the B2C Tenant .................................................................... 12
Make things easy to find ...................................................................................................................................... 13
Create a B2C Test user ........................................................................................................................................... 13
Important Concepts ................................................................................................................................................ 14
Module 1 Using Built in Policies ......................................................................................................................... 15
Introduction ............................................................................................................................................................... 15
Create a Sign-up or Sign-In Policy .................................................................................................................... 16
Create a Password Reset Policy.......................................................................................................................... 19
Update the Password Reset Policy to include Multifactor Authentication ........................................ 21
Create a Profile Editing Policy ............................................................................................................................. 23
Register the Reply URL .......................................................................................................................................... 24
Review the Identity Token Using https://jwt.ms .......................................................................................... 28
Important Concepts ................................................................................................................................................ 31
Module 2 - Using Identity Providers with Azure AD B2C Built in Policies .............................................. 33
Introduction ............................................................................................................................................................... 33
See it in action .......................................................................................................................................................... 33
Setup Social Sign In ................................................................................................................................................ 34
Facebook Social Sign in Configuration Steps ............................................................................................... 36
2 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
Modify the SUSI Policy to Include Facebook ................................................................................................ 37
Test the Facebook SUSI Policy ............................................................................................................................ 38
Important Concepts ................................................................................................................................................ 39
Module 3: Application Integration for a .Net Web App ................................................................................ 40
Introduction ............................................................................................................................................................... 40
Register a Relying Party Application ................................................................................................................ 41
Download the Sample Application and Open it in Visual Studio ......................................................... 43
Edit the Application to Include SISU, Profile Edit and Password Reset Policies .............................. 44
Edit the Application to Add the Tenant ID..................................................................................................... 44
Edit the Application to Include the Client ID and Client Secret ............................................................. 45
Configure the Edit Profile and Reset Password Links ................................................................................ 45
Examine the OWIN Middleware Configuration ............................................................................................ 46
Publish the Sample Application ......................................................................................................................... 48
Test the Deployed Application ........................................................................................................................... 51
Important Concepts ................................................................................................................................................ 51
Module 4: UX Customization using Built-In Functionality ............................................................................ 55
Introduction ............................................................................................................................................................... 56
Customize the HTML Pages Displayed by B2C Policies ............................................................................ 56
Customize Email Messages sent by the B2C App ....................................................................................... 65
Add Localization to Support Spanish-Speaking Users .............................................................................. 67
Modify the Password Complexity of Policies ................................................................................................ 69
Important Concepts ................................................................................................................................................ 71
Module 5: Introduction to Custom Policies ....................................................................................................... 76
Introduction ............................................................................................................................................................... 77
Create a Custom Policy ......................................................................................................................................... 77
Update the Web Application to Reference the New Policies ................................................................. 88
est and Debug a Custom Policy by Using Application Insights ............................................................. 91
Modify the Starter Pack SUSI Policy ................................................................................................................. 94
Important Concepts ................................................................................................................................................ 96
What is IEF? ................................................................................................................................................................ 97
Module 6 Custom Policies 2 REST APIs ...................................................................................................... 105
3 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
Introduction.................................................................................................................................................................. 105
See it in action ........................................................................................................................................................ 105
Prerequisites ............................................................................................................................................................ 105
Step-by-Step Instructions ....................................................................................................................................... 106
Create a custom policy for REST API integration ...................................................................................... 106
Modify the Profile Edit Policy to Return the User Store Membership Date .................................... 122
Module 7External IDPs, OIDC and SAML ...................................................................................................... 130
Introduction ............................................................................................................................................................. 130
Integrate an OIDC IDP and Map Claims ....................................................................................................... 131
Integrate a SAML IDP and Map Claims ......................................................................................................... 139
Module 8: Using the Azure AD Graph API and User Migration ............................................................... 147
Introduction.................................................................................................................................................................. 147
Use the Azure AD Graph API to Query, Add, Update, and Delete Users in AAD .......................... 148
Migrate Users to AAD .......................................................................................................................................... 161
Require Users to Change Password on First Sign-in ................................................................................ 170
Important Concepts .................................................................................................................................................. 186
The Azure AD Graph API and the Microsoft Graph API .......................................................................... 186
Graph Explorer ........................................................................................................................................................ 189
Planning User Migrations ................................................................................................................................... 196
Module 9 Auditing and Reporting ................................................................................................................... 200
Introduction ............................................................................................................................................................. 200
Setup Application Insights ................................................................................................................................. 201
Use Audit logs to Export Application, Policy, and User Activity Data ................................................ 204
Download Data into an Insight/Analytics System ..................................................................................... 205
Auditing Admin and Security Events .............................................................................................................. 209
Accessing Audit Logs through the Azure AD Reporting API ................................................................ 210
4 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
About this course
Welcome to the Gaining Expertise with Azure AD B2C course for developers.
This self-paced course is designed to take you from initial awareness of Azure AD B2C to being
able to create complex user journeys for your customers and leveraging the insights of their
behavior with those journeys to determine how to deepen your organization’s relationship with
those customers.
Each module within the course builds on the previous, and at the end you will have a
working .Net web application that:
Enables customers to log in with local, social, and enterprise accounts.
Enables customers to edit their profiles and reset their own passwords with an MFA
experience.
Has a fully customized UI.
Requests users to accept terms and conditions.
At the end of the course, you will be able to:
Create an Azure AD B2C tenant.
Use built-in (UI-based) policies to
Create sign up, sign in, profile edit, multi-factor authentication, and self-service
password reset journeys.
Add many popular identity providers.
Enable sign in with social accounts.
Customize the User interface.
Use custom policies built in XML to
o Create customized sign up, sign in, profile edit, multi-factor authentication, and
self-service password reset journeys.
o Enable sign in with social accounts
o Enable sign in with any OIDC or OAuth compliant identity provider.
o Enable REST API calls to eternal systems to validate user input.
o Migrate users from other Identity Providers to Azure AD B2C.
o CRUD users using Microsoft Graph.
5 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
Course Elements
In most course modules you will see the following elements:
See it in action. Before you complete most modules, you’ll go to the Awesome
Computers site to see the customer experience you’ll build in the module.
Step-by-step directions. A click-through guide for completing each procedure. We
have included screen shots of virtually every step to guide you.
Important Concepts. An explanation of some of the concepts important to the
procedures in the module, and what happens behind the scenes.
Sample application, policies, and files. A downloadable version of the Awesome
Computers application that you will use throughout course, and other files you will need.
Please go to https://aka.ms/B2CCourse-SampleApp to download all necessary assets.
Course Prerequisites
To be successful in this course, you should be familiar with the following concepts:
What is Azure Active Directory?
What are authentication and authorization?
What is federation?
What is Single sign on?
What are open authentication standards?
o OpenID Connect
o OAuth 2.0
Understanding web site .CSS
6 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
Module 0: AAD B2C Environment Setup
Introduction
At the end of this module, you will be able to:
Set up an Azure Tenant that supports Azure AD B2C
Add a co-admin and a test user to the Azure tenant
Enable the co-admin to manage the B2C tenant
Set up an Azure AD B2C Tenant
Create a test user in the B2C Tenant
8 Link the B2C Tenant to the Azure subscription
And you will have a deeper understanding of the following concepts:
What Azure AD B2C is
What tenants and subscriptions are
When to use Azure AD B2C
This module should take you 30 minutes to complete.
7 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
Accounts, tenants, and subscriptions
In this module you will create an Azure account, which results in an Azure tenant. To create an
Azure Active Directory B2C tenant, your Azure tenant must have a subscription. Azure
subscriptions require a billing method and are pay-as-you go.
Nothing you do in this course should result in any billing to your Azure subscription. The
first 50,000 users in a B2C tenant are free. Be sure, at the end of the course, to follow the
directions for removing any test tenants and accounts from your subscription.
Create an Azure Tenant
If you already have an Azure account with a subscription, you may use that account to create
your B2C tenant for this course, in which case you can skip to you can skip to Create an Azure
co-admin and test user. If you have a free Azure tenant, you can choose to add a subscription to
it, and use that one.
Perform the following steps to create an Azure account, tenant, and subscription
1) Access https://azure.microsoft.com, and select the green Start Free button.
2) On the resulting page, select the Or buy now link, and on the next page select Buy now.
3) Sign in with a Microsoft account, and select No at the Stay signed in? prompt.
you will be using an admin account you create in the next procedure.
4) On the Azure Pay-As-You-Go signup page, enter your contact information and select Next.
5) Verify your identity via phone, enter your payment information, then select Next.
6) Select No technical support, and then select Next.
7) Read the Agreement documents, and then select I agree…, and select Sign up.
8) Select answers to the questions if desired, and select Submit, then on the resultant page,
select Go to the portal.
8 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
Create an Azure co-admin and test user
In this procedure, you create an admin account to use throughout the course, and a test user to
use in later modules. It is always a good idea to have more than one administrator.
Perform the following steps to create your Azure users:
1) Log in to your Azure tenant at https://portal.azure.com
2) In the left navigation, select Azure Active Directory, select Users, then select + New user.
3) In the Name field, enter B2cadmin, and in the User name field, enter
b2cadmin@yourtenantname.onmicrosoft.com.
NOTE: if you have a custom domain name, your tenant will not have the .onmicrosoft
element in the name.
4) Select Directory role, select a role of Global Administrator and select OK.
NOTE: when you create a regular user, you will not need to select OK.
5) Select Show password, copy down the temporary password, and select Create.
9 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
6) Repeat steps 2-5 with the following values to create your test user.
a) Name: Testuser
b) User Name: Testuser@yourtenant.onmicrosoft.com
c) Directory role: User
Your administrator account and test user account now appear in your users list.
10 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
Create a B2C tenant
Perform the following steps to create a new B2C Tenant.
1) In the left navigation of the Azure portal, select Azure Active Directory, then select + Create
a resource at the top of the navigation.
2) In the search box, type B2C, and from the results choose Azure Active Directory B2C.
3) In the window that opens, select Create, then select Create a new Azure AD B2C Tenant.
4) In the Organization name, type Awesome Computers.
5) In the Initial domain name, type AwesomeYourLastName, for example AwesomeJones, and
then select Create.
If AwesomeYourLastName isn’t available, choose another name, such as AwesomeJones22.
The new directory will now be available in the drop down under your sign in name.
11 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
Link the B2C Tenant to the Azure Subscription
In this process, you connect your Azure AD B2C tenant to your Azure subscription.
Perform the following steps to make the connection.
1) In the left navigation of the Azure portal, select Azure Active Directory, then select + Create
a resource at the top of the navigation.
2) In the search box, type B2C, and from the results choose Azure Active Directory B2C.
3) In the window that opens, select Create, then select Link an existing Azure AD B2C Tenant
to my subscription.
4) In the Azure AD B2C Tenant drop down, select your AwesomeYourLastname tenant.
5) Choose an existing resource group or create a new one and select the resource group
location, select the Pin to dashboard check box, and then select Create.
12 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
Enable the B2CAdmin account to manage the B2C Tenant
In this process, you will enable the B2CAdmin account to manage the B2C Tenant.
1) Ensure you are in your Azure Tenant.
2) From the dashboard, select your B2C Tenant, AwesomeYourLastName.
3) In the tenant navigation, select Users.
4) In the resultant window, Select + New guest user.
5) Type the B2CAdmin email B2CAdmin@YourTenantName.onmicrosoft.com, and select Invite.
On the All Users screen, the b2cadmin account will now show with a user type of Guest.
6) Select the link for the user name, and on the b2cadmin properties screen, select Directory
Role, choose a role of Global adminstrator, and select Save.
7) Sign out and sign in with the B2C admin account.
8) Select All Services, Search for B2C, and mark Azure AD B2C as a favorite by selecting the
For the rest of this course, use the B2CAdmin account.
13 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
Make things easy to find
1) In your Azure portal, select All Services, search for B2C, then select the star next to it to add
it to your favorites. It will then appear in your left navigation.
2) Drag Azure AD and Azure AD B2C to the top of your favorites.
Create a B2C Test user
1) In the left navigation select Azure AD B2C, select Users, the select + New user.
2) In the Name field enter B2C Test User.
3) In the User name field, enter b2ctestuser@AwesomeYourlastname.onmicrosoft.com,
and then select the Show Password link, note the password, and select Create.
4)
14 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
Important Concepts
What is Azure AD B2C
Azure AD B2C is a customer identity management system that enables you to abstract the
authentication and authorization functions from your application. Azure AD B2C uses policies to
construct user journeys (or user flows) including sign up, sign in, and profile management.
Azure AD B2C interacts with identity providers, customers, other systems (such as CRM systems)
and a local directory to complete identity tasks.
The underlying platform that establishes multi-party trust and completes these steps is called
the Identity Experience Framework (IEF). This framework and a policy (also called a user journey
or a Trust Framework policy) explicitly defines the actors, the actions, the protocols, and the
sequence of steps to complete. You can find out more about Azure AD B2C here.
When to use Azure AD B2C
Azure AD B2C is best used when you want to sign up and sign in users for web apps, iOS apps,
android apps, single page apps, or desktop apps. It can enable the user journeys discussed
above and can interact with REST APIs to validate information with other systems, such as
validating an address with the postal service, or validating a governmental identity with a
government system.
If you are looking for identity services for enterprise accounts, you should investigate Azure
Active Directory. If you are looking for identity services for partners or suppliers to give them
access to enterprise resources, you should investigate Azure AD B2B collaboration. In B2B, you
invite users into your corporate directory. With Azure AD B2C, users remain external.
Accounts, Tenants, and Subscriptions
An Azure account is created when you sign up for Azure. Creating your Azure account creates
an Azure Tenant, which is accessed by logging in to https://portal.azure.com with the credentials
that you used to create your Azure account. This is the Azure Portal. Inside the portal, you
create and manage different types of user accounts and other resources.
An Azure subscription is a billing agreement you create in conjunction with your Azure
account. Azure subscriptions are usually pay-as-you-go, and you only incur charges for the
services that you use. To create an Azure AD B2C Tenant, your Azure account must have a
subscription.
An Azure AD B2C Tenant is a resource that you create within your Azure tenant.
15 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
Module 1 Using Built in Policies
Introduction
This module introduces you to policies in Azure AD B2C that can be used with Identity Providers,
or IdPs, as part of the user journeys listed below. Policies save you time and effort within your
application so that you do not have to completely write code or create new pages for each user
journey. However, it is still possible to use the extensibility of Azure AD B2C to create custom
pages for each journey if at all desired.
At the end of this module, you will be able to:
Create built-in policies for
o The sign up or sign-in journey.
o The password reset journey.
o The profile edit journey.
And you will have a deeper understanding of the following concepts:
What policies are, and how applications use them.
Claims and attributes and how they are used.
How to view the contents of tokens.
The pros and cons of using multi-factor authentication.
Using policies to facilitate single-sign on among applications.
This module should take you 15 minutes to complete.
See it in action
Before you begin the module, you can experience the end user journeys that you are about to
build.
Go to the Demo site and sign up.
Enter your profile information
o Note: you must use both an email and a phone number to which you have
access.
Edit your profile to add “-1” to your last name.
Reset your password and experience the multi-factor authentication (MFA) experience.
16 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
Create a Sign-up or Sign-In Policy
A sign-up or sign-up policy provides a sign-in and a sign-up user experience with a single policy
configuration. Policies define the user experience and the attributes which are received when a
user signs into an application. The attributes are added as claims to the user token.
Perform the following steps to configure a Sign-up or Sign-in policy in the Azure AD B2C tenant.
1) Sign in to the Azure portal as the B2CAdmin account in your Azure tenant.
2) Select Azure AD B2C in the left navigation.
3) In the Azure AD B2C blade, under the Policies section, select Sign-up or sign-in-policies,
then select + Add.
4) Name the policy SignUpOrSignInPolicy.
5) Select Identity Providers, then select the checkbox for Email signup.
This is for local accounts that are created within the Azure AD B2C tenant.
6) Select OK.
7) Select Sign-up attributes and then select the following attributes. The attributes are
collected as part of a sign-up process.
City
Country/Region
Display Name
Email Address
Given Name
Postal Code
Surname
17 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
8) Select OK.
9) Select Application claims and then select the following application claims.
City
Country/Region
Display Name
Email Addresses
Given Name
Identity Provider
Postal Code
Surname
User is new
User's Object ID
10) Select OK to save the application claims.
11) Select Create to provision the Sign-up or Sign-In Policy.
18 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
When the Policy has been created, the name will be prefixed with B2C_1_.
19 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
Create a Password Reset Policy
You will now create a password reset policy, so that the application can handle password resets
for the local Azure AD B2C tenant user accounts.
Perform the following steps to create the password reset policy.
1) In the Azure AD B2C blade, under the Policies section, select Password reset policies, then
select +Add.
2) Name the policy PasswordResetPolicy.
3) Select Identity Providers, then select Reset password using email address.
4) Select OK.
20 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
5) Select Application claims and then select the following claims. These will be returned to the
application after a successful password reset.
Email Addresses
User’s Object ID
6) Select OK.
7) Select Create to provision the password reset policy.
When the Policy has been created, the name will be prefixed with B2C_1_.
21 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
Update the Password Reset Policy to include Multifactor Authentication
Multifactor Authentication (MFA) can be enabled to secure Azure AD B2C identities.
Perform the following steps to enable MFA on a password reset policy.
1) In the Azure AD B2C blade, under the Policies section, select Password reset policies and
then select the B2C_1_PasswordResetPolicy policy.
2) Select Edit.
3) Select Multifactor authentication.
22 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
4) Toggle the State from Off to On and then select OK.
5) Select Save to save the change to the policy. Ensure that the Multifactor authentication
option displays On.
Multifactor authentication has been enabled on the password reset policy.
6) Close the Edit Policy blade, by selecting the X.
23 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
7) Close the B2C_1_PasswordResetPolicy blade, by selecting the X.
Create a Profile Editing Policy
Profile editing policies allow users to make changes to their profile.
Perform the following steps to enable a profile editing policy.
1) In the Azure AD B2C blade, under the Policies section, select Profile editing policies, then
select + Add.
2) Name the policy ProfileEditPolicy.
3) Select Identity providers, select Local Account SignIn and then select OK.
4) Select Profile attributes, select the attributes shown in the following image, and then select
OK.
24 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
5) Select Application claims, select Email Addresses and User's Object ID, and then select
OK.
6) Select Create in the Add Policy blade.
Register the Reply URL
You can examine the claims present in the identity tokens by using the https://jwt.ms website.
Jwt.ms provides the ability to decode id_tokens and show the claims present within the token.
To utilize jwt.ms, you can either paste in an id_token, or set the reply URL of the application to
https://jwt.ms.
Perform the following steps to update the application reply URL to https://jwt.ms.
1) In the Azure AD B2C blade, under the Manage section select Applications.
25 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
2) Select +Add.
3) In the New application blade, set the Name to Awesome Computers and set Include web
app / web API to Yes.
26 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
4) Set the Reply URL to https://jwt.ms then select Create.
27 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
5) Close the application blade .
28 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
Review the Identity Token Using https://jwt.ms
You can inspect identity tokens by using the page at https://jwt.ms. This site enables you to
review the token, and the decoded token and claims associated with the token that have been
issued by an IdP.
Perform the following steps to update the application reply URL to jwt.ms.
1) In the Azure AD B2C blade, under the Policies section, select Profile editing policies.
2) Select the B2C_1_ProfileEditPolicy which was created earlier.
3) In the profile editing policy blade select Run now. This will launch a browser with the
Run now endpoint URL.
4) Enter the credentials for the b2cTestUser@AwesomeYourLastname.onmicrosoft.com
that you created in the pre-module, and then select Sign in.
5) If this is the first time you have logged into the tenant with the test user account, you will
be asked to update your password. Enter the current password, new password and
confirm the new password, then select Sign in.
6) After successfully authenticating, you will need to complete the user profile fields as the
Sign-in and Sign-up policy enforces the capturing of profile information. Enter the details
29 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
as desired for the user profile then select Continue.
7) After successfully authenticating, you will be re-directed to https://jwt.ms which is the
reply URL for the application. This is the URL where all tokens are returned, by the Azure
AD B2C OAuth 2.0 endpoint.
8) Inspect the decoded token and claims in https://jwt.ms.
Token
30 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
Decoded Token
Claims
31 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
Important Concepts
Unique IDs for Applications
Each application registered in an Azure AD or Azure AD B2C tenant has a unique application ID
which is utilized as part of the trust mechanisms built into the Azure AD authentication libraries.
Applications contain unique IDs and secrets, which are used in applications to ensure that they
are authorized to request tokens from Azure AD tenants.
What are built in policies
Built in policies provide the user experience and are associated with IdPs and applications for
various user journeys. These include Sign up, Sign In, Password Resets and Profile Editing
policies. Policies can be applied to multiple IdPs and applications that are registered in Azure AD
B2C which makes the development effort faster, reducing the time you need to spend on coding
the user journeys.
Policies are important to ensure that the right user attributes are captured as part of the sign up
or sign in process and are flexible enough so that you can add custom attributes too. Policies
also allow you to control the look and feel of the user journeys and also enforce Multi Factor
Authentication.
How do policies work
Policies you define are associated with one or more IdPs. When your application leverages Azure
AD B2C, the policies will determine the behavior when a user authenticates to the IdP. When
the token from the IdP is validated by Azure AD B2C, ensuring the signature is trusted, Azure AD
B2C then uses a policy specified in the Azure AD B2C tenant for the specific IdP and application.
How applications use policies
Applications receive user id_tokens to make authorization decisions. Users attributes, which may
be collected during a sign up or sign in policy, are used as claims that are present in the
id_token. Applications can then utilize the claims in the id_token, to understand the user in more
detail e.g. a claim can be used to expose different UI elements based on a role associated with a
user’s claims, which are taken from attributes.
What are attributes and claims
Attributes are pieces of information which are tied to a user profile. You may want to collect
specific attributes as part of a sign up or sign in policy to ensure that you have collected the
necessary information for the application you are developing. Users will be presented with a
form, for each user journey, to ensure that the attributes are collected as part of the initial sign
up or sign in process.
Attributes of a user can be added to the user’s claims, which is essentially updating the user’s
id_token through the policies, when they are authenticated by Azure AD B2C which be utilized
across different applications.
32 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
Using policies for SSO across applications
Multiple applications within a tenant may use the same policies, which can result in Single Sign-
on (SSO) to all the applications to which the user has access. By default, the configuration is set
at the tenant level, which means that multiple applications can share the same user session. This
means that once the user is authenticated to an application, the user can access multiple
applications registered in the same Azure AD B2C tenant, without having to follow a user
journey or be re-directed for authentication credentials.
For further information, see Azure Active Directory B2C: Token, session and single sign-on configuration.
Pros and cons of using MFA
Multi-factor authentication (MFA) increases security, and also increases the friction a user
experiences in their journey by adding more steps. You should use it in situations where you feel
increased security is paramount. There is also a cost to using MFA. While minimal, if you plan to
scale to tens or hundreds of thousands of users, you should consider the impact of MFA
scenarios.
33 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
Module 2 - Using Identity Providers with Azure AD B2C Built in Policies
Introduction
This module introduces you to IdPs and provide you with the steps to federate with Facebook
using Azure AD B2C. You will learn how to add Facebook as an identity provider and set up
Facebook federation with an Azure AD B2C tenant.
At the end of this module, you will be able to:
Register a Facebook developer account.
Create a Facebook application.
Create an Azure AD B2C Identity Provider.
And, you will have a deeper understanding of the following concepts:
Identity Providers and federation
Authentication protocols supported by Azure AD B2C
This module should take approximately 15 minutes to complete.
See it in action
Before you begin the module, you can experience the end user journeys that you are about to
build at https://aka.ms/b2ccourse-2.
34 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
Setup Social Sign In
Prerequisites
You must have an account in the Facebook for developers website, prior to implementing this
task. The following steps show how to setup an application in the Facebook for developers
website.
Setup the Facebook Application
1) Open a browser and navigate to https://developers.facebook.com/, enter your account
details, and select Login.
2) If you do not have a current Facebook for developers account, select Create New
Account then enter the details as requested.
3) Navigate to https://developers.facebook.com/, select My Apps, and then select Add a
New App.
4) Enter the application Display Name and a Contact Email address.
5) Select Create App ID.
6) If you receive a Security Check message, enter the code on the screen in the box
provided and then select submit.
7) When you are shown the Add a Product page, note down the App ID as this will be
required for the configuration steps in the next set of tasks. Ensure that you handle this
information securely.
8) Click Settings in the left navigation pane and then click Basic.
35 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
9) Select + Add Platform and then select Website.
10) In the Site URL field, enter https://login.microsoftonline.com/.
11) In the Privacy Policy URL, enter https://privacy.microsoft.com, then select Save
Changes.
12) In the App Secret section of the page, Click Show to reveal the App Secret. You may
have to re-enter your password to complete this step.
13) Copy the App Secret when it is display on the page. Ensure that you handle this
information securely.
14) Click in the left-hand navigation pane, and then select Set Up, under the
Facebook Login section.
36 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
15) Under Facebook Login, in the left-hand navigation pane, select Settings.
16) In the Valid OAuth Redirect URIs field, enter
https://login.microsoftonline.com/te/AwesomeYourLastname.onmicrosoft.com/oauth2/au
thresp, and then select Save Changes.
17) Select App Review in the left-hand navigation pane, and then toggle the Make the App
Public option from No to Yes.
Facebook Social Sign in Configuration Steps
Follow the steps below to configure Social Sign In, by adding an Identity Provider (IdP) within
your Azure AD B2C tenant.
1) Log in to the Azure portal as B2CAdmin in your Azure tenant, and then switch to the
AwesomeYourLastname.onmicrosoft.com B2C tenant, where
AwesomeYourLastname is the name of your B2C tenant, and then select Save
Changes.
2) Go to your Azure tenant. Select All services, in the Filter box enter B2C, and then select
Azure AD B2C.
3) In the Azure AD B2C blade, under the Manage section, select Identity Providers.
4) Select +Add.
5) In the Add identity provider blade, in the Name field, enter Facebook, and then select
Identity provider type.
6) In the Select social identity provider blade, select Facebook, and then select OK.
7) In the Add identity provider blade, select Set up this identity provider.
8) In the Set up this social identity provider blade, enter the Client ID (the Facebook App
ID) and Secret that was configured in the Facebook for developers website, and then
select OK.
9) In the Add Identity Provider blade, select Create.
10) You will be re-directed back to the Azure AD B2C Identity Providers blade. This blade
should now show the Facebook Social Identity Provider which you have just created.
11) Ensure that Local Accounts is set to Email.
37 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
References
The following references are provided for detailed steps to integrate additional IdPs with Azure
AD B2C.
IdP
Reference
Microsoft
Accounts
Azure Active Directory B2C: Provide sign-up and sign-in to consumers with
Microsoft accounts
Facebook
Accounts
Azure Active Directory B2C: Provide sign-up and sign-in to consumers with
Facebook accounts
Google+
Accounts
Azure Active Directory B2C: Provide sign-up and sign-in to consumers with
Google+ accounts
Amazon Accounts
Azure Active Directory B2C: Provide sign-up and sign-in to consumers with
Amazon accounts
LinkedIn
Accounts
Azure Active Directory B2C: Provide sign-up and sign-in to consumers with
LinkedIn accounts
Twitter
Azure Active Directory B2C: Provide sign-up and sign-in to consumers with
Twitter accounts
GitHub
Azure Active Directory B2C: Provide sign-up and sign-in to consumers with
GitHub accounts
Weibo
Azure Active Directory B2C: Provide sign-up and sign-in to consumers with
Weibo accounts
QQ
Azure Active Directory B2C: Provide sign-up and sign-in to consumers with
QQ accounts
WeChat
Azure Active Directory B2C: Provide sign-up and sign-in to consumers with
WeChat accounts
Modify the SUSI Policy to Include Facebook
Azure AD B2C has an extensive policy framework which provides the consumer identity
experience and profile editing options. Azure AD B2C includes sign-up and sign-in policies that
can be used across registered applications. It is recommended that you use a sign-up or sign-in
policy.
Follow the steps below to add the Facebook IdPs to the policies.
1) In the Azure AD B2C blade, under the Policies section, select Sign-up or sign-in-
policies, and then select +Add.
38 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
2) In the Add policy blade, type ADandFacebookSignUporSignInPolicy in the Name field,
select Identity providers, select Facebook, and then select OK.
3) In the Add policy blade, select Sign-up attributes.
4) In the Sign-up attributes blade, select Display Name, Email Address, Given Name,
and Surname, and then select OK.
5) In the Add policy blade, select Application claims.
6) In the Select application claims blade, select Display Name, Email Address, Given
Name, Identity Provider, Surname, and User’s Object ID, and then select OK.
7) In the Add policy blade, leave Multi-Factor Authentication set to Off, and then select
Create.
Test the Facebook SUSI Policy
1) In the Azure AD B2C blade, under the Policies section, select Sign-up or sign-in
policies.
2) Select the B2C_1_ADandFacebookSignUporSignInPolicy.
3) Select Run now. The Facebook sign-in page should appear.
4) Log in using your Facebook account. The jwt.ms page should appear, displaying the
identity token and claims returned Facebook.
39 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
5) Click Claims, and verify that the Display Name (name), Email Address (emails), Given
Name (given_name), Identity Provider (idp), Surname (family_name), and User’s
Object ID (oid) are all listed.
Important Concepts
What are IdPs?
An Identity Provider’s primary purpose is to store information for user or system principals that
has its own mechanisms to provide authentication to a known subject. A subject can be referred
to as a user identity. A typical example of an identity provider is Azure AD; it encompasses user
identities, groups and various pieces of information for each object it stores. For example, Azure
AD provides authentication services to Office 365 and each Office 365 application relies on
Azure AD to provide a user identity token, using common authentication protocols.
Authentication occurs at the IdP and authorization occurs within an application.
What protocols does Azure AD B2C support?
A token that is signed by a trusted IdP is provided to Azure AD B2C, utilizing one of the
following authentication protocols which are supported by Azure AD B2C.
OAuth 2.0
Open ID Connect (OIDC)
SAML 2.0
A user ID token or application token, also referred to as am App token, is provided by Azure AD
B2C to an application, which provides an authentication context for the user or application
respectively. Applications can utilize claims, based on the identity, present within the token e.g.
to make decisions on what the users role is within the application.
40 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
Module 3: Application Integration for a .Net Web App
Introduction
In this module, you will download the sample web application and configure it to utilize your
Azure AD B2C tenant and policies created in Module 1. You will then publish the application and
examine the claims associated with an id_token. The web application itself is very simple; all it
does is configure the OWIN middleware that implements the OAuth 2.0 authentication protocol
to integrate with your Azure AD B2C policies, and then display the resulting identity token when
the user has connected.
At the end of this module, you will have registered an application, edited the application to
incorporate policies, and edited the authorization token path.
And, you will have a deeper understanding of the following concepts:
1. How to register a relying party application
2. How to configure an application to utilize Azure AD B2C policies
3. Installing OWIN Middleware
4. Examine claims using jwt.ms
5. This module should take approximately 45 minutes to complete.
41 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
Register a Relying Party Application
A relying party application is required within the Azure AD B2C tenant so that it is authorized to
retrieve tokens from the Azure AD B2C tenant. The relying party application has several
important pieces of information that describe the application so that it can be integrated with
the Azure AD B2C tenant. The information that is required to register the relying party
application has been listed below.
Name the name of the application
Application Type Web app / API or a Native application
Sign-on URL A URL where users will sign into the application
Follow the steps below to configure a relying party application in the Azure AD B2C tenant.
1) Log in to the Azure portal as B2CAdmin.
2) Switch to the AwesomeYourLastname.onmicrosoft.com directory to access your B2C
tenant.
3) Select Azure AD B2C from your favorites.
4) In the Azure AD B2C blade, in the Manage section, select Applications.
5) Select the Awesome Computers application.
6) Make a note of the Application ID. You will need this when you configure the sample web
application later.
42 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
7) Change the Reply URL to https://AwesomeYourLastname.azurewebsites.net. This is the
URL that you will to deploy the sample web application. Note that if you deploy the web
application to a different location, you must remember to update this URL for the
application.
8) You need to create an application secret to enable B2C to integrate with your web app.
Select Keys, and then select Generate Key.
9) Select Save and note down the App key value. You will reference this key later in the
web.config file for the sample application.
43 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
You must continue to manage the application in the Azure Portal, not with PowerShell. For
example, if you edit the application registered in an Azure B2C tenant using the Azure Portal,
subsequently managing the application with PowerShell is unsupported. For further
information, see Azure Active Directory B2C: Register your application, faulted apps section.
Download the Sample Application and Open it in Visual Studio
Follow the steps below to download the sample application to the local C:\B2Course-
SampleApp folder. This sample application will be used throughout the course.
1) Navigate to the following URL to download the sample application.
https://github.com/Azure-Samples/active-directory-b2c-training-course.
Note, download all the assets at this site as you will need them throughout the course.
2) If your browser shows a popup message to provide permissions to download the file, select
OK. If you opened the above URL in PDF, select Open.
3) Select the downloaded zip file in the browser to open the zip file contents.
4) Right-click the folder in the zip file and select Copy.
5) Navigate to the [C:\B2Course-SampleApp] folder, right-click in the explorer window and
then select Paste. The contents of the solution from the zip file will be copied into the folder.
6) Start Visual Studio and open the B2C-WebAPI-DotNet.sln solution in the C:\B2Course-
SampleApp\MsftBuild2018.AwesomeComputers_Before folder.
7) Select OK to the security warning. A sample of the security warning is shown below.
I
44 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
Edit the Application to Include SISU, Profile Edit and Password Reset Policies
1. In Solution Explorer, in the AwesomeComputers project, select the Web.config file.
2. In the <appSettings> section of the file, replace the placeholders for the
SignInSignUpPolicyId, EditProfilePolicyId, and ResetPasswordPolicyId settings with
the names of the policies you created in module 1, as follows:
<configuration>
<appSettings>
...
<add key="ida:SignUpSignInPolicyId" value="B2C_1_SignUpOrSignInPolicy" />
<add key="ida:EditProfilePolicyId" value="B2C_1_ProfileEditPolicy" />
<add key="ida:ResetPasswordPolicyId" value="B2C_1_PasswordResetPolicy" />
</appSettings>
</configuration>
3. Replace the value of the RedirectUri setting with the URL that you specified when you
registered the application in the Azure portal,
https://AwesomeYourLastname.azurewebsites.net.
<configuration>
<appSettings>
...
<add key="ida: RedirectUri" value=" https://AwesomeYourLastname.azurewebsites.net" />
...
</appSettings>
</configuration>
4. Save the file.
Edit the Application to Add the Tenant ID
In the web.config file, update the app setting for the Tenant to reference the tenant ID for
your Azure AD B2C tenant. Replace AwesomeComputers with the name of your B2C tenant:
<configuration>
<appSettings>
<add key="ida:Tenant" value="AwesomeYourLastname.onmicrosoft.com" />
...
</appSettings>
</configuration>
45 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
Edit the Application to Include the Client ID and Client Secret
In the web.config file, update the app setting for the ClientId and specify the app id and app
secret that you generated earlier using the Azure portal.
<configuration>
<appSettings>
...
<add key="ida:ClientId" value="ApplicationId" />
<add key="ida:ClientSecret" value="ApplicationSecret"/>
...
</appSettings>
</configuration>
Note: The generated client secret may require escape characters to be correctly parsed in the
web.config (XML). Use an XML escape tool such as https://www.freeformatter.com/xml-
escape.html#ad-output to escape any special characters. In a production scenario, escape these
characters manually or generate your own secret using powershell.
Configure the Edit Profile and Reset Password Links
The web application includes links that enable the user to edit their profile and reset their
password. However, to keep the code straightforward, these links are hardcoded into the user
interface, and by default reference a version of the application running in the AADB2CTraining
domain. You should modify these links to reference your own web application.
1) In Solution Explorer, in the AwesomeComputers project, expand the Shared folder, expand
the Home folder, and then select the _LoginPartial.cshtml file.
2) In the _LoginPartial.cshtml file, modify the two <a> elements as follows. Replace
AwesomeYourLastname with the name of your Azure AD B2C tenant, and specify the value
that you added to the web.config file for the ClientID:
<ul class="nav navbar-nav navbar-right">
<li>
<a
href="https://login.microsoftonline.com/AwesomeYourLastname.onmicrosoft.com/oauth2/
v2.0/authorize?p=B2C_1_ProfileEditPolicy&client_id=ClientID&nonce=defaultNonce&redi
rect_uri=https%3A%2F%2FAwesomeYourLastname.azurewebsites.net&scope=openid&res
ponse_type=id_token">
Edit Profile
</a>
46 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
</li>
<li>
<a
href="https://login.microsoftonline.com/AwesomeYourLastname.onmicrosoft.com/oauth2/
v2.0/authorize?p=B2C_1_PasswordResetPolicy&client_id=ClientID&nonce=defaultNonce
&redirect_uri=https%3A%2F%2FAwesomeYourLastname.azurewebsites.net&scope=openid
&response_type=id_token">
Reset Password
</a>
</li>
</ul>
3) Save the file.
Examine the OWIN Middleware Configuration
4) In Solution Explorer, in the AwesomeComputers project, expand the App_Start folder, and
then select the Startup_Auth.cs file. This file contains the code that configures the OWIN
middleware when the web application starts running.
5) Examine the ConfigAuth method. This is the code that initializes the OWIN middleware:
public void ConfigureAuth(IAppBuilder app)
{
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationTyp
e);
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions
{
// Generate the metadata address using the tenant and policy information
47 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
MetadataAddress = String.Format(AadInstance, Tenant, DefaultPolicy),
// These are standard OpenID Connect parameters, with values pulled from
web.config
ClientId = ClientId,
RedirectUri = RedirectUri,
PostLogoutRedirectUri = RedirectUri,
// Specify the callbacks for each type of notifications
Notifications = new OpenIdConnectAuthenticationNotifications
{
RedirectToIdentityProvider = OnRedirectToIdentityProvider,
AuthorizationCodeReceived = OnAuthorizationCodeReceived,
AuthenticationFailed = OnAuthenticationFailed,
},
// Specify the claim type that specifies the Name property.
TokenValidationParameters = new TokenValidationParameters
{
NameClaimType = "name"
},
// Specify the scope by appending all of the scopes requested into one string
(separated by a blank space)
Scope = $"openid profile offline_access"
}
);
}
48 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
6) The remaining methods in the file, OnRedirectToIdentityProvider,
OnAuthenticationFailed, and OnAuthorizationCodeReceived are handlers that respond to
authentication and authorization events raised by the OWIN middleware. Note that the
OnAuthenticationFailed method also handles password resets.
Publish the Sample Application
Follow the steps below to publish the application to the Azure Web App.
7) In Solution Explorer, right-click the AwesomeComputers project, then select Publish.
8) Select Create new profile.
9) In the Pick a publish target dialog box, select App Service, select Create New, and then
select Publish.
49 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
10) In the Create App Service dialog box, connect to your Azure tenant as the B2CAdmin
account, and specify the name of your app (AwesomeYourLastname).
11) Select New to create new resource group and name it AwesomeComputersApp.
12) Select New, next to the App Service Plan field.
50 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
13) In the Configure Hosting Plan dialog box,
a. enter AwesomeComputersAppServicePlan for the App Service Plan Name.
b. Select your location.
c. Select B1 (1 core, 1.75 GB RAM) for the size, and then select OK.
14) In the Create App Service dialog box, select Create.
15) Publish the Application by selecting "Publish":
16) Wait while application is deployed.
17) Ensure the build has succeeded and the Web App was published successfully. You should
see messages similar to the following in the Output window of Visual Studio.
51 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
18) When the application has deployed, it will launch in the browser and display the sign-in
page. Do not sign in yet, just close the browser window.
Test the Deployed Application
1) In a web browser, navigate to your app web address,
https://AwesomeYourLastname.azurewebsites.net.
2) In the sign-in page, log in as TestUser@AwesomeYourLastname.onmicrosoft.com.
3) Verify that you are signed in successfully. You should see the following page.
5. Select View Token Contents. You will be presented with a page generated by using the web
site at https://jwt.ms which you used in Module 1 to display the identity token for the signed-
in user.
Note: If you select Back To B2C Training, you will be taken to the aadb2ctraining web site.
6. Select Claims, and view the claims passed to the web app by the SUSI policy.
Important Concepts
Authentication Flows for Web Apps
There are several common authentication flows for web apps and APIs. They are:
52 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
1) A user authenticating to a web application.
2) A user authenticating to a web API.
3) An application authenticating to a web API on behalf of a user using a confidential client.
4) A service authenticating to another service (service to service).
5) A mobile or native application authenticating to a web API.
For whichever scenario you need to develop, please see Azure Active Directory B2C: Types of
applications for further information.
53 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
Claims and Tokens Overview
The user id_token, which is issued by Azure AD B2C, contains claims that provide web apps and
APIs important information that can be used to make authorization decisions in applications
and/or surface different user interface elements or text specific to a user. The id_token is
essentially a security token that is signed by the Azure AD B2C tenant as part of the
authentication flow. Azure AD issues an id_token, the application utilizes the token with Open ID
Connect.
Bearer tokens are also security tokens that provide the bearer access to resources such as an
API. These are presented to a resource and the resource determines if the bearer token is
trusted and valid for use as part of a request. You must ensure that all tokens are transmitted
securely.
Access tokens and refresh tokens are also provided by Azure AD B2C, and have claims present
to authorize access to APIs. When an API receives an access token it must validate the access
token before authorizing the use of the access token. Refresh tokens are used to request a new
access token as the access token lifetime is limited and configurable within Azure AD B2C.
For further information, see Azure AD B2C: Token reference.
Incorporating Azure AD B2C into existing applications
To incorporate Azure AD B2C into existing applications you need to perform the following steps:
1) Ensure the application is registered in the Azure AD B2C tenant so that the application
can receive tokens, and ensure the reply url is set to the application authorization path.
2) Integrate Azure AD authentication, MSAL Libraries, and Open ID Connect middleware
into the application project.
3) Change the configuration files to include the following information:
a) Azure AD B2C tenant ID.
b) Application ID and secret
c) Azure AD B2C policy names which you intend to use in the application
d) Handle the Azure AD B2C notifications
e) Ensure that the application has the correct permissions to any resources i.e. Azure AD
B2C permissions to read directory data
54 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
Azure AD V1 vs V2 Endpoints
Azure AD provides a v1 and v2 endpoint which utilizes OAuth 2.0 to issue JSON Web Tokens. It
is important to understand the differences between both endpoints and the limitations. The v1
endpoints are commonly access using the Active Directory Authentication Library for work or
school accounts. The v2 endpoint is utilized using the Microsoft Authentication Library and
provides integration with Azure AD B2C and thus provides access to any IdP supported by Azure
AD B2C, which includes all the IdPs referenced in Module 1.
For further information, see What's different about the v2.0 endpoint?
55 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
Module 4: UX Customization using Built-In Functionality
At the end of this module, you will be able to:
Customize the HTML pages displayed by B2C policies.
Modify the style of email messages sent by B2C policies to match the corporate design.
Localize the HTML content generated by B2C policies.
And, you will have a deeper understanding of the following concepts;
Customized Azure AD domains.
Built-in localization strings used by B2C policies.
This module should take approximately 40 minutes to complete.
56 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
Introduction
In this module, you will customize the user experience of the policies implemented by your
Azure AD B2C application to match the corporate look and feel of the Awesome Computers
organization. You will also add localization to the policies to support Spanish-speaking users,
and you will increase the password complexity requirements for users to make the application
more robust to attack.
See the end user experience you are about to build.
In the demonstration site, you will perform the following tasks:
Login on the customized screen.
At the end of this module, you will be able to:
Customize the HTML pages displayed by B2C policies. To achieve this, you will:
a. Create a storage account for holding customized content.
b. Create HTML content for the Profile Edit policy and the SUSI policy.
c. Upload the HTML content to blob storage
d. Update the SUSI and Profile Edit policies.
Customize email messages sent by the B2C app.
Add localization to support Spanish-speaking users.
Modify the password complexity of policies.
Customize the HTML Pages Displayed by B2C Policies
You can customize the Azure AD B2C user interface to match the look and feel of your existing
applications and provide a seamless experience to users. Specifically, you can customize the
pages that appear in response to the SUSI, sign-up, sign-in, profile editing, and password reset
policies.
To customize the interface, you provide the HTML5 content in the form of HTML fragments and
CSS styling. The content includes placeholders where Azure AD B2C-specific content is
generated and inserted when the policies run. You save your HTML5 content to a convenient
and accessible location, and provide the URL of this content to your policies; different policies
can reference different HTML fragments. At run-time, the policy retrieves your content and
merges it with content that it generates for the placeholders. Note that the site that hosts your
content should expose an HTTPS endpoint with Cross-Origin Resource Sharing (CORS) enabled.
The GET and OPTIONS request methods must both allow CORS.
57 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
Follow these steps to create a custom HTML page, upload it to the cloud, and associate it with a
policy in the Azure AD B2C tenant.
Create a Storage Account for Holding Customized Content:
Note: This series of steps uses Azure Blob Storage to hold the HTML content, but you can
host this material anywhere that is accessible to Azure AD B2C. This includes publicly
accessible web servers, CDNs, AWS S3, and file servers. The prime requirements are that the
content is accessible through HTTPS and CORS has been enabled.
1) Log in to the Azure portal as the B2CAdmin account in your Azure tenant. Do not log
into the domain for the B2C tenant.
2) Select Create a resource, type Blob Storage in the search field, and then select Storage
account blob, file, table, queue.
3) In the Storage account blob, file, table, queue blade, select Create.
4) In the Create storage account blade, specify the following settings and then select
Create.
Name: A unique name for the storage account. For example,
AwesomeYourlastnameUX
Account kind: Blob storage
Accept the default values for the remaining settings (create a new resource group
for the storage account if required)
5) When the storage account has been created, select All resources, and then select the
new storage account.
6) In the Services section of the blade, select Blobs.
7) In the Blob service blade, select +Container.
8) Add a container with a convenient name, such as b2c, set the Public access level to
Blob, and then select OK.
58 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
9) Return to the blade for the storage account, and then select Access keys. Make a note of
the value of key1.
Create HTML Content for the Profile Edit Policy and the SUSI Policy
1) On your computer, create a new folder named PolicyUX under the B2Course-
SampleApp folder. Copy the subfolders named css, images, and fonts and their content
from the ui-customizations folder under the sample app to the PolicyUX folder.
2) Using Visual Studio, create a custom HTML5 page for the Profile Edit policy, as follows.
a. Replace the URLs highlighted in bold with the address of the blob storage
container you created earlier.
b. Name the file updateprofile.html, and save it in the PolicyUX folder you created
in the previous step.
<!DOCTYPE html>
<html>
<head>
<title>Update Profile</title>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- TODO: favicon -->
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"
rel="stylesheet" type="text/css" />
<link
href="https://awesomeyoursurnameb2cux.blob.core.windows.net/b2c/css/global.css"
rel="stylesheet" type="text/css" />
</head>
<body>
<div class="container self_asserted_container">
<div class="row">
<div class="col-md-6 col-md-offset-3 col-sm-8 col-sm-offset-2">
59 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
<div class="panel panel-default">
<div class="panel-body">
<div class="image-center">
<img alt="Awesome Computers" class="login-logo"
src="https://AwesomeYourLastnameUX.blob.core.windows.net/b2c/images/logo
.png" />
</div>
<h3 class="text-center">Update your current profile</h3>
<div id="api" data-name="SelfAsserted">
</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
The page references a style sheet and image files that provide a corporate look and feel that
matches the styling used by other applications published by Awesome Computers. You will
upload the CSS and image files to blob storage. Note that the URLs for these items reference
the container you created in the previous step.
The <div> highlighted in bold is the placeholder that will be replaced with content generated
by the policy at runtime. It is important to set the id attribute of this section to api. The content
generated by the policy uses a set of specific HTML class and id attributes. These attributes are
documented online at https://docs.microsoft.com/azure/active-directory-b2c/active-directory-b2c-
reference-ui-customization. The css file contains styles that modify the way in which elements in
this content are displayed.
3) Create another HTML page for customizing the SUSI user experience. Again, specify the
URLs for your blob storage account where highlighted. Save this page in the same folder,
and name it unified.html. Again, notice that this page includes a <div> named api.
60 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
<!DOCTYPE html>
<html>
<head>
<title>Sign in</title>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- TODO: favicon -->
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"
rel="stylesheet" type="text/css" />
<link href="https://AwesomeYourLastnameUX.blob.core.windows.net/b2c/css/global.css"
rel="stylesheet" type="text/css" />
</head>
<body>
<div class="container unified_container">
<div class="row">
<div class="col-md-6 col-md-offset-3 col-sm-8 col-sm-offset-2">
<div class="panel panel-default">
<div class="panel-body">
<div class="image-center">
<img alt="Awesome Computers" class="login-logo"
src="https://AwesomeYourLastnameUX.blob.core.windows.net/b2c/images/logo.png" />
</div>
<h3 class="text-center">Sign in with your existing account</h3>
<div id="api" data-name="Unified">
</div>
</div>
</div>
61 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
</div>
</div>
</div>
</body>
</html>
Upload the HTML Content to Blob Storage
1) On your desktop computer, download the Azure Blob Storage helper tool from
https://github.com/azureadquickstarts/b2c-azureblobstorage-
client/raw/master/B2CAzureStorageClient.zip. Extract this archive into a convenient folder.
2) Run the B2CAzureStorageClient.exe utility extracted from the archive. You use this
utility to upload the HTML files and content that implement the customized user
interface. At the prompt, enter the following details:
a. The name of the storage account. For example, awesomecomputersb2cux.
b. The value of key1, the access key for the storage account, recorded earlier.
c. The name of the storage container you created earlier. For example, b2c.
d. The folder on your computer that contains the customized HTML pages,
including the subfolders holding the css and image files. For example, B2Course-
SampleApp\PolicyUX.
3) Verify that the pages were uploaded correctly, and that a message appears indicating
that the CORS policy has been set.
62 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
4) You can test the page by using a Web browser; navigate to the URL https://<storage
account name>.blob.core.windows.net/<container>/<page>.html, where <storage
account name> is the name of your storage account (awesomecomputersb2cux),
<container> is the name of the blob container (b2c), and page is the name of either of
the HTML files you uploaded (updateprofile.html or unified.html)
Update the SUSI and Profile Edit Policies
Once you have created and uploaded the HTML pages that define the user interface for a set of
policies, you can modify each policy to reference the appropriate page.
1) In the Azure portal, switch to the AwesomeYourLastname.onmicrosoft.com B2C tenant.
2) Select Azure AD BC from your favorites.
63 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
3) In the Policies section of the Azure AD B2C blade, select Sign-up or sign-in policies, and then
select B2C_1_SignUporSignInPolicy.In the SIGN-UP OR SIGN-IN POLICY blade, select Edit,
and then in the EDIT POLICY blade, select Page UI customization.
4) In the Page UI customization blade, select Unified sign-up or sign-in page. Set Use
custom page to Yes, and then enter the URI of the unified.html page you uploaded to blob
storage; https://<storage account
name>.blob.core.windows.net/<container>/unified.html
5) In the Unified sign-up or sign-in page blade, select OK.
6) In the Page UI customization blade, select OK.
7) In the Edit policy blade, select Save.
8) In the Policies section of the Azure AD B2C blade, select Profile editing policies, and then
select B2C_1_ProfileEditPolicy.
9) In the PROFILE EDITING POLICY blade, select Edit, and then in the EDIT POLICY blade, select
Page UI customization.
10) In the Page UI customization blade, select Profile Edit page. In the Profile Edit page blade,
set Use custom page to Yes, and then enter the URI of the profileedit.html page you
uploaded to blob storage: https://<storage account
name>.blob.core.windows.net/<container>/updateprofile.html
64 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
11) In the Profile Edit page blade, select OK.
12) In the Page UI customization blade, select OK.
13) In the Edit policy blade, select Save.
14) Return to the B2C_1_SignUpOrSignInPolicy, and in the B2C_1_SignUpOrSignInPolicy blade,
select Run now.
15) Verify that the sign-in page for the application appears. It should display the styling and
images specified by the unified.html page:
.
16) Sign in as TestUser@AwesomeYourLastname.onmicrosoft.com.
17) When the Awesome Computers page appears, select Edit Profile at the top of the page.
18) Verify that the customized version of the update profile page for the application appears:
65 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
19) Close the update profile page and return to the Azure portal.
Customize Email Messages sent by the B2C App
When a user signs up or needs to reset their password, Azure AD B2C responds by sending
emails containing confirmation codes to the user's registered email address. These emails have a
default style, but you can use the Azure AD company branding feature to modify features such
as the logo displayed at the bottom of the email, the signature, and the background color of the
banner displayed at the top. The following steps show how to perform these tasks.
1) In the Azure portal, select Azure Active Directory.
2) Select Company branding, and then select Configure.
3) In the background image box, specify the name of the image file provided with the
sample application, B2CCourse-SampleApp\ui-
customizations\images\background_web.jpg.
4) In the Banner logo box, specify the name of the logo file provided with the sample
application, B2CCourse-SampleApp\ui-customizations\images\logo_small.jpg.
66 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
5) Set the background color to #A9CBFF, select Save, and then close the Edit company
branding blade.
6) In the Azure Active Directory blade, select Properties. In the Properties blade, in the
Name box enter Awesome Computers, and then select Save.
7) Select Azure AD BC from your favorites.
8) In the Policies section of the Azure AD B2C blade, select Password reset policies, and
then select B2C_1_PasswordResetPolicy.
9) In the PASSWORD RESET POLICY blade, select Run Now.
10) In the verification page, enter the email address associated with your account, and then
select Send verification code.
11) When you receive the verification email, note that it has been branded with the color,
logo, and domain name.
67 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
Add Localization to Support Spanish-Speaking Users
Localization enables Azure AD B2C to present the HTML pages displayed by your application
policies in the language most appropriate to the user and their location. The language to use is
passed as a parameter in the HTTP requests sent to Azure AD B2C.
Azure AD B2C provides automatic translation of the HTML content that it generates, depending
on the user's login locale, or the locale specified by the browser. You can also customize the way
in which translations are performed and provide your own translation strings.
Perform the following steps to enable translation of content generated for the SUSI page by
Azure AD B2C to Spanish. You should repeat this process for any other policies used by your
application.
1) In the Azure portal, select Azure AD B2C from your favorites.
2) In the Policies section of the Azure AD B2C blade, select Sign-up or sign-in policies,
and then select B2C_1_SignUporSignInPolicy.
3) In the SIGN-UP OR SIGN-IN POLICY blade, select Edit, and then in the EDIT POLICY
blade, select Language customization.
4) In the Language customization blade, select Enable language customization. In the
confirmation message box, select Yes.
68 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
5) In the Language customization blade, select español.
6) In the es español blade, set Enabled to Yes, select Save, and then close the blade.
7) Close the Language customization blade.
8) In the SIGN-UP OR SIGN-IN POLICY blade, select Run now.
9) Verify that the English language version of the sign-in page appears.
10) Modify the URL in the browser, and append the string &ui_locales=es to the end of the
address:
https://login.microsoftonline.com/AwesomeYourLastname.onmicrosoft.com/oauth2/v2.0
/ […]=login&ui_locales=es
The ui_locales parameter indicates the locale that should be used to display a page. Azure B2C
determines the locale by examining the user's own configuration in the domain and includes the
69 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
appropriate ui_locales parameter as a query string parameter. Some browsers (not Microsoft
Edge) also enable you to change the locale as a browser configuration setting.
11) Verify that the sign in page is presented in Spanish.
Modify the Password Complexity of Policies
Azure AD B2C is able to detect brute-force password attacks and dictionary password attacks,
and differentiate users attempting to recall or mistyping a password from hackers and botnets.
In the event of a suspected attack, Azure AD B2C will lock the affected account. Additionally, to
help prevent successful attacks, users should create passwords that are sufficiently complex. You
can use the following steps to configure password complexity, and enforce custom complexity
rules when users sign up or reset their passwords. Note that password strength applies to SUSI,
password reset, and sign-in policies, and that you must configure each of these policies
separately.
1) In the Azure portal, select Azure AD BC from your favoites.
2) In the Policies section of the Azure AD B2C blade, select Sign-up or sign-in policies,
and then select B2C_1_SignUporSignInPolicy.
3) In the SIGN-UP OR SIGN-IN POLICY blade, select Edit, and then in the EDIT POLICY
blade, select Password complexity.
4) In the Password complexity blade, select Custom. Set Minimum length to 12. Set
Character classes required to Must contain all of the following: uppercase,
lowercase, numbers, symbols, and then select OK.
5) In the SIGN-UP OR SIGN-IN POLICY blade, select Run now.
6) In the sign-in page, select Sign up now.
70 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
7) On the sign-up page, enter your email address and select Send verification code.
8) Wait for the verification email, and then enter the verification code and select Verify
code.
9) Enter a short password that does not meet the password complexity requirements in the
New Password and Confirm New Password boxes. Note that a message appears
indicating that the password is not complex enough.
10) Enter a password that matches the complexity requirements and verify that it is
accepted.
71 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
Important Concepts
Azure AD and Customized Domains
An Azure AD domain represents your organization on the Internet; it is the entry point through
which customers access your applications and services. An Azure AD domain handles many
aspects surrounding your applications, including the security, visibility, and look and feel of the
applications and services that your organization publishes.
You can customize many elements in an Azure AD domain. For example, you can:
Add and delete users and groups, and assign permissions over your applications and
services to these users and groups. Identity and user management is a key aspect of
Azure AD that is utilized by B2C. See Quickstart: Add new users to Azure Active Directory for
details. You can also manage user profile information, such as adding a profile picture,
phone numbers, contact details, and other authentication information.
You can implement self-service enrollment for users. This feature allows users to sign-up
to your services without requiring any administrative action (or cost) on your part. You
can enable self-service password reset (SSPR) for users who forget their sign-in
credentials. You can configure the methods available to perform this task, for example,
send a code to a specified email account, or verify the user's identity by asking questions
to which only the user should know the answer. The article Azure AD self-service password
reset for the IT professional describes how to perform these tasks.
Associate an Azure domain with your own corporate DNS name. By default, each Azure
AD domain has a name in the form domainname.onmicrosoft.com. You can't remove or
change this name, but you can add your own custom DNS name, such as Contoso.com,
to the domain, and use this domain name to gain access to the domain. You can find
more information at Quickstart: Add a custom domain name to Azure Active Directory.
Change the appearance of the sign-in page that Azure AD displays to match your
company's branding. You can change items such as the banner logo that appears on the
sign-in page, the text displayed, the background image and color, and other aspects.
These changes also apply to items such as emails sent by the domain by processes such
as password reset and confirmation. See Quickstart: Add company branding to your sign-in
page in Azure AD for additional information.
These features work in conjunction with the UX customization available through B2C
policies.
Built-in Localization Strings for B2C Policies, and Customization
The language customization feature of Azure AD B2C performs the automatic translation of text
generated as part of the HTML content for the various policies that you define. As noted on the
page Language customization in Azure Active Directory B2C:
72 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
"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
journey."
The translations are based on a predefined set of built-in strings displayed by the policies. You
can override the translations performed, and provide your own localized text, if the default
translations do not meet your requirements, or if you need to display different or additional
information.
Each phrase on each page displayed by the policies is associated with an identifier. You can
download the list of identifiers and the corresponding phrases from the Language
customization page of a policy to a local file. You can then edit this file to provide your own
translations for any phrases and upload this file to the policy. The following steps describe how
to override the Spanish language translation of phrases for the SUSI policy of the sample
application:
1) In the Policies section of the Azure AD B2C blade, select Sign-up or sign-in policies,
and then select B2C_1_ADandFacebookSignUporSignInPolicy.
2) In the SIGN-UP OR SIGN-IN POLICY blade, select Edit, and then in the EDIT POLICY
blade, select Language customization.
3) In the Language customization blade, select español.
4) In the es español blade, under Page-level resources, expand Unified sign-up or sign-
in page, and then select Download defaults (es).
5) Save the downloaded file in a convenient place, and open it using a text editor. The
contents will look similar to this (a large part of the file has been omitted, to save space):
73 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
{
"LocalizedStrings": [
{
"ElementType": "UxElement",
"ElementId": null,
"StringId": "email_pattern",
"Override": false,
"Value": "^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\\.[a-zA-Z0-9-]+)*$"
},
{
"ElementType": "UxElement",
"ElementId": null,
"StringId": "logonIdentifier_email",
"Override": false,
"Value": "Dirección de correo electrónico"
},
{
"ElementType": "UxElement",
"ElementId": null,
"StringId": "requiredField_email",
"Override": false,
"Value": "Escriba su correo electrónico"
},
{
"ElementType": "UxElement",
"ElementId": null,
"StringId": "logonIdentifier_username",
74 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
"Override": false,
"Value": "Nombre de usuario"
},
{
"ElementType": "UxElement",
"ElementId": null,
"StringId": "password",
"Override": false,
"Value": "Contraseña"
},
{
"ElementType": "ErrorMessage",
"ElementId": null,
"StringId": "AADRequestsThrottled",
"Override": false,
"Value": "Hay demasiadas solicitudes en este momento. Espere un momento y vuelva a
intentarlo."
}
]
}
6) To override the default translation of a phrase, set Override to true, and provide your
own custom translation string as the Value.
7) Save the file and return to the es español blade in the Azure portal.
8) Select Upload new overrides, and specify the file that you have just edited.
75 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
9) When the policy is executed, any overrides that you have specified will be used rather
than the default translations.
76 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
Module 5: Introduction to Custom Policies
At the end of this module, you will be able to:
Create a custom policy.
Test and debug a custom policy.
Modify an existing custom B2C policy.
And, you will have a deeper understanding of the following concepts;
When to use custom policies rather than built-in policies
The Identity Experience Framework (IEF)
See it in action
See the end-user experience you are about to build.
In the demonstration site, access the Module 5 area and perform the following tasks:
Sign up with your email and a password.
Edit your profile to include a “1” at the end of your last name.
Change your password and experience the Multi-factor Authentication process.
This module should take approximately 60 minutes to complete.
77 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
Introduction
Built-in policies provide a set of standard behaviors that are useful in the most common
situations in Azure AD B2C and are not customizable. If you need to implement some form of
non-standard or extended behavior, you can implement custom policies.
You describe the features implemented by a custom policy by using a set of XML files. These
files can define the claims schema, claims transformations, content definitions, claims
providers/technical profiles, and user journey orchestration steps, among other elements. You
can define a hierarchy of XML files to ease maintenance and provide consistency across policies.
The Microsoft recommended approach is to use three types of policy files:
1) A BASE file. This file contains the definitions that are shared all policies in your tenant.
tenants. Any changes to this file can affect all the policies that depend on it. We
recommend not changing this file unless absolutely necessary.
2) An EXTENSIONS file. This file specifies elements that override the base configuration for
a single tenant.
3) A Relying Party (RP) file. This is a single task-focused file that is invoked directly by the
application or service. There could be many RP files depending on RP requirement.
When an application calls the RP Policy file, the IEF in B2C will assemble the policy file by
adding all the elements from BASE, then from EXTENSIONS, and lastly from the RP policy file.
Create a Custom Policy
To create a custom policy, you require the following items:
78 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
Signing and encryption keys
AAD applications that enable users to sign up and sign in.
To create the custom policy, you can download the custom policy starter pack from GitHub and
use the items it contains as a starting point. The following steps perform these tasks.
Add Signing and Encryption Keys to the B2C Tenant for use by Custom Policies
1) Create a Facebook application following the process described in Module 2 Using
Identity Providers with Azure AD B2C Built in Policies. Make a note of the Facebook app
id and Facebook secret.
2) Log into the Azure portal as B2CAdmin in your Azure tenant.
3) Switch to the AwesomeYourLastname.onmicrosoft.com B2C tenant.
4) Select Azure AD BC from your favorites.
5) Select Identity Experience Framework.
6) Select Policy Keys to view the keys available in your tenant (there should be none).
7) Create a new key:
a) Select +Add.
b) For Options, select Generate.
c) For the Name, enter TokenSigningKeyContainer.
d) For the Key type, select RSA.
e) For Dates, keep the defaults.
f) For Key usage, select Signature.
g) Select Create to add the new key.
79 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
8) Create the TokenEncryptionKeyContainer:
a) Select +Add.
b) Select Generate.
c) For the Name, enter TokenEncryptionKeyContainer
d) For the Key type, select RSA.
e) For Dates, keep the defaults.
f) For Key usage, select Encryption.
g) Select Create.
9) Create a Facebook secret key:
a) Select +Add.
b) For Options, select Manual.
c) For the Name, specify FacebookSecret.
d) For the Secret, specify your Facebook secret.
e) For Key usage, select Signature.
80 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
f) Select Create to create the key.
Register Identity Experience Framework applications
1) Create the IdentityExperienceFramework application (Web app)
a. Open the Azure Active Directory blade.
b. Select App registrations.
c. Select + New application registration.
d. Name the application IdentityExperienceFramework.
e. For the Application type, select Web App/API.
81 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
f. In Sign-on URL, enter
https://login.microsoftonline.com/AwesomeYourLastname.onmicrosoft.c
om, where AwesomeYourLastname is the name of your B2C tenant.
g. Select Create.
h. Record the application ID. You will need this later.
2) Create the ProxyIdentityExperienceFramework application (Native app).
a. Create a new application in Azure Active directory blade.
b. Name the application ProxyIdentityExperienceFramework.
c. Set application type to Native.
d. In Redirect Url, enter
https://login.microsoftonline.com/AwesomeYourLastname.onmicrosoft.c
om.
82 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
e. Select Create.
f. Record the application ID.
g. On the Application Details page select Settings.
h. Select Required permissions.
i. Select Add.
j. Select Select an API.
k. Search for IdentityExperienceFramework and select it.
l. Select Select permissions, and check Access IdentityExperienceFramework.
83 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
m. Select Select located at the bottom of the panel.
n. Select Done.
o. Select Grant Permissions, and then select Yes in the resulting dialog to
confirm the process.
Create the Custom Policies
Custom policies do not overwrite built in policies. To avoid possible confusion by having two
sets of policies defined for your B2C tenant, you will remove the built in policies you have added
in earlier modules as the functionality that they contain will be implemented (and extended) by
the custom policies.
1) In the Azure portal, move to the Azure AD B2C blade.
2) In the Policies section of the blade, select All policies.
3) Select the B2C_1_PasswordResetPolicy policy.
4) In the B2C_1_PasswordResetPolicy blade, select Delete, and then select Yes.
5) Repeat this process for the B2C_1_ProfileEditPolicy, B2C_1_SignUpOrSignInPolicy and
B2C_1_ADandFacebookSignUporSignInPolicy policies.
6) Using a web browser, download the custom policy starter packs from active-directory-b2c-
custom-policy-starterpack.
Each pack contains a list of XML policy files that include a Base file, an Extension File and
Replying Party files. You will use the SocialAndLocalAccounts pack for this tutorial.
7) Unzip the downloaded file to a convenient folder on your computer.
84 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
8) Move to the SocialAndLocalAccounts folder in the unzipped package.
9) Open the file TrustFrameworkBase.xml file using Visual Studio.
10) Modify the XML element TrustFrameworkPolicy at the top of the file, and replace
yourtenant with your B2C tenant name, AwesomeYourLastname. The resulting XML
element should look like this:
<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="AwesomeYourLastname.onmicrosoft.com"
PolicyId="B2C_1A_TrustFrameworkBase"
PublicPolicyUri="http://AwesomeYourLastname.onmicrosoft.com/
B2C_1A_TrustFrameworkBase">
11) Save the file.
12) Open the file TrustFrameworkExtensions.xml in Visual Studio.
13) Find and replace yourtenant with the tenant name AwesomeYourLastname. There
should be three occurrences.
14) Find the element <TechnicalProfile Id="login-NonInteractive"> and replace both
instances of IdentityExperienceFrameworkAppId with the application id of the
IdentityExperienceFramework app that you created earlier.
15) Replace both instances of ProxyIdentityExperienceFrameworkAppId with the
application id you created earlier for ProxyIdentityExperienceFramework app. The
result should look similar to this (but with your own app ids):
<ClaimsProvider>
<DisplayName>Local Account SignIn</DisplayName>
<TechnicalProfiles>
<TechnicalProfile Id="login-NonInteractive">
<Metadata>
<Item Key="client_id">e4c7ce45-9291-49f0-a824-0decbb98601b</Item>
<Item Key="IdTokenAudience">3643843e-0931-43de-8ab7-
fc37d8f00d0b</Item>
</Metadata>
<InputClaims>
<InputClaim ClaimTypeReferenceId="client_id" DefaultValue="e4c7ce45-9291-
49f0-a824-0decbb98601b" />
85 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
<InputClaim ClaimTypeReferenceId="resource_id" PartnerClaimType="resource"
DefaultValue="3643843e-0931-43de-8ab7-fc37d8f00d0b" />
</InputClaims>
</TechnicalProfile>
</TechnicalProfiles>
</ClaimsProvider>
16) Save the file.
17) Edit the SignUpOrSignin.xml file and replace yourtenant with
AwesomeYourLastname (three occurrences).
18) After the closing </BasePolicy> tag but before the opening <RelyingParty> tag, add
the following <BuildingBlocks> XML element. Replace awesomeyoursurnameb2cux
with the name of the Azure storage account you created in Module 4 to hold the
custom unified.html fragment for the SUSI page. Replace b2c with the name of the
blob storage container you created.
<BuildingBlocks>
<ContentDefinitions>
<ContentDefinition Id="api.signuporsignin">
<LoadUri>https://AwesomeYourLastnameb2cux.blob.core.windows.net/b2c/unified.
html</LoadUri>
</ContentDefinition>
<ContentDefinition Id="api.localaccountsignup">
<LoadUri>https://AwesomeYourLastnameb2cux.blob.core.windows.net/b2c/unified.
html</LoadUri>
</ContentDefinition>
</ContentDefinitions>
</BuildingBlocks>
19) Save the file.
20) Edit ProfileEdit.xml and replace yourtenant with AwesomeYourLastname (three
occurrences).
21) After the closing </BasePolicy> tag but before the opening <RelyingParty> tag, add
the following <BuildingBlocks> XML element.
<BuildingBlocks>
<ContentDefinitions>
<ContentDefinition Id="api.selfasserted.profileupdate">
86 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
<LoadUri>https://AwesomeYourLastnameb2cux.blob.core.windows.net/b2c/update
profile.html</LoadUri>
</ContentDefinition>
</ContentDefinitions>
</BuildingBlocks>
22) Save the file.
23) Edit PasswordReset.xml and replace yourtenant with AwesomeYourLastname
(three occurrences).
24) After the closing </BasePolicy> tag but before the opening <RelyingParty> tag, add
the following <BuildingBlocks> XML element.
<BuildingBlocks>
<ContentDefinitions>
<ContentDefinition Id="api.localaccountpasswordreset">
<LoadUri>https://AwesomeYourLastnameb2cux.blob.core.windows.net/b2c/unified.
html</LoadUri>
</ContentDefinition>
</ContentDefinitions>
</BuildingBlocks>
25) Save the file.
26) Return to the Azure Portal. Open the Azure AD B2C blade and select Identity
Experience Framework.
27) Select Upload policy, and upload the policy files in the following order:
a. TrustFrameworkBase.xml
b. TrustFrameworkExtensions.xml
c. SignUpOrSignin.xml
d. ProfileEdit.xml
e. PasswordReset.xml
87 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
The list of uploaded files should look like this:
Add Facebook as an Identity Provider in the Custom Policy
1) Using Visual Studio, edit the TrustFrameworkExtensions.xml policy file, find the
element <Item Key="client_id">facebook_clientid</Item>. Replace
facebook_clientid with your Facebook app id.
2) Save the file, and then in the Azure portal, upload the policy file. Select Overwrite the
policy if it exists.
88 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
Update the Web Application to Reference the New Policies
1) Using Visual Studio, return to the B2C-WebAPI-DotNet.sln solution for the web
application you configured and published in Module 3.
2) In Solution Explorer, In the AwesomeComputers project, select the Web.config file.
3) In the <appSettings> section near the start of the file, change the values for the
policy references to specify the new custom policy files, as follows:
<appSettings>
...
<add key="ida:SignUpSignInPolicyId" value="B2C_1A_signup_signin" />
<add key="ida:EditProfilePolicyId" value="B2C_1A_ProfileEdit" />
<add key="ida:ResetPasswordPolicyId" value="B2C_1A_PasswordReset" />
</appSettings>
4) Save the file.
5) In Solution Explorer, in the AwesomeComputers project, expand the Shared folder,
expand the Home folder, and then select the _LoginPartial.cshtml file.
6) In the _LoginPartial.cshtml file, modify the two <a> elements as follows. Replace the
policy names as highlighted in bold:
<ul class="nav navbar-nav navbar-right">
<li>
<a
href="https://login.microsoftonline.com/AwesomeYourLastname.onmicrosoft.com/oauth2/v
2.0/authorize?p=B2C_1A_ProfileEdit&client_id=ClientID&nonce=defaultNonce&redirect_ur
i=https%3A%2F%2FAwesomeYourLastname.azurewebsites.net&scope=openid&response_ty
pe=id_token">
Edit Profile
</a>
89 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
</li>
<li>
<a
href="https://login.microsoftonline.com/AwesomeYourLastname.onmicrosoft.com/oauth2/v
2.0/authorize?p=B2C_1A_PasswordReset&client_id=ClientID&nonce=defaultNonce&redire
ct_uri=https%3A%2F%2FAwesomeYourLastname.azurewebsites.net&scope=openid&respon
se_type=id_token">
Reset Password
</a>
</li>
</ul>
7) Save the file.
8) In Solution Explorer, right-click the AwesomeComputers project, then select Publish.
9) On the Publish page, select Publish, and wait for the web application to be deployed.
When the sign-in page appears in the web browser, close the page (do not sign in).
10) Return to the Azure AD B2C blade in the Azure portal.
11) Under the Policies section, select All policies, and then select the
B2C_1A_signup_signin policy.
12) Select Run now. When the sign-in page appears, it should be correctly styled, and
include the option to sign in using Facebook.
90 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
13) Sign in as TestUser@AwesomeYourLastname.onmicrosoft.com. When the Awesome
Computers page appears after signing in, select Edit Profile. The edit profile should
also be correctly styled.
91 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
14) Select Continue. When the Awesome Computers page reappears, select Reset
Password. This page should have the same styling.
15) Close the web app.
est and Debug a Custom Policy by Using Application Insights
You can use the detailed log information provided by Application Insights to investigate any
issues that might occur with a custom policy. Use the following steps to configure IEF to send
events directly to Application Insights.
Create Application Insights Resource
1) In the Azure portal, switch to the Azure tenant (not the current B2C tenant).
2) Select + Create a resource.
3) In the search box, enter Application Insights, and then select Application Insights.
4) Select Create.
5) Specify the following settings, and then select Create.
Name: DemoInsightsForCustomPolicies
Application Type: ASP.NET web application
Resource Group: Create new, AppInsightsResourceGroup
92 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
6) When the Application Insights resource has been created, select All resources, and
then select DemoInsightsForCustomPolicies.
7) Select Overview and then expand Essentials. Make a note of the Instrumentation
Key.
Update Relying Party (RP) Policies to Collect Logs
1) Using Visual Studio, open the SignUpOrSignIn.xml file.
2) Add the following attribute to the <TrustFrameworkPolicy> element.
DeploymentMode="Development"
UserJourneyRecorderEndpoint="urn:journeyrecorder:applicationinsights"
3) Under the <RelyingParty> element, add the following <UserJourneyBehaviours> node
immediately after <DefaultUserJourney ReferenceId="SignUpOrSignIn" /> element.
Replace the bold text with your application Insight Key.
<UserJourneyBehaviors>
<JourneyInsights
TelemetryEngine="ApplicationInsights"
InstrumentationKey="Your Application Insight Instrumentation Key"
DeveloperMode="true"
93 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
ClientEnabled="false"
ServerEnabled="true"
TelemetryVersion="1.0.0" />
</UserJourneyBehaviors>
Note the following points:
DeveloperMode=true is good for development but constrained at high volumes
because it tells Application Insights to expedite the telemetry through the processing
pipeline.
ClientEnabled="true" will send client-side scripts to Application Insights, for
tracking page view and client-side errors
ServerEnabled="true" will send the existing UserJourneyRecorder JSON as a custom
event to Application Insights
4) Save the file.
5) Return to the Azure Portal and switch to your B2C tenant. Open the Azure AD B2C
Blade and select Identity Experience Framework.
6) Select Upload policy, and upload the SignUpOrSignIn.xml policy file. Select overwrite
the policy if it exists.
Check the logs in Application Insights
1) Select the B2C_1A_signup_signin policy.
2) Select Run now.
3) Attempt to sign in as ;
a. an invalid user (type a random email address). T
b. TestUser@AwesomeYourLastname.onmicrosoft.com but with the wrong
password.
c. TestUser@AwesomeYourLastname.onmicrosoft.com using the correct
password.
4) In the Azure portal, switch back to your Azure tenant, and open the
DemoInsightsForCustomPolicies Application Insights resource.
5) In the Details/Overview menu, select Analytics.
6) Open a new tab inside the Application Insights web application.
7) Use any of the following example queries to view log information.
94 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
traces: See all of the logs generated by Azure AD B2C
traces | where timestamp > ago(1d): See all of the logs generated by Azure AD
B2C for the last day
traces | count: See how many events have been generated
traces | render pie chart: Summarize the data as a pie chart
Note that you might have to wait for a few minutes before logs start appearing in Application
Insights.
If necessary, you can download the query results and export them to CSV files if you need to
perform a detailed analysis.
You can learn more about performing analytics with Application Insights here
Modify the Starter Pack SUSI Policy
You can use a custom policy to include additional sign-up/sign-in functionality. In this
procedure, you will see how to incorporate a journey step into the SUSI process that prompts
the user to accept the organization's terms and conditions, add a claim to the sign-up page, and
validate input using an external REST API.
1) Using Visual Studio, open the TrustFrameworkBase.xml file.
2) Inside the <ClaimsSchema> node, insert the following claim type.
<ClaimType Id="TnCs">
<DisplayName>Terms of Service Consent</DisplayName>
<DataType>string</DataType>
<UserHelpText>I agree to the Awesome Computers terms of
service.</UserHelpText>
<UserInputType>CheckboxMultiSelect</UserInputType>
<Restriction>
<Enumeration Text="I agree to the Awesome Computers terms of service."
Value="4/19/2018" SelectByDefault="false" />
</Restriction>
</ClaimType>
3) Find the element <TechnicalProfile Id="LocalAccountSignUpWithLogonEmail">, and
in the <OutputClaims> node, add the following element.
<OutputClaim ClaimTypeReferenceId="TnCs" Required="true" />
4) Save the file.
5) Return to the Azure Portal and switch to your B2C tenant. Open the Azure AD B2C
Blade and select Identity Experience Framework.
95 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
6) Select Upload policy and upload the TrustFrameworkBase.xml policy file. Select
overwrite the policy if it exists.
7) To add a claim to the sign up page, open the SignUpOrSignIn.xml file using Visual
Studio.
8) Find the element <TechnicalProfile Id="PolicyProfile">, and in the <OutputClaims>
node, add <OutputClaim ClaimTypeReferenceId="TnCs"/>.
9) Save the file.
10) In the Azure portal, upload the SignUpOrSignIn.xml policy file and overwrite the
existing policy.
11) Select the B2C_1A_signup_signin policy.
12) Select Run now.
13) In the sign-in page, select Sign-up now.
14) In the sign-up page, notice that the Terms of Service Consented checkbox appears.
96 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
15) Attempt to create an account without checking Terms of Service Consent. This
should fail with the message This information is required. You should only be able
to proceed once you have checked the box.
16) Verify that you can create an account if you select the Terms of Service Consent
box.
Important Concepts
When to Use Built-in Versus Custom Policies
Built in policies implement the behavior most commonly required by tasks such as sign-in, sign-
up, password reset, and profile editing. . They also support scenarios such as authentication
through trusted parties, including Facebook, Google, and LinkedIn. If you have no special
identity requirements, using the built-in policies will get you up and running with the minimum
of fuss.
97 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
Custom policies are useful if you have special requirements, such as the use of non-standard
Identity providers. You can use custom policies to:
Interact with providers that implement the OIDC, OAUTH, and SAML protocols.
Include additional steps in the identity process, such as asking the user to confirm
acceptance of terms and conditions when they sign up to a service.
Perform custom operations, such as transposing requests when RPs (relying parties) and
AtPs (attribute providers) do not support the same protocol.
Custom policies provide you with full control over identity behavior and experience. Azure AD
B2C custom policies enable you to author your own trust framework: For example, they control
how the identity information is exchanged between relying parties, IdPs (identity providers) and
AtPs. They include all the operational details including claim providers, metadata and technical
profiles, claims schema definitions, claims transformation functions, and user journeys necessary
to facilitate operational orchestration and automation.
You can define the behavior of custom policies through XML configuration files, and then apply
them to your B2C container by using the IEF.
What is IEF?
The Identity Experience Framework (IEF) is a fully configurable, policy driven, cloud based Azure
service that coordinates trust between various entities such as claim providers. It implements
standard protocol formats such as OAuth, SAML, WsFed, and OpenIdConnect as well as non-
standard formats, such as claims based on proprietary REST APIs. The IEF provides a user-
friendly step-by-step interface that simplifies many of the tasks involved when implementing
identity policies.
Using the IEF, you provide the following essential information.
The legal, security, privacy and data protection policies to which participants must
conform.
The contacts and process required to become an accredited user.
The trusted identity/claims providers to use.
The trusted relying parties and their requirements.
The run time rules to enforce for exchanging identity information.
For built-in policies, you simply use the various wizards provided by the IEF blade in the Azure
portal. For more complex, custom requirements, you specify the details by using custom policy
files that you upload to IEF.
Using the IEF also minimizes the complexity of configuring identity federation. Federated
identity provides the end-user identity assurance. By delegating Identity to third parties, a single
user identity can be used with multiple relying parties. Identity assurance requires that the IdPs
and AtPs must adhere to specific security, privacy, and operational policies and practices. RPs
98 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
must build the trust relationships between IdPs and AtPs they choose to work with. The IEF
assists in this task, essentially reducing the process to two steps; establishing a trust relationship,
and performing a single metadata exchange.
99 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
Sample Custom Policy Files
TrustFrameworkExtensions.xml
<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="aadb2ctraining.onmicrosoft.com"
PolicyId="B2C_1A_TrustFrameworkExtensions"
PublicPolicyUri="http://aadb2ctraining.onmicrosoft.com/B2C_1A_TrustFrameworkExtensions"
TenantObjectId="4ba38890-d941-471a-b8cd-e5df2769070c">
<BasePolicy>
<TenantId>aadb2ctraining.onmicrosoft.com</TenantId>
<PolicyId>B2C_1A_TrustFrameworkBase</PolicyId>
</BasePolicy>
<BuildingBlocks>
<!--
Custom claims for Azure Application Insights go here
-->
<ClaimsSchema>
<ClaimType Id="extension_TermsOfServiceConsented">
<DisplayName>Terms of Service Consented</DisplayName>
<DataType>string</DataType>
<UserHelpText>I am agreeing to the Awesome Computers terms of
service.</UserHelpText>
<UserInputType>CheckboxMultiSelect</UserInputType>
<Restriction>
<Enumeration Text="I am agreeing to the Awesome Computers terms of service."
Value="4/19/2018" SelectByDefault="false" />
</Restriction>
</ClaimType>
</ClaimsSchema>
</BuildingBlocks>
<!--
All Claim provider definitions go here. In this example, only FB and local account providers are
configured
-->
<ClaimsProviders>
<ClaimsProvider>
<DisplayName>Facebook</DisplayName>
<TechnicalProfiles>
<TechnicalProfile Id="Facebook-OAUTH">
<Metadata>
100 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
<Item Key="client_id">1567223293375050</Item>
<!-- FB app client Id -->
<Item Key="scope">email public_profile</Item>
<!-- What access required-->
<Item
Key="ClaimsEndpoint">https://graph.facebook.com/me?fields=id,first_name,last_name,name,e
mail</Item>
<!-- what user profile information will be needed by FB API endpoint-->
</Metadata>
</TechnicalProfile>
</TechnicalProfiles>
</ClaimsProvider>
<ClaimsProvider>
<DisplayName>Local Account SignIn</DisplayName>
<TechnicalProfiles>
<TechnicalProfile Id="login-NonInteractive">
<Metadata>
<!-- Apps we created in Azure Active Directory for B2C to work-->
<Item Key="client_id">c5f2f442-6750-448f-9855-92d8e1d496f1</Item>
<Item Key="IdTokenAudience">d210459f-f186-4b9a-ac63-a4b20645b0d3</Item>
</Metadata>
<InputClaims>
<InputClaim ClaimTypeReferenceId="client_id" DefaultValue="c5f2f442-6750-448f-
9855-92d8e1d496f1" />
<InputClaim ClaimTypeReferenceId="resource_id" PartnerClaimType="resource"
DefaultValue="d210459f-f186-4b9a-ac63-a4b20645b0d3" />
</InputClaims>
</TechnicalProfile>
</TechnicalProfiles>
</ClaimsProvider>
</ClaimsProviders>
<UserJourneys>
<!-- Signup Signin user journey where we define all Orchestra Steps needed to send back
claims to Azure Application Insights using the Technical profile references we defined earlier -->
<UserJourney Id="SignUpOrSignIn">
<OrchestrationSteps>
<OrchestrationStep Order="1" Type="CombinedSignInAndSignUp"
ContentDefinitionReferenceId="api.signuporsignin">
<ClaimsProviderSelections>
<ClaimsProviderSelection TargetClaimsExchangeId="FacebookExchange" />
101 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
<ClaimsProviderSelection
ValidationClaimsExchangeId="LocalAccountSigninEmailExchange" />
</ClaimsProviderSelections>
<ClaimsExchanges>
<ClaimsExchange Id="LocalAccountSigninEmailExchange"
TechnicalProfileReferenceId="SelfAsserted-LocalAccountSignin-Email" />
</ClaimsExchanges>
</OrchestrationStep>
<!-- Check if the user has selected to sign in using one of the social providers -->
<OrchestrationStep Order="2" Type="ClaimsExchange">
<Preconditions>
<Precondition Type="ClaimsExist" ExecuteActionsIf="true">
<Value>objectId</Value>
<Action>SkipThisOrchestrationStep</Action>
</Precondition>
</Preconditions>
<ClaimsExchanges>
<ClaimsExchange Id="FacebookExchange" TechnicalProfileReferenceId="Facebook-
OAUTH" />
<ClaimsExchange Id="SignUpWithLogonEmailExchange"
TechnicalProfileReferenceId="LocalAccountSignUpWithLogonEmail" />
</ClaimsExchanges>
</OrchestrationStep>
<!-- For social IDP authentication, attempt to find the user account in the directory. -->
<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>
<!-- Show self-asserted page only if the directory does not have the user account already
(i.e. we do not have an objectId). This can only happen when authentication happened using a
social IDP. If a local account was created or authentication was done using ESTS in step 2, then a
user account must exist in the directory by this time. -->
<OrchestrationStep Order="4" Type="ClaimsExchange">
<Preconditions>
<Precondition Type="ClaimsExist" ExecuteActionsIf="true">
102 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
<Value>objectId</Value>
<Action>SkipThisOrchestrationStep</Action>
</Precondition>
</Preconditions>
<ClaimsExchanges>
<ClaimsExchange Id="SelfAsserted-Social" TechnicalProfileReferenceId="SelfAsserted-
Social" />
</ClaimsExchanges>
</OrchestrationStep>
<!-- This step reads any user attributes that we may not have received when
authenticating using ESTS so they can be sent in the token. -->
<OrchestrationStep Order="5" 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>
<!-- The previous step (SelfAsserted-Social) could have been skipped if there were no
attributes to collect from the user. So, in that case, create the user in the directory if one does
not already exist (verified using objectId, which would be set from the last step if account was
created in the directory. -->
<OrchestrationStep Order="6" Type="ClaimsExchange">
<Preconditions>
<Precondition Type="ClaimsExist" ExecuteActionsIf="true">
<Value>objectId</Value>
<Action>SkipThisOrchestrationStep</Action>
</Precondition>
</Preconditions>
<ClaimsExchanges>
<ClaimsExchange Id="AADUserWrite" TechnicalProfileReferenceId="AAD-
UserWriteUsingAlternativeSecurityId" />
</ClaimsExchanges>
</OrchestrationStep>
<OrchestrationStep Order="7" Type="SendClaims"
CpimIssuerTechnicalProfileReferenceId="JwtIssuer" />
</OrchestrationSteps>
<ClientDefinition ReferenceId="DefaultWeb" />
103 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
</UserJourney>
</UserJourneys>
</TrustFrameworkPolicy>
SignUpOrSignin.xml
<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="aadb2ctraining.onmicrosoft.com"
TenantObjectId="4ba38890-d941-471a-b8cd-e5df2769070c"
PolicyId="B2C_1A_Module5SignupSignin"
PublicPolicyUri="http://aadb2ctraining.onmicrosoft.com/"
DeploymentMode="Development"
UserJourneyRecorderEndpoint="urn:journeyrecorder:applicationinsights">
<BasePolicy>
<TenantId>aadb2ctraining.onmicrosoft.com</TenantId>
<PolicyId>B2C_1A_TrustFrameworkExtensions</PolicyId>
</BasePolicy>
<RelyingParty>
<DefaultUserJourney ReferenceId="SignUpOrSignIn" />
<UserJourneyBehaviors>
<SingleSignOn Scope="Application" />
<SessionExpiryType>Rolling</SessionExpiryType>
<SessionExpiryInSeconds>86400</SessionExpiryInSeconds>
<JourneyInsights
TelemetryEngine="ApplicationInsights"
InstrumentationKey="XXXXXXXXXXXXXXXXX"
DeveloperMode="true"
ClientEnabled="false"
ServerEnabled="true" TelemetryVersion="1.0.0" />
</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" />
<OutputClaim ClaimTypeReferenceId="identityProvider" />
104 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
<OutputClaim ClaimTypeReferenceId="TnCs" />
</OutputClaims>
<SubjectNamingInfo ClaimType="sub" />
</TechnicalProfile>
</RelyingParty>
</TrustFrameworkPolicy>
105 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
Module 6 Custom Policies 2 REST APIs
Introduction
At the end of this module, you will be able to integrate your own REST APIs into custom policies,
to perform tasks such as validating input claims and sending back output claims. You will be
able to:
1. Create a custom policy for REST API integration
2. Modify the profile edit policy to consume data from an external API.
See it in action
See the end-user experience you are about to build.
In the demonstration site, access the Module 6 are and perform the following tasks:
1. Sign in with a previously created account.
2. When the Store membership Number field appears, enter a multiple of 5.
a. Only multiple of five will successfully validate against the API.
This module will take 60 minutes to complete.
The Azure AD B2C Identity Experience Framework (IEF) provides complete control for
configuring policies. It enables you to integrate identity providers with external REST full APIs
through user journeys. IEF sends and receives data in form of claims. You can configure a policy
to exchange claims and perform complex validation of identity information through a REST API
by adding orchestration steps inside the user journey.
By the end of this module, you will be able to create a user journey that interacts with a RESTful
service.
Prerequisites
Note that this module assumes that you have completed Module 5 and created the XML
files that define the custom policies used by the sample web application.
106 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
Step-by-Step Instructions
Create a custom policy for REST API integration
You will create a RESTful service that validates user input and sends an error message if the
input data is not valid. The data that the service validates is part of the identity information
provided when a user signs up to your application.
Create an API Application
1) Start Visual studio.
2) On the File menu, select New and then select Project.
3) In the New Project dialog box, expand Visual C#, select Web, and then select ASP.NET
Core Web Application.
4) Name the project StoreMembershipApi, and then select OK.
5) In the New ASP.NET Core Web Application dialog box, select Web Application
(Model View Controller), select No Authentication and then select OK.
107 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
Add Data Models and the Controller to the API project
The user will provide a Store Membership Number at the time of registration of his account. The
RESTful service will validate this number, and if it is verified registration will be allowed to
proceed. If the number is invalid, the service will send back a validation failed error.
In this example, the validation is simple; the provided Store Membership Number must be an
integer that is divisible by 5.
1) In Solution Explorer, right-click Models, select Add, and the select Class.
108 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
2) In the Add New Item dialog box, select Class. Specify the name
ValidationResponseContent, and then select Add.
3) Replace the code in the ValidationResponseContent.cs file with the following class:
109 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
namespace StoreMembershipApi.Models
{
public class ValidationResponseContent : StoreResponseContent
{
public string StoreMembershipNumber { get; set; }
}
}
4) Using the same procedure, add another class to the Models folder, named
StoreResponseContent. Replace the code for the class with these statements:
using System.Net;
using System.Reflection;
namespace StoreMembershipApi.Models
{
public class StoreResponseContent
{
public string Version { get; set; }
public int Status { get; set; }
public string UserMessage { get; set; }
public StoreResponseContent()
{ }
public StoreResponseContent(string message, HttpStatusCode status)
{
this.UserMessage = message;
this.Status = (int)status;
110 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
this.Version = Assembly.GetExecutingAssembly().GetName().Version.ToString();
}
}
}
5) Add a further class to the Models folder, named MembershipRequest. Replace the
code generated for this class with the following statements:
namespace StoreMembershipApi.Models
{
public class MembershipRequest
{
public int StoreMembershipNumber { get; set; }
}
}
6) In Solution Explorer, right-click the Controllers folder, select Add, and then select
Controller.
7) In the Add Scaffold dialog box, select API Controller -Empty, and then select Add.
111 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
8) In the Add Controller dialog box, name the controller MembershipController, and then
select Add.
9) Replace the code generated for the controller with the following.
using System;
using System.Net;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using StoreMembershipApi.Models;
namespace StoreMembershipApi.Controllers
{
/// <summary>
/// This controller is responsible for responding to requests from our custom policies
/// to validate store membership numbers and retrieve customer membership dates.
/// </summary>
[Route("api/[controller]")]
public class MembershipController : Controller
{
/// <summary>
/// This method receives a storeMembershipnumber from the policy validation
step and returns a 409 Conflict
/// response if the store membership number is not valid (not a multiple of 5),
and a 200 Ok response on
/// successful validation of the store membership number.
112 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
/// </summary>
/// <param name="request">Passed from the policy validation step, contains a
storeMembershipNumber.</param>
/// <returns>HTTP 200 Ok on success. HTTP 409 Conflict if provided an invalid
store membership number.</returns>
[HttpPost("validate")]
public IActionResult ValidateMembershipNumber([FromBody]
MembershipRequest request)
{
if (!IsStoreMembershipNumberValid(request.StoreMembershipNumber))
{
return GenerateErrorMessageWithMessage("Store membership
number is not valid, it must be a multiple of 5!");
}
// Return the output claim(s)
return Ok(new ValidationResponseContent
{
StoreMembershipNumber =
request.StoreMembershipNumber.ToString()
});
}
/// <summary>
/// Constructs an HTTP 409 Conflict IActionResult to return back to the validation
or orchestration step.
/// This is used to communicate with the policy steps to communicate an error
state.
113 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
/// </summary>
/// <param name="message">The message to be passed back to the user to
explain why the request failed.</param>
/// <returns>An IActionResult representing an HTTP 409 Conflict with a custom
payload.</returns>
private IActionResult GenerateErrorMessageWithMessage(string message)
{
return StatusCode((int)HttpStatusCode.Conflict, new
StoreResponseContent
{
Version = "1.0.0",
Status = (int) HttpStatusCode.Conflict,
UserMessage = message
});
}
/// <summary>
/// Validates a provided store membership number by using the modulus
operator (see more <see href="https://docs.microsoft.com/en-us/dotnet/csharp/language-
reference/operators/remainder-operator">here</see>)
/// to determine if the provided store membership number is a multiple of 5. If it
is, we return true, if not, we return false.
/// </summary>
/// <param name="storeMembershipNumber">The store membership number
to be validated.</param>
/// <returns>True on successful validation, false if validation fails.</returns>
private bool IsStoreMembershipNumberValid(int storeMembershipNumber)
{
114 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
if (storeMembershipNumber % 5 != 0)
{
return false;
}
return true;
}
}
}
10) On the Build menu, select Rebuild Solution, and verify that the solution builds without
any errors.
Publish the Project as an Azure Website
1) In Solution Explorer, right-click the StoreMembershipApi project node, and then select
Publish.
115 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
2) In the Pick a publish target dialog box, select App Service, select Create New, and then
select Publish.
116 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
3) In the Create App Service dialog box, login to Azure as B2CAdmin in your Azure
domain, specify a unique App Name, select a resource group, and then select Create.
4) Wait while the service is published. The site will launch in the browser when publishing is
complete.
5) Record the URL of your service in the browser address bar.
Update Custom Policies
117 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
1) In Visual Studio and open the TrustFrameworkExtensions.xml policy file that you
created in Module 5.
2) In the <BuildingBlocks> node add the following <ClaimsSchema> element.
<ClaimsSchema>
<ClaimType Id="extension_storeMembershipNumber">
<DisplayName>Store Membership Number</DisplayName>
<DataType>string</DataType>
<UserHelpText>Your store membership number</UserHelpText>
<UserInputType>TextBox</UserInputType>
</ClaimType>
</ClaimsSchema>
3) In the <ClaimsProviders> node, add the following <ClaimsProvider> element. Replace
the address highlighted in bold with the URL of your REST web service.
<ClaimsProvider>
<DisplayName>REST APIs</DisplayName>
<TechnicalProfiles>
<TechnicalProfile Id="ValidateStoreMembershipNumber">
<DisplayName>Validate Store Membership Number</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://yourwebservice.azurewebsites.net/api/membership/validate</Item
>
<Item Key="AuthenticationType">None</Item>
<Item Key="SendClaimsIn">Body</Item>
</Metadata>
<InputClaims>
<InputClaim ClaimTypeReferenceId="extension_storeMembershipNumber"
PartnerClaimType="storeMembershipNumber" />
</InputClaims>
<UseTechnicalProfileForSessionManagement ReferenceId="SM-Noop" />
</TechnicalProfile>
<TechnicalProfile Id="LocalAccountSignUpWithLogonEmail">
<OutputClaims>
<OutputClaim ClaimTypeReferenceId="extension_storeMembershipNumber"
PartnerClaimType="storeMembershipNumber" />
</OutputClaims>
<ValidationTechnicalProfiles>
<ValidationTechnicalProfile ReferenceId="ValidateStoreMembershipNumber" />
118 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
</ValidationTechnicalProfiles>
</TechnicalProfile>
</TechnicalProfiles>
</ClaimsProvider>
4) Save the file.
5) Using the Identity Experience Framework in the Azure portal, upload the
TrustFrameworkExtensions.xml file, and overwrite the existing policy.
6) In Visual Studio, open the SignUpOrSignIn.xml file in your working directory.
7) Find the element <TechnicalProfile Id="PolicyProfile">, and in the <OutputClaims> node
add the following XML markup:
<OutputClaim ClaimTypeReferenceId="extension_storeMembershipNumber" />
8) Save the file.
9) Using the Identity Experience Framework in the Azure portal, upload the
SignUpOrSignIn.xml file, and overwrite the existing policy.
Test the Custom Policy
1) In the Azure portal, select Azure Active Directory, and then select Users.
119 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
2) Select the user you created in module 5, and then select Delete user. Select Yes to
confirm the deletion.
Note: The purpose of these two steps was to enable you to reuse the same user account in the
following test.
3) In the Azure portal, return to the Azure AD B2C blade, and then select All policies.
120 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
4) Select the B2C_1A_signup_signin policy to open its detail view.
121 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
5) Select Run now.
6) On the sign in page, select Sign up now.
7) On the sign up page, verify that the prompt Store Membership Number appears.
8) Attempt to sign up with a store membership number that is not a multiple of 5.
9) Verify that if you specify a multiple of 5 for the store membership number then sign up is
successful. You can check this as follows:
a. When the Awesome Computers page appears, select View Token Contents.
122 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
b. In the jwt.ms page, select the Claims tab.
c. Scroll through the list of claims, you should see a claim with type
extension_storeMembershipNumber that has the value that you specified.
Modify the Profile Edit Policy to Return the User Store Membership Date
In this task, you will add an additional step to the RESTful service. This step will read the input
user claims and return the Store Membership Date.
Modify the API Project
1) Return to the StoreMembershipApi project in Visual Studio.
123 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
2) In Solution Explorer, right-click Models, select Add, and then select Class.
3) In the Add New Item dialog box, select Visual C#, and then select Class. Specify the
name MembershipDateResponseContent and then select Add.
4) Replace the code in the MembershipDateResponseContent.cs file with the following
code:
namespace StoreMembershipApi.Models
{
public class MembershipDateResponseContent : StoreResponseContent
{
public string StoreMembershipDate { get; set; }
}
}
5) In Solution Explorer, expand the Controllers folder, and select the
MembershipController.cs file.
6) Add the following methods to the MembershipController class.
/// <summary>
/// This method receives a storeMembershipnumber from the policy orchestration step and
returns a 409 Conflict
/// response if the store membership number is not valid (not a multiple of 5), and a 200 Ok
response containing
/// the member's membership date if the store membership number is valid.
/// </summary>
/// <param name="request">Passed from the policy orchestration step, contains a
storeMembershipNumber.</param>
/// <returns>HTTP 200 Ok on success with an obtained membership date. HTTP 409 Conflict if
provided an invalid store membership number.</returns>
[HttpPost("membershipdate")]
public IActionResult GetMembershipDate([FromBody] MembershipRequest request)
{
124 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
if (!IsStoreMembershipNumberValid(request.StoreMembershipNumber))
{
return GenerateErrorMessageWithMessage("Store membership number is not valid, it must
be a multiple of 5!");
}
var membershipDate = ObtainStoreMembershipDate();
return Ok(new MembershipDateResponseContent
{
Version = "1.0.0",
Status = (int)HttpStatusCode.OK,
UserMessage = "Membership date located successfully.",
StoreMembershipDate = membershipDate.ToString("d")
});
}
/// <summary>
/// Generates a date within the last 90 days to return as the store membership number for a
member.
/// In a production application you'd likely contact a database here to get a real membership
date for a member.
/// </summary>
/// <returns>A DateTime representing the store membership date for a member.</returns>
private static DateTime ObtainStoreMembershipDate()
{
var random = new Random();
var daysOffOfToday = random.Next(0, 90);
var randomDate = DateTime.Now.AddDays(-daysOffOfToday);
125 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
return randomDate;
}
7) Save the file
8) On the Build menu, select Rebuild Solution. Verify that the solution compiles without
any errors.
9) In Solution Explorer, right-click the StoremembershipApi project, and then select
Publish.
10) In the Publish window, select Publish. Wait for the updated service to be deployed.
Update Custom Policies
1) Using Visual Studio, open the TrustFrameworkExtensions.xml policy file.
2) In the <BuildingBlocks> node, insert the following <ClaimType> to the collection in the
<ClaimsSchema> node.
<ClaimType Id="extension_storeMembershipDate">
<DisplayName>Store Membership Date</DisplayName>
<DataType>string</DataType>
<UserHelpText>Your store membership date</UserHelpText>
<UserInputType>TextBox</UserInputType>
</ClaimType>
3) In the <ClaimsProviders> node, find the <ClaimsProvider> node that contains the
<DisplayName>REST APIs</DisplayName> element. Add the following
<TechnicalProfile> node to this ClaimsProvider. Replace the address highlighted in bold
with the URL of your REST web service.
<!-- Obtain claim technical profile -->
<TechnicalProfile Id="ObtainStoreMembershipDate">
<DisplayName>Obtain Store Membership Date</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://yourwebservice.azurewebsites.net/api/membership/membershipdate</Item>
<Item Key="AuthenticationType">None</Item>
<Item Key="SendClaimsIn">Body</Item>
</Metadata>
<InputClaims>
126 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
<InputClaim ClaimTypeReferenceId="extension_storeMembershipNumber"
PartnerClaimType="storeMembershipNumber" />
</InputClaims>
<OutputClaims>
<OutputClaim ClaimTypeReferenceId="extension_storeMembershipDate"
PartnerClaimType="storeMembershipDate" />
</OutputClaims>
<UseTechnicalProfileForSessionManagement ReferenceId="SM-Noop" />
</TechnicalProfile>
4) Uncomment the <UserJourneys> node at the end of the file, and add the following
<UserJourney> element to this node.
<UserJourney Id="ProfileEditObtainApiClaim">
<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">
<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="4" Type="ClaimsExchange">
<ClaimsExchanges>
127 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
<ClaimsExchange Id="B2CUserProfileUpdateExchange"
TechnicalProfileReferenceId="SelfAsserted-ProfileUpdate" />
</ClaimsExchanges>
</OrchestrationStep>
<OrchestrationStep Order="5" Type="ClaimsExchange">
<ClaimsExchanges>
<ClaimsExchange Id="GetStoreMembershipDateData"
TechnicalProfileReferenceId="ObtainStoreMembershipDate" />
</ClaimsExchanges>
</OrchestrationStep>
<OrchestrationStep Order="6" Type="SendClaims"
CpimIssuerTechnicalProfileReferenceId="JwtIssuer" />
</OrchestrationSteps>
<ClientDefinition ReferenceId="DefaultWeb" />
</UserJourney>
5) Save the XML file.
6) Using the Identity Experience Framework in the Azure portal, upload the
TrustFrameworkExtensions.xml file, and overwrite the existing policy.
7) Using Visual Studio, open the ProfileEdit.xml file.
8) Under the <RelyingParty>, node replace the <DefaultUserJourney> node with the
following XML element.
<DefaultUserJourney ReferenceId="ProfileEditObtainApiClaim" />
9) Under the <TechnicalProfile Id="PolicyProfile">node, add the following XML markup
below the <OutputClaims> node.
<OutputClaim ClaimTypeReferenceId="extension_storeMembershipDate" />
10) Save the XML file.
11) Using the Identity Experience Framework in the Azure portal, upload the B2C_1A_
ProfileEdit.xml file, and overwrite the existing policy.
Test the Custom Policy
1) In the Azure portal, use the Azure Active Directory blade to delete the user you created
in the previous test.
2) Return to the Azure AD B2C blade, and then select All policies.
3) Select the B2C_1A_signup_signin policy, and then select Run now.
4) On the sign in page, select Sign up now.
128 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
5) On the sign up page, sign up again, using the same account as before.
6) When sign up is complete, edit your profile by selecting Edit Profile in the demo web
app.
7) After updating your profile, select View Token Contents.
8) Select Claims. You should see the storeMembershipDate claim in the claims list sent
back from Azure AD B2C.
129 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
130 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
Module 7External IDPs, OIDC and SAML
Introduction
At the end of this module, you will be able to:
Add OIDC IDP (Google) in Azure AD B2C using Custom Policies
Integrate a SAML IDP and map claims (Salesforce) using Custom Policies
This module should take approximately 75 minutes to complete.
User management and configuring authentication can be a time-consuming process. It can also
be error prone if the authentication and identity requirements are complex, leading to possible
issues with security. To reduce costs, it is sometimes worthwhile to consider using third party
identity providers to manage and authenticate users, although integration multiple IdPs into a
solution can also be a challenge. Using Azure AD B2C simplifies many of these tasks. This
module shows two examples for configuring popular third-party external IdPs.
Note that this module assumes that you have completed Module 6 and created the XML
files that define the custom policies used by the sample web application.
131 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
Integrate an OIDC IDP and Map Claims
As an example of using an OIDC IDP, the following procedure describes how to integrate
Google as an IDP in Azure Identity Framework Experience.
Create a Google+ Application
Note: This procedure is only necessary if you don't already have a Google app available. It
assumes that you have a Google+ account. If you need to create a Google+ account, click here.
1) Sign in to your Google+ account
2) Open the Google Developer Console
3) Select Select project.
4) Select Create.
5) Enter a project name of DemoB2CGooglePlus, and then click Create.
6) When the project has been created, select the DemoB2CGooglePlus project from
project menu.
132 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
7) In the left-hand menu, select Credentials.
8) Select OAuth Consent Screen.
9) Provide your email address, enter a product name, and then select Save.
10) After the project has been saved, select Create Credentials, and then select OAuth
Client ID.
133 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
11) In the list of options, select Web Application.
12) Set the name to Azure Demo B2C Client, set the Authorised JavaScript Origins to
https://login.microsoftonline.com, enter
https://login.microsoftonline.com/te/AwesomeYourLastname.onmicrosoft.com/oa
uth2/authresp in the Authorized Redirect URIs field (where AwesomeYourLastname
is the name of your B2C tenant), and then select Create.
134 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
13) Record the client ID and client secret; you will need them later.
Setup Google+ Application Key and Secret in Azure AD B2C
1) Log in to the Azure portal as B2CAdmin in your Azure tenant, and then switch to the
AwesomeYourLastname.onmicrosoft.com B2C tenant.
2) Select All services, type Azure AD BC in the search field, and then select Azure AD B2C.
3) Select Identity Framework Experience.
135 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
4) Select Policy Keys from left menu.
5) Select + Add.
6) For Options, select Manual.
7) In the Name field, enter GoogleSecret.
8) In the Secret field, enter the Google app secret key you recorded earlier.
9) Select Encryption.
10) Select Create.
136 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
Update Policy Files
1) Open the TrustFrameworkBase.xml policy file that you used in Modules 5 and 6 using
Visual Studio.
2) Add the following ClaimsProvider element to the list in the <ClaimsProviders> node.
Replace client_id with the client ID of your Google+ application.
<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</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="socialIdpUserId" 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>
137 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
<UseTechnicalProfileForSessionManagement ReferenceId="SM-SocialLogin" />
<ErrorHandlers>
<ErrorHandler>
<ErrorResponseFormat>json</ErrorResponseFormat>
<ResponseMatch>$[?(@@.error == 'invalid_grant')]</ResponseMatch>
<Action>Reauthenticate</Action>
<!--In case of authorization code used error, we don't want the user to select his account
again.-->
<!--AdditionalRequestParameters
Key="prompt">select_account</AdditionalRequestParameters-->
</ErrorHandler>
</ErrorHandlers>
</TechnicalProfile>
</TechnicalProfiles>
</ClaimsProvider>
3) Save the file
4) Open the TrustFrameworkExtensions.xml policy file.
5) Find the <UserJourneys> element near the end of the file.
6) Copy the <UserJourney> element with attribute value Id="SignUpOrSignIn" from the
TrustFrameworkBase.xml file to the list of UserJourney elements in the
TrustFrameworkExtensions.xml file.
Note: Make sure that you copy the entire <UserJourney> element; it contains seven
orchestration steps.
7) Locate the <OrchestrationStep> element with attribute Order="1" value under this
element.
8) Replace the <ClaimsProviderSelections> element in this step with the following XML
markup.
<ClaimsProviderSelections>
<ClaimsProviderSelection TargetClaimsExchangeId="GoogleExchange" />
</ClaimsProviderSelections>
9) Locate the <OrchestrationStep> element with attribute Order="2" in the
<UserJourney> node and replace the <ClaimExchanges> node with this markup.
<ClaimsExchanges>
<ClaimsExchange Id="GoogleExchange" TechnicalProfileReferenceId="Google-OAUTH"
/>
</ClaimsExchanges>
138 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
10) Save the file.
11) In the Azure portal, in the Azure AD B2C blade, select Identity Experience Framework.
12) Select Upload Policy, and upload the TrustFrameworkBase.xml policy file. Overwrite
the policy if it already exists.
13) Repeat the operation and upload TrustFrameworkExtensions.xml policy file.
14) When the files have been uploaded, click B2C_1A_signup_signin policy to see its detail
view.
15) Select Run now.
16) The sign-in page should include the option to sign in with Google.
139 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
17) You should be able to sign in using your Google account.
18) After you have signed in, on the Awesome Computers page select View Token
Contents, and then select the Claims tab. The idp claim should be set to google.com.
Integrate a SAML IDP and Map Claims
This example shows how to integrate the Salesforce IDP as an example of a SAML identity
provider. If you don't have a Salesforce developer account you can Signup for a free Developer
Account, and then setup My Domain.
Setup the Identity Provider in Salesforce
1) Login to your Salesforce developer account.
2) In the left menu, under Settings, expand the Identity menu and then select Identity
Provider.
3) Select Enable Identity Provider (you may need to create a domain first).
140 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
4) Select the default certificate from the list and then select Save.
Create a Salesforce App
1) On the Identity Provider page, select the Service Providers link.
2) Provide a connected app name, API name, and contact email as shown in the following
image:
3) In the Web App Settings section select Enable SAML.
4) In the Entity Id field, enter
https://login.microsoftonline.com/te/AwesomeYourLastname.onmicrosoft.com/B2
C_1A_TrustFrameworkBase.
5) In the ACS URL field, enter
https://login.microsoftonline.com/te/AwesomeYourLastname.onmicrosoft.com/B2
C_1A_TrustFrameworkBase/samlp/sso/assertionconsumer.
141 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
6) Leave the remaining fields at their default values, scroll down, and select Save.
7) On the overview page for the new app, select Manage.
8) In the Metadata section, record the value for Metadata Discovery Endpoint.
9) Scroll down to the Profiles section, and then select Manage Profile.
10) Select the profile or group you want to federate with Azure AD B2C. Select System
Administrator so that you can federate with your account.
142 © 2018 Microsoft Corporation Feedback? https://aka.ms/aad-b2c-course-feedback
Create a Signed Certificate for Azure AD B2C
1) Open Azure Power shell and run the following commands. Replace
AwesomeYourLastname with the name of your B2C tenant, and provide a password for
the certificate.
$tenantName = "AwesomeYourLastname.onmicrosoft.com"
$pwdText = "<YOUR PASSWORD HERE>"
$Cert = New-SelfSignedCertificate -CertStoreLocation Cert:\CurrentUser\My -DnsName
"SamlIdp.$tenantName" -Subject "B2C SAML Signing Cert" -HashAlgorithm SHA256