What is Azure B2C?

Azure B2C may just be the greatest thing since sliced bread.  The real power of Azure’s public cloud (as compared to AWS and GCP) is in their AAD centric approach.   This post will not delve into the basics of AAD – but suffice to say that all of Azure’s access control and identity solutions reside INSIDE your AAD tenant.  While identities can be federated to Azure, native AAD identities provide you with a great deal of power and flexibility.

Azure B2C is Identity as a Service. A Web App (e.g. ASP.NET Core app) can use B2C for it’s AUTHENTICATION. Also, for certain apps, B2C can be used Authorization. For others, the authorization flow has to come from an external source (like a SQL Server database).

Apps, apps and apps

Active Directory, handles both human users, robo users (managed service accounts) and computers. Azure AD goes a step beyond handling identities and computers. It also allows Application ‘Registrations’ – which allows AAD to manage some of the common lifecycle pieces of ANY application. You read that right – ANY application! Regardless of the stack that your application is using and regardless of where it is situated physically, Azure AD can provide you with a SIGN UP solution, a SIGN ON Solution (including SSO), a Sign Off Solution and a few other common use cases (such as Password Reset).

Imagine NOT having to worry about building Sign Up, Sign Out, Sign On or Password Reset for any of your applications.

That’s the power of Azure AD.

What APPs can Azure B2C be applied to? (difference between AAD Enterprise Apps  and AAD App Registrations)

Azure B2C  is primarily for your CONSUMER facing applications. This is in contrast to Enterprise Applications that are part of ‘Enterprise’ apps on Azure AD (Apps like github, O365 apps, Workflow Analytics…)

So, B2C can handle Authentication. What about Authorization?

Authorization – has to be done OUTSIDE of Azure B2C tenant for most use cases. For simple use cases (e.g. endpoint access), it is possible to use Azure B2C and Custom Attributes in SAML to define an authorization workflow.

Azure B2C
B2C Solution design for authorization outside of Azure B2C

How exactly does SSO work in Azure B2C? If an App is hosted on premises and the Identity Auth is handled by Azure…? Doesn’t SSO require cookies? I thought Azure B2C used tokens…??

Although sessions are cookie based and tokens are not, B2C does use Tokens exclusively (JWT tokens).

This is how sessions (SSO) comes in:

  • User signed into App A – needs to switch to App B (she is already signed into App A).  She gets redirected to B2C endpoint that is configured in App B. B2C returns a token for App B – which is validated by App B. App B validates the token and detects that there is a session in the browser (session is under the SAME TENANT name).
  • OAuth 2.0 can allow custom attributes. B2C defines a Policy attribute  along with a Scope. These two attributes (which are returned in every valid JWT token) allow an app to ‘let a user in’ as well as ‘allow access to resources such as API endpoints’.  Some resources can be granted access this way (using OAuth 2.0 scope attributes).
  • Adding custom applications requires Azure AD Premium. You can also active Azure Active Directory Premium free for one month. SSO integration in Active Directory is totally different from SSO integration in an application through AD B2C.
  • However, other resources, such as GROUPS of user, may need to be retrieved in a different way back to the app.
  • RBAC and Custom Roles – you can create your own custom roles. Just like built-in roles, you can assign custom roles to users, groups, and service principals at management group, subscription, and resource group scopes.

I am sold – How do I go about migrating my on prem ADFS apps to Azure ?

ADFS App Authentications can be handled by Azure AD B2C. Migrating all your application authentication to Azure AD is optimal, as it gives you a single control plane for identity and access management.Your applications may use modern or legacy protocols for authentication. 

  • One control plane to allow seamless and secure access to your on-premises applications. 
  • Consider first migrating applications that use modern authentication protocols (such as SAML and Open ID Connect).
  • These apps can be reconfigured to authenticate with Azure AD via  registering the application in Azure AD. OR  a built-in connector in our App Gallery 
  • Apps using older protocols (WSE 1.0) can be integrated using Application Proxy.
  • Apps that use SAML 2.0 for authentication can be configured for SAML-based single sign-on (SAML-based SSO). With SAML-based SSO, you can map users to specific application roles based on rules that you define in your SAML claims.
  • Understanding client assertion in OpenID Connect. When using authorization code flow or hybrid flow in OpenID Connect, the client exchanges an authorization code for an access token. During this step, the client has to authenticate itself to the server.

  • For additional security, you can use client assertion instead of a client secret. With client assertion, the client uses an X.509 certificate to prove the token request came from the client. The client certificate is installed on the web server. Generally, it will be easier to restrict access to the certificate, than to ensure that nobody inadvertently reveals a client secret. For more information about configuring certificates in a web app, see Using Certificates in Azure Websites Applications

Where does OAuth enter?

  • OAuth can be used for both – authentication (access id –> JWT access Token) as well as authorization (Custom Attributes, Resource Access JWT Token).
  • You can use the OAuth 2.0 authorization code grant in apps installed on a device to gain access to protected resources, such as web APIs.
  • By using the Azure Active Directory B2C (Azure AD B2C) implementation of OAuth 2.0, you can add sign-up, sign-in, and other identity management tasks to your mobile and desktop apps.
  • All of these policies are a result of OAuth custom attributes
  • OAuth 2.0 authorization code grant – access id (authentication only) and grant tokens (resource access).
  • 4 MAIN types of Policies  can be introduced through custom attributes – Sign Up Policies, Sign In Policies, Password Reset, Profile Edit

registered application receives tokens and communicates with Azure AD B2C by sending requests to these endpoints:

  • https://<tenant-name>.b2clogin.com/<tenant-name>.onmicrosoft.com/<policy-name>/oauth2/v2.0/authorize
  • https://<tenant-name>.b2clogin.com/<tenant-name>.onmicrosoft.com/<policy-name>/oauth2/v2.0/token

What are the different types of FLOWS in Azure B2C? – Implicit Flow vs. Authorization Code Flow

Single Page Apps – These types of applications are “untrusted clients” since our server-side code has no control over the environment they run in.  Even regular web applications have these issues. People can easily alter or inject javascript code on a page through the developer console.

IMPLICIT (Direct) FLOW because no app runtime to store the session

GET https://{tenant}.b2clogin.com/{tenant}.onmicrosoft.com/{policy}/oauth2/v2.0/authorize? client_id=90c0fe63-bcf2-44d5-8fb7-b8bbc0b29dc6 &response_type=id_token+token &redirect_uri=https%3A%2F%2Faadb2cplayground.azurewebsites.net%2F &response_mode=fragment &scope=openid%20offline_access &state=arbitrary_data_you_can_receive_in_the_response &nonce=12345

Authorization Code FLOW (Indirect)  

You can configure the session behavior, including the session TTL and how Azure AD B2C shares the session across policies and applications.

When ID tokens are acquired from the /authorize endpoint, it’s done using the implicit flow, which is often used for users signing in to JavaScript-based web applications. When ID tokens are acquired from the /token endpoint, it’s done using the authorization code flow, which keeps the token hidden from the browser.

Authorization Code Flow

OAuth 2.0 authorization code grant in apps installed on a device to gain access to protected resources, such as web APIs. By using the Azure Active Directory B2C (Azure AD B2C) implementation of OAuth 2.0, you can add sign-up, sign-in, and other identity management tasks to your mobile and desktop apps

Authorization Server – handles the trust relationships between the parties in a flow. It is responsible for verifying the user’s identity, granting and revoking access to resources, and issuing tokens. It is also known as the identity provider.

To support these applications, Azure Active Directory B2C (Azure AD B2C) uses the OAuth 2.0 implicit flow. The OAuth 2.0 authorization implicit grant flow is described in section 4.2 of the OAuth 2.0 specification. In implicit flow, the app receives tokens directly from the Azure Active Directory (Azure AD) authorize endpoint, without any server-to-server exchange. All authentication logic and session handling is done entirely in the JavaScript client with either a page redirect or a pop-up box.

XSS attacks occur when a vulnerable application allows arbitrary javascript code to be injected and executed on your page. This often occurs through the form fields on the page.

  1. Did you use a built in sign up policy – or define your own? Sign Up Policy, Password Reset Policy, Sign Off Policy, SSO Policy. Policy = User Attributes, Which IdPs, What type of Token to return
  2. Users are browser, mobile Devices or both? (Endpoints Auth OpenID and Authorization OAuth)?
  3. Are you interested in Authorization Flows or only Authentication Flows?
  4. Azure AD B2C acts as the service provider (SP)
    Azure AD B2C acts as a service provider when connecting to the SAML identity provider. It’s a federation proxy between your application and the SAML identity provider.

Approval / Invitation Flows

    1. Custom Attribute – and Self Sign Up  User flow: Having a custom attribute to determine whether a user has been “approved” or not. You would let users sign up by themselves and you would create an experience or flow that queries the Azure AD Graph for users that haven’t been “approved” and then either approve them or delete them.
    2. Special invitation flow.  When you invite a user, you’d create the user through the Azure AD Graph. You would then direct your users to the Password Reset policy as their “account verification” flow.

What is the difference between ID Tokens and Access Tokens? (Token Types) 

  • ID tokens carry identity information encoded in the token itself, which must be a JWT. Access tokens are used to gain access to resources by using them as bearer tokens. Refresh tokens exist solely to get more access tokens.
  • So – there are 3 types of tokens – ID Token, Access Token (bearer token) and refresh token (used to get more access tokens)

A web, mobile, or single page application can be protected by OAuth access, ID tokens (JWT), or SAML tokens. When a user tries to access a protected resource on the app, the app checks whether there is an active session on the application side. If there is no app session or the session has expired, the app will take the user to Azure AD B2C to sign-in page.

GraphServiceClient graphClient = new GraphServiceClient( authProvider );

var user = new User
{
	DisplayName = "John Smith",
	Identities = new List<ObjectIdentity>()
	{
		new ObjectIdentity
		{
			SignInType = "userName",
			Issuer = "contoso.onmicrosoft.com",
			IssuerAssignedId = "johnsmith"
		},
		new ObjectIdentity
		{
			SignInType = "emailAddress",
			Issuer = "contoso.onmicrosoft.com",
			IssuerAssignedId = "jsmith@yahoo.com"
		},
		new ObjectIdentity
		{
			SignInType = "federated",
			Issuer = "facebook.com",
			IssuerAssignedId = "5eecb0cd"
		}
	},
	PasswordProfile = new PasswordProfile
	{
		Password = "password-value",
		ForceChangePasswordNextSignIn = false
	},
	PasswordPolicies = "DisablePasswordExpiration"
};

await graphClient.Users
	.Request()
	.AddAsync(user);

First Step – Create a new tenant

First step, you need to ‘Create an Azure B2C Tenant’ in your portal. The App Registration (for your consumer app), will need to take place here – as opposed to in the main AAD menu.

Second Step – Figure out your redirect URL (for testing, you can use https://jwt.ms) – for the case of successful authentication. Where should the user be sent after successful authentication (back to the web app or mobile app)

Before we get to user flows, look at the ‘endpoints’ for your app

Notice the OAuth token and OAuth authorize endpoints.

These are what YOUR MOBILE App or Web App will need to use to redirect the login request (or password reset request etc.).

Now, you are all ready to start configuring User Flows

User Flows are built in policies to manage the signing in, singing out, SSO and MFA for your app’s users

Sign Up Policy – Define the Providers your app will support (FB etc.) and the Attributes your app needs (email, first name..)

B2C Approval Flows

You can achieve this by two different flows:

  1. Having a custom attribute to determine whether a user has been “approved” or not. You would let users sign up by themselves and you would create an experience or flow that queries the Azure AD Graph for users that haven’t been “approved” and then either approve them or delete them.
  2. Building an invitation flow.  When you invite a user, you’d create the user through the Azure AD Graph. You would then direct your users to the Password Reset policy as their “account verification” flow.

Add a user via  Graph API, Azure Identity Architect

GraphServiceClient graphClient = new GraphServiceClient( authProvider );

var user = new User
{
	AccountEnabled = true,
	DisplayName = "displayName-value",
	MailNickname = "mailNickname-value",
	UserPrincipalName = "upn-value@tenant-value.onmicrosoft.com",
	PasswordProfile = new PasswordProfile
	{
		ForceChangePasswordNextSignIn = true,
		Password = "password-value"
	}
};

await graphClient.Users
	.Request()
	.AddAsync(user);

What about internal (on prem) IdPs such as ADFS?

My users need single-sign-on with a SAML-compliant identity provider like ADFS, Salesforce, or Shibboleth. Azure AD B2C acts as the service provider (SP)
Azure AD B2C acts as a service provider when connecting to the SAML identity provider. It’s a federation proxy between your application and the SAML identity provider.

Azure AD B2C achieves SAML interoperability in one of two ways:

  • By acting as an identity provider (IdP) and achieving single-sign-on (SSO) with SAML-based service providers (your applications)
  • By acting as a service provider (SP) and interacting with SAML-based identity providers like Salesforce and ADFS

Add ADFS as a SAML identity provider using custom policies in Azure Active Directory B2C

Create the signing key

  1. Select Policy Keys and then select Add.
  2. For Options, choose Generate.
  3. In Name, enter TokenSigningKeyContainer. The prefix B2C_1A_ might be added automatically.
  4. For Key type, select RSA.
  5. For Key usage, select Signature.
  6. Select Create.

Create the encryption key

  1. Select Policy Keys and then select Add.
  2. For Options, choose Generate.
  3. In Name, enter TokenEncryptionKeyContainer. The prefix B2C_1A_ might be added automatically.
  4. For Key type, select RSA.
  5. For Key usage, select Encryption.
  6. Select Create.

If you want users to sign in using an ADFS account, you need to define the ADFS account as a claims provider that Azure AD B2C can communicate with through an endpoint. The endpoint provides a set of claims that are used by Azure AD B2C to verify that a specific user has authenticated.

You can define an ADFS account as a claims provider by adding it to the ClaimsProviders element in the extension file of your policy. For more information, see define a SAML identity provider technical profile.

B2C SSO Sessions, Azure Identity Architect

The Azure AD B2C session can be configured with the following scopes:

  • Tenant – This setting is the default. Using this setting allows multiple applications and user flows in your B2C tenant to share the same user session. For example, once a user signs into an application, the user can also seamlessly sign into another one upon accessing it
  • Application – This setting allows you to maintain a user session exclusively for an application, independent of other applications.  For example, you can use this setting if you want the user to sign in to Contoso Pharmacy regardless of whether the user is already signed into Contoso Groceries.
  • Policy – This setting allows you to maintain a user session exclusively for a user flow, independent of the applications using it. For example, if the user has already signed in and completed a multi-factor authentication (MFA) step, the user can be given access to higher-security parts of multiple applications, as long as the session tied to the user flow doesn’t expire.
  • Disabled – This setting forces the user to run through the entire user flow upon every execution of the policy.

Need an azure identity architect or help with your AWS or GCP cloud journey?  Set up a free 30 minute consultation.

Anuj Varma is an Azure Identity Architect with hands on experience in AWS Identity, Azure Identity and GCP Identity Use Cases. He is professionally certified and specializes in AWS Infastructure, Azure and GCP Infrastructure, Automation, Data Protection and Terraform based devops.

 

Anuj holds professional certifications in Google Cloud, AWS as well as certifications in Docker and App Performance Tools such as New Relic. He specializes in Cloud Security, Data Encryption and Container Technologies.

Initial Consultation

Anuj Varma – who has written posts on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.