This document outlines the agenda and topics that will be covered in an Azure AD B2C webinar on troubleshooting custom policies. The webinar will cover visual studio code extensions for custom policies, navigating and editing policies, deploying policies using PowerShell, application insights monitoring of user journeys and technical profiles, and interacting with an Azure AD B2C tenant through the Microsoft Graph API and viewing protocol exchanges. Attendees are encouraged to complete a post-call survey to provide feedback and ask any remaining questions.
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
Azure AD B2C Webinar Series: Custom Policies Part 3 Troubleshooting
1. Azure AD B2C Webinar Series
Troubleshooting Custom Policies
John Garland
VP Cloud Development & Instructor, Wintellect
Azure MVP, MCT, P-CSA
wintellect.com
@dotnetgator
Vinu Gunasekaran
Program Manager, Microsoft
3. Date Time (PDT) Topic
20-Apr
21-Apr
2-3 PM
8-9 AM
Identity Protocols – OIDC, OAuth2
Recording: https://aka.ms/B2CWebinarRecordings
27-Apr
28-Apr
2-3 PM
8-9 AM
B2C & App Integration (with MSAL)
Recording: https://aka.ms/B2CWebinarRecordings
4-May
5-May
2-3 PM
8-9 AM
Custom Policies Part 1: Concepts with Take-Home Lab
Recording: https://aka.ms/B2CWebinarRecordings
11-May
12-May
2-3 PM
8-9 AM
Custom Policies Part 2: Policy Walkthrough
Recording: https://aka.ms/B2CWebinarRecordings
18-May
19-May
2-3 PM
8-9 AM
Custom Policies Part 3: Troubleshooting
Calendar of Previous & Upcoming Sessions
4. Azure AD B2C Webinar Series
Troubleshooting Custom Policies
John Garland
VP Cloud Development & Instructor, Wintellect
Azure MVP, MCT, P-CSA
wintellect.com
@dotnetgator
Vinu Gunasekaran
Program Manager, Microsoft
5. Agenda
Note – The content today assumes you are familiar with the pre-requisite material outlined in the
session description, including:
• What is Azure AD B2C
• Basic Azure AD B2C configuration and user flow creation
• Azure AD B2C Use Cases
Also, if you haven’t already, you may want to go back and watch the prior sessions in this series.
Design Develop Publish Runtime Integrate
6. Visual Studio Code Extension
https://marketplace.visualstudio.com/items?itemName=AzureADB2CTools.aadb2c
7. • Managed repository that contains dozens of custom policy solutions
for common scenarios.
Azure AD B2C Documentation
https://docs.microsoft.com/azure/active-directory-b2c/
Design
8. • Managed repository that contains dozens of custom policy solutions
for common scenarios.
Azure AD B2C Custom User Journey Repository
https://github.com/azure-ad-b2c/samples
Design
9. • Explore policy file contents with the Policy Explorer
• Navigate with Go to Definition, Go to References,
Peek, and Find All References
• Look up item definitions by hovering
Policy NavigationDevelop
11. • Replace environment-
specific content values in
your policies
• Manage per-environment
settings
Policy Value ReplacementPublish
12. Automated Policy Deployment (PowerShell)Publish
Install-module AzureADPreview
# Connect to AAD (B2C) Tenant
Connect-AzureAD -Tenant "{b2c-tenant-name}.onmicrosoft.com” # Account must have B2C IEF Policy Administrator
Role
# List Policies
Get-AzureADMSTrustFrameworkPolicy
# Download Policy
Get-AzureADMSTrustFrameworkPolicy -Id <policyId> [-OutputFilePath <outputFilePath>]
# Upload a Policy
Set-AzureADMSTrustFrameworkPolicy [-Id <policyId>] –InputFilePath <inputFilePath>
New-AzureADMSTrustFrameworkPolicy -InputFilePath <inputpolicyfilePath>
# Delete a Policy
Remove-AzureADMSTrustFrameworkPolicy -Id <policyId>
13. Application Insights Monitoring
• There are two kinds of Application Insights logging available in a
policy
• User Journey Logging
• Configured at the Policy and Relying Party levels (together)
• Can be verbose
• Should only be used in development/debugging scenarios, not in production
• Insights Technical Profiles
• Specific Technical Profiles you call as Orchestration Steps in the User Journey
• You choose the content
Runtime
15. Application Insights Technical Profile
<TechnicalProfile Id="ApplicationInsights-Common">
<DisplayName>Application Insights</DisplayName>
<Protocol Name="Proprietary" Handler="Web.TPEngine.Providers.Insights.AzureApplicationInsightsProvider,
Web.TPEngine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
<Metadata>
<Item Key="InstrumentationKey">{Your Application Insights Key}</Item>
<Item Key="DeveloperMode">false</Item>
<Item Key="DisableTelemetry">false</Item>
</Metadata>
<InputClaims>
<InputClaim ClaimTypeReferenceId="PolicyId" PartnerClaimType="{property:Policy}"
DefaultValue="{Policy:PolicyId}" />
<InputClaim ClaimTypeReferenceId="CorrelationId" PartnerClaimType="{property:JourneyId}"
DefaultValue="{Context:CorrelationId}"/>
</InputClaims>
</TechnicalProfile>
<TechnicalProfile Id="ApplicationInsights-AfterSignIn">
<InputClaims>
<InputClaim ClaimTypeReferenceId="EventType" PartnerClaimType="eventName“
DefaultValue="SignInComplete" />
<InputClaim ClaimTypeReferenceId="objectId" PartnerClaimType="{property:ObjectId}"
DefaultValue="Not Set" />
</InputClaims>
<IncludeTechnicalProfile ReferenceId="ApplicationInsights-Common" />
</TechnicalProfile>
An input claim with a
PartnerClaimType="eventName" is
required.
This is used by the
AzureApplicationInsightsProvider to c
reate an event with the specified
value.
Properties of an event are added
through the syntax
{property:NAME}.
DefaultValue can be a static
value or a value that's resolved
by one of the supported
Claim Resolvers.
Runtime
16. Interacting with an AAD B2C Tenant
Azure Active Directory Tenant
Identity Experience Framework
B2C Policies
User Database Application Registrations
Microsoft Graph API
User
Applications
Runtime
OIDC
OAuth2, SAML
17. Using the Graph Explorer
• Requires an admin account native to the tenant you want to see
• Graph Explorer uses home realm discovery
• Cannot be an “invited admin”
• Still requires “Beta” endpoint for B2C property visibility
Runtime
https://developer.microsoft.com/graph/graph-explorer
19. Please take a few minutes to complete the feedback survey,
and we'll prepare a few questions to discuss.
https://aka.ms/B2CTheoryPostCallSurvey/
Feedback and Q&A
20. Thank you!
Vinu Gunasekaran
Program Manager, Microsoft
John Garland
VP Cloud Development & Instructor, Wintellect
Azure MVP, MCT, P-CSA
wintellect.com
@dotnetgator
Editor's Notes
Green = “You are here”
In today's session we are going to discuss tools and techniques that you can use to help you create custom policies that meet your needs. We're going to go pretty much through the while custom policy lifecycle, looking at different phases like:
Design - how can you get from requirements to custom policy, and what prior content is available for you to consume
Develop - what tools can you use to help you actually author your policies
Publish - You need to get your policies into your different environments like dev, test, staging, and production - how can you make your policies "Dev-ops" friendly?
Runtime - How can you make sure your policy logic is working as you intended, and if there are problems, what can you do to detect and correct them?
Integration - With your custom policies ready to go, how do you make sure that the applications that will be using them are working correctly?
As has been the case with the previous sessions. today's content does assume that you're familiar with the prerequisite material that is outlined in the session description. This includes:
An understanding of what Azure AD B2C is
Knowing how to do basic configuration and User Flow creation using Azure AD B2C
Understanding basic Azure AD B2C use cases
Also, if you haven't seen the previous sessions in this series, you may want to check out the recordings in order to supplement what we're going to be going over today
The first tool to discuss is the Azure AD B2C Visual Studio Code extension. Adding this extension to the Visual Studio Code editor helps you create, navigate, deploy, and troubleshoot Azure AD B2C custom policies. You can get this extension from the Visual Studio Marketplace, or directly from within Visual Studio Code.
<DEMO>
Open new instance of VS Code
Go to extensions, search for B2C
Show the title page, click “install”, etc.
Once again, we'll be covering several of the extension's features throughout this session
The first area to discuss is Design-Time. There are several tools available that you can use to help you with your initial policy design.
First and foremost, you need to be aware of the Azure AD B2C documentation resources, and in particular the Custom Policy sections.
<DEMO>
Show https://docs.microsoft.com/azure/active-directory-b2c
How-to guides, custom policy
UX customization custom email
Reference Building Blocks, Claims Transformations, String (the warnings come after the spells…)
Besides the Custom Claims “API reference” and examples in the official documents, the Azure AD B2C team also maintains a repository that includes an extensive set of policy samples.
This is extremely helpful because a lot of common scenarios that you may need to implement have been included and documented in this repository. Referencing this content is going to allow you to take advantage of work that has already been done. This eliminates a lot of the “exploration” or prototype/POC work you might otherwise have to do to figure out some of the basic facets that need to be included in your policies.
<DEMO>
Show https://github.com/azure-ad-b2c/samples
Scroll to show categorization/menu of options (search “password”)
Open “profiles” folder, show Progressive… The “progressive profile” policy that was the subject of the lab that was reviewed in the previous example in this series has been published.
Eventually, though, you are going to have to get your hands dirty and get in and code up your custom policies. This is where we start to see how the Azure AD B2C Visual Studio Code extension helps us out. The extension includes:
A Policy Explorer panel that lets you see the different declarations in the policy file that is currently open.
Right-click navigation support – right click on an item reference and see its declaration
Hover-help support
<DEMO>
The first place where this extension helps us is with policy file navigation. You may have noticed this being used in the previous session in this series.
“code .” from progressive profile example folder
Base file, use Explorer to open User Journeys/Signup-Sign In
LocalAccountSignUpWithLogonEmail Go to definition
ObjectId claim Go to definition
Hover on ClaimType, click link, show docs file being opened.
In addition to helping you get around your policies, the Azure AD B2C Visual Studio Code extension helps you to actually write them. It includes autocomplete support to help provide you with context-aware options for what elements and values you can include. And it also includes several macros you can use to quickly configure common policy elements.
<DEMO>
Intellisense
In Relying Party file
After BasePolicy section, type an opening “<“
Select Claims Providers Open/Close
Macros
Open the Command Palette - Shift-Control-P
Type B2C
Add a Claim Type, TextBox, DemoClaim, “This is being used for a demo”
So in addition to using the docs to find out how to configure the elements you need and using the sample repository to find common policy implementations, the Intellisense and macros can help you with creating correct policy definitions.
Now that you have assembled your policies, you may need to deploy them across several different environments. The problem is, generally you want to separate your environments so that each one has its own distinct Azure AD B2C tenant. And policy files are scoped to a given Azure AD B2C tenant in several ways. The tenant ID is included in the TrustFrameworkPolicy and Public PolicyUri elements of each policy file, and likely is also included in the BasePolicy declaration for any dependent files.
Also, as you saw in the previous session in this series, policy files generally include IDs that are used for logging into local accounts or for using custom claims; these IDs are also usually specific to a given Azure AD B2C tenant. And if your policy uses RESTFul technical profiles to call external HTTP endpoints, the URL that the policy uses is also sometimes scoped per environment.
This is a bit of a problem when it comes to having “DevOps friendly” policies that can be easily published to each one of your environment rings.
To help with this, the Azure AD B2C Visual Studio Code extension includes tooling to help parameterize your policy files and can generate environment-scoped files from these parameterized templates.
<DEMO>
Show policy file elements that are not “Devops friendly” – Tenant ID, Policy URI, Local Account SignIn Metadata, REST profile
Add a new REST profile –
Name = DemoRestProfile
URL = https://dev.demorestprofile.com
B2C Policy Build, yes to create file
Switch to WithSettings folder
Show settings substitution tokens – show REST item in RP file, show ID’s in extensions file
Show settings file
Re-run build show new Environments folder, and show content substituted.
NOTE – at this point, you would do this on your dev box BEFORE checking in and include the Environment folders. It is not externally automated yet.
Great – now you have policy files scoped to each environment…the next step is to automate deployment of your policies. To do so, the Microsoft Graph API has support for working with the various Azure AD B2C artifacts and resources. In addition to working directly with the Graph APIs, you can also use the Azure AD Powershell module – which wraps this functionality – to script automatic publishing. Be aware, you don’t *have* to use Powershell, you can also use the Graph APIs directly; sometimes Powershell scripting can be a bit more familiar to DevOps development and maintenance.
<DEMO>
connect-azuread –tenant AzureADB2CWebinarSeries.onmicrosoft.com
Get-AzureADMSTrustFrameworkPolicy
Note – currently requires the Azure AD PowerShell for Graph preview module
Note – can also use the Microsoft Graph API to work with policy files, requires Beta/Preview endpoints.
Once the policy files are published, you may want to look at telemetry information to help spot errors or to identify usage trends. To do so, you can integrate your policies with Azure’s Application Insights service.
Application Insights is an Application Performance Management service that is part of the Azure Monitor telemetry solution. In addition to providing a place where your applications can send log, metric, and event details, it also provides searching, reporting, and analysis features over that data.
There are two ways that your policies can directly integrate with Application Insights:
First, you can use User Journey logging to collect log information from your running Azure AD B2C policy. Be aware, though, that this is only meant to be a development & debugging solution, and isn’t meant to be used in production, since the logs include sensitive claims information that you will not want to be responsible for storing and securing. These logs can be quite verbose and somewhat cryptic – we’ll look at some tooling that can help you work with them.
Second, you can create and execute technical profiles that send data that you select as custom events to the Azure Application Insights service. This is useful not only for more discrete troubleshooting than the User Journey logs, but also to provide usage insights and performance metrics.
Let’s examine these two approaches in more detail:
You enable User Journey logging in two steps. First, you need to update the TrustFrameworkPolicy element to indicate the UserJourneyRecorderEndpoint, and also to declare that your policy is in “Development” mode.
Next, you update the RelyingParty section of your file to include a JourneyInsights element in its UserJourneyBehaviors section. In the JourneyInsights section you indicate:
Your telementry engine (Application Insights is currently supported)
The Instrumentation Key for your App Insights instance – each instance of the Azure Application Insights service includes an InstrumentationKey value – this value is specified when data is sent to App Insights so that the data being sent is routed to the proper instance of the service.
DeveloperMode is a performance setting for Application Insights. This updates the rate at which telemetry is gathered and emitted to the App Insights service. In developer mode, the App Insights tooling isn’t as concerned with preventing performance interruptions to the client application as it would normally be. As a result, telemetry flows faster to the service, but this is a setting that you generally do not want enabled in a production system.
Client and Server enabling speak to the origins of data being sent to App Insights in a web application. Including client data will add some client-side script to your web pages which will allow tracking page view performance and client-side errors.
<DEMO>
Show App Insights instance in portal
Show Application Key
Open up ProgressiveProfileWithAppInsights folder in Code
Show RP file
Run, show results in Code Extension
Besides Journey logging, you can include your own customized Application Insights technical profiles in your User Journeys. When you call the Application Insights technical profile, you also need to specify an Instrumentation Key as well as whether or not to publish data in Developer Mode.
You must also include a claim named “eventName” and provide a value that App Insights will use as the name in the custom event entries that it records. In addition to the name, you can use claims to provide additional data values in the event. To do so, you use the syntax {property:Name} and you can use values taken from the claims bag or environment values using the Azure AD B2C Custom Policy Claims Resolvers (we haven’t gone over those much in this series, but they are basically a special notation that allow you to retrieve information about your policy’s runtime environment.)
Notice that – similar to the Azure AD Technical Profile we showed in the previous session in this series – it is common to use the IncludeTechnicalProfile approach and a common base profile with the Application Insights Technical Profile. This way you can specify the Instrumentation Key and other App Insights settings in one place, and you can also gather a core set of telemetry details that will be included in each event, regardless of the event type.
<DEMO>
Show App Insights instance in portal
Show Application Key
Open up ProgressiveProfileWithAppInsights folder in Code
Show Extensions File
Show App Insights Claims Providers
Show Orchestration Steps with TP’s called in
Run (sign up new user, then sign in to get Loyalty #), show results in Search
In addition to gathering telemetry about the execution of our policies, we can also look the data that is being stored.
Normally, our end-user facing applications interact with our Azure AD B2C tenant through our Azure AD B2C User Flows or custom policies. These in turn leverage the functionality provided by the Identity Experience Framework to access the tooling that’s provided by the Azure AD tenant, including the User Information Data Store, application registrations, and other services.
However, Azure AD does provide an additional API endpoint that you can use to interact with the data stored in the tenant, via the Microsoft Graph API. Using the Microsoft Graph API endpoints, you can access this data and identify the values that have been stored in your tenant.
There are several ways you can work with the Microsoft Graph – you can issue direct REST calls, and there are APIs for several programming languages. There is also the Microsoft Graph explorer, which provides a web-based GUI that you can use to explore the contents of a graph.
There is one challenge, however, with working with the Graph Explorer with an Azure AD B2C tenant. The Explorer currently does what’s called “home realm discovery” on the user that signs into it – it will look at the identity of the user account, and that is the directory it will provide information for.
Now when you created your Azure AD B2C tenant from your Azure subscription, you were working from an account that was part of the Azure AD tenant that was used as that’s subscription’s ID provider – usually something like your company’s Azure AD tenant.
When your Azure AD B2C tenant was created the user who actually created the tenant was “invited” as a Guest user into the newly created Azure AD B2C tenant and made a global Admin. So your admins credentials – and typically the credentials of any developers from your organization that you similarly invite into your Azure AD B2C tenant – won’t work with the Microsoft Graph Explorer to peek into the contents of your Azure AD B2C directory.
So, in order to access information for your Azure AD B2C directory in the Graph Explorer, you need to create a user account that is LOCAL to the Azure AD B2C tenant itself. Then you can sign in as THAT user and use the Azure AD Graph Explorer.
<DEMO>
Sign into Graph endpoint: https://developer.microsoft.com/graph/graph-explorer/preview
Run query for users https://graph.microsoft.com/beta/users
Show Demo user, show firstname, surname
Show Identities…
Show extension attribute for Loyalty Number…
The final topic to address today is working with and troubleshooting integrating your Azure AD B2C Custom Policies (or even prebuilt User Flows) with your applications that rely on them for their Identity needs.
The first two sessions in this series covered the Identity protocols and some of the tools you can use in the Microsoft Identity Platform to help you integrate your applications with your Azure AD B2C tenant.
Let’s close this session by taking a minute to see how we can troubleshoot our policy’s integration into our applications, considering the underlying protocols.
One of the tools that you will want to use if you experience problems with your policy configuration is to examine the network traffic between your application and the Azure AD B2C policy endpoint. Considering the protocols, look at what is being requested and how.
Consider a web application – use the browser’s development tools to examine the network traffic when you make an authentication request. Is the endpoint correct? Does the Client ID match a registered application? Is the Redirect URI included in the list of URI’s listed for that application? (And check for small typos and port designations!) Are you requesting the scopes you think you need to be?
<DEMO>
Visual Studio – New Web Project, ASP.NET Core, MVC
Change Authentication
Domain = AzureADB2CWebinarSeries.onmicrosoft.com
Create App Registration
Demo ASP.NET Core MVC Application
Use copied URL
Update settings in app
Instance: "https://AzureADB2CWebinarSeries.b2clogin.com/tfp/" (switch from older login.microsoft.com approach)
Run/see
OOPS! What happened?
Look at output notice problem? (needs Implicit)
Add App Insights to the app
Make a signin request
Wait a few minutes
See the flow… (TODO – can I set dev mode???)