Azure AD B2C Authentication

What is Azure AD B2C?
Azure Active Directory Business to Consumer (Azure AD B2C) is an identity management solution that allows organizations to provide a seamless login experience to their customers. Unlike Azure Active Directory (Azure AD) which is typically used for managing employee identities and access within an organization, Azure AD B2C is specifically designed for consumer-facing applications. Here are some key aspects of Azure AD B2C:
Features and Capabilities
1. Customizable User Experiences:
– Sign-up and Sign-in:
Allows organizations to create custom sign-up, sign-in, and profile management experiences. These can be adapted to match the branding and user experience of the application.
– Social Identity Providers:
Supports integration with social identity providers like Google, Facebook, LinkedIn, and more, allowing users to sign in using their existing social media accounts.
– Local Accounts:
Users can also create accounts using their email addresses or usernames with passwords.
2. User Flows and Custom Policies:
– Predefined User Flows:
Azure AD B2C offers predefined user flows for common scenarios such as sign-up, sign-in, password reset, and profile editing. These flows are configurable through the Azure portal.
– Custom Policies:
For more complex scenarios, custom policies allow for fine-grained control over the identity experience, enabling advanced scenarios like multi-factor authentication, custom attribute collection, and integration with external identity providers.
3. Security and Compliance:
– Data Protection:
Provides robust security features, including encryption of data at rest and in transit, and compliance with various regulatory requirements like GDPR.
– Multi-Factor Authentication (MFA):
Supports MFA to enhance security by requiring an additional verification step during the sign-in process.
4. Scalability and Reliability:
– Global Reach:
Azure AD B2C leverages Azure’s global infrastructure to provide high availability and scalability, ensuring that user authentication is reliable and performant.
– Flexible Pricing:
Offers a pay-as-you-go pricing model based on the number of authentications and users, allowing businesses to scale their identity solution according to their needs.
5. Integration with Applications:
– OAuth2 and OpenID Connect:
Supports industry-standard protocols like OAuth2 and OpenID Connect, making it easier to integrate with various applications and services.
– API Access:
Allows secure access to APIs, enabling scenarios where user identity is required to access backend services.
Use Cases
– Consumer Applications:
Ideal for applications that require user registration and authentication, such as e-commerce platforms, online services, and mobile apps.
-B2C Services:
Enables organizations to manage and authenticate millions of consumers, providing a personalized and secure user experience.
– External Partner Access:
Facilitates secure access for external partners and customers to business applications and services.
Benefits
– Enhanced User Experience:
Provides a seamless and customizable login experience, improving user satisfaction and engagement.
– Simplified Identity Management:
Reduces the complexity of managing multiple identity providers and user credentials.
– Improved Security:
Offers advanced security features and compliance capabilities to protect user data and prevent unauthorized access.
Overall, Azure AD B2C helps organizations build secure and scalable identity solutions for their consumer-facing applications, enhancing both user experience and security.
Microservices with Azure AD B2C
Microservices bring flexibility but also security challenges. Let’s explore how Azure AD B2C can help secure microservices.
1. Microservices Security Challenges:
Microservices have unique security hurdles, especially when it comes to managing user access securely.
2. Azure AD B2C Basics:
Azure AD B2C is a service that handles user identities for consumer applications, making user management easier.
3. User Authentication and Authorization:
Azure AD B2C helps in securely letting users log in and controls what they can access within microservices.
4. Securing Communication:
Encrypting data ensures that communication between microservices and users is safe from prying eyes.
5. Centralized Identity Management:
Azure AD B2C simplifies managing users by taking care of authentication, reducing complexity for developers.
6. Handling Access Tokens:
Access tokens provided by Azure AD B2C are managed securely to ensure only authorized users can access microservices.
7. Logging and Monitoring:
Keeping track of user activity helps in identifying and responding to any security threats effectively.
Azure AD B2C is a valuable tool for securing microservices, ensuring that user data remains protected while taking advantage of the flexibility offered by a microservices architecture.
Prerequisites:
Before we dive into implementation, make sure you have the following prerequisites:
- An Azure account with appropriate permissions to create resources.
- .NET Core SDK installed on your machine.
- Basic understanding of microservices architecture and authentication concepts.
Azure Setup
-
Create Tenant:
- Log in to the Azure portal and navigate to the Azure AD B2C service.
- Create a new Azure AD B2C tenant if you haven’t already.
- Note down the Domain Name and Tenant ID, which will be used later.
-
Register Application:
- Register a new application in Azure AD B2C.
- Configure redirect URIs and permissions as needed.
- Obtain the Application ID, also known as the Client ID.
-
Define User Flows:
- Define user flows for sign-up, sign-in, and password reset as per your application requirements.
Let’s Setup Azure AD B2C
I am going to show how you can configure your authentication in a sample web application and this web application uses the dot net core MVC application and this application will call web API which will be then protected by the Azure AD B2C.
First let’s understand few concepts before dive into the implementation so you can setup this effortlessly.
You might hear about terms OIDC (OpenID Connect) and OAuth2
OIDC (OpenID Connect) is a technology that lets you log in to a website or app using your account from the other websites, like Google or Facebook. It’s a standard way to handle secure logins and makes it easier for developers to implement authentication and authorization in their applications.
OAuth 2.0 is the Authentication protocol that came in first and then followed by something was written on top of that and that’s called OIDC. So, Azure AD B2C supports OpenID Connect and OAuth 2.
We are going to see how we can protect your web app using Azure AD B2C which then supports these protocols.
What is the Sign in Flow?
The sign-in flow involves the following steps.
- Users go to the web app and select Sign-in.
- The app initiates an authentication request and redirects users to Azure AD B2C.
- Once users sign up or sign in and reset the password. Alternatively, they can sign in with a social account.
- After users sign in, Azure AD B2C returns an authorization code to the app which is initiating this request.
- Now the application does the following:
a. It exchanges the authorization code to get and ID token, access token, and refresh token.
b. It reads the ID token claims and persists an application authorization cookie.
c. It stores the refresh token in an in-memory cache for later use.
App Registration
Now we will go through the set of app registration process and once done with that I will show you which code you should download for the understating purpose and i will show you what you have ti modify there and how application has been configured.
Let’s see how this app architecture and registration looks like.

The first side of the image you can see is Application architecture under this we have Web API and Web Application, Web API could be even of Azure function or even a regular Web API.
The other side is Azure AD B2C endpoints and App registration, so we will have the apps registered and there will be the B2C endpoints.
The authorization token is exchanged with the ID token, access token, refresh token and then that will eventually use to get response from the web Api so that will be validate and give response.
When Web application is calling the Web Api, we will use authorization as a bearer token so we will invoke the bearer token and then send that to web Api.
Azure AD B2C
- I have logged into my Azure portal
When I land to the portal this will be my Default Directory. - Let’s create Azure AD B2C tenant.
> Go to the create resources

> On the search box start typing Azure AD B2C

> You will get something Azure active directory B2C > Click on create.
> Create a new tenant
> On create tenant page fill the required details such as Organization name and Domain name (should be unique) and select resource group if existing od create new resource group

> Review + Create
> Once tenant created you will get notified then click on the same notification or click on the Azure AD B2C
Directory has been changed.

- Once we’ve created tenant, we will setup couple of things such as:
a. App registration.
b. Create user flow.

Once we done with that, we’ll look how to configure that.> Go to the App registrations.
> Go to user flows.

> Let’s see how we can add new user flow.
> Click on the New user flow

> You can see all these available types; you can see Sign up and sign in most famous one and so recommended one because two in one policy, you can use both sign up and sign in together.
> Let’s click on Sign up and sign in and let’s create it.
> Choose Version as Recommended and create.
> Under the name choose unique name, also it cannot be changes after a user flow created.
> Under the identity providers we will choose Email signup as it our first setup.
> We have social identity provider, but we will do it first time do not expect these things to come up because you haven’t setup anything.

> Multifactor authentication you can just choose email.
> For MFA you can enforce it to off as we are not setting up multi factor authentication right now.
> User attributes and token claims, basically collect attributes written claim means something you wish to collect from user for ex:
Collect attribute:
I need your Name, Surname, City, LastName, Country/Region, the more i choose all these information will be collected from the user
Return Claim: What you have to send it back to the token, when you read the token, you can actually get all these return types whatever you are selecting here in Return Claim will be there to collected.
Select Collect attribute and Return claim from show more.

> Ok > Create.
> User flow created.

> Similarly go to the Profile editing name it and follow the same this as Sign up and sign in.
Basically, profile editing means after this user has been signed up if user wants to change his display name or he wants to change some information of this profile you can let him do by selecting the attribute you want him to edit.
> Create.

> Last one is Password reset.

Same you choose the name and then come back to select all these things and then any of the Return claim and create.


> Whatever I’ve explained has been created:

You can view and update user attributes and Application claims for the user flows.
App registration
Once you are done setting up user flow the next first thing is the App registration.
> Click on App registration.

New registration.
Register an application
> Name: The first app that we have to register is the web API, wo we will name it as web API demo.
> Supported account types: under the supported account types choose the third one “Accounts in any identity provider or organizational directory (for authenticating users with user flows)”, this is what we need to choose for the AD B2C so that users can use their own email id as well.
> Redirect URI: Leave Redirect URI as it is.
> Permission: Check for the “Grant admin consent and offline_access permissions”.
> Register.

Once the app is registered you can see on the overview Client ID and Tenant ID. Copy Client ID and Tenant ID, you will need it later.

Endpoints
If you click endpoints, you can see various endpoints for this app.

Expose an API
![]()
> Click on expose an API and then click on add a scope or click on the Set.
> Once you do a set you will see the default URL that will.

> Make it easy, I am going to name it as api, URL looks like https://practiceblogadb2cdemo.onmicrosoft.com/api
![]()
> Now click on Add a scope
![]()
Once you click on add a scope you can see the scope come under the above URL.
> Add two scopes here, task.read and task.write

You can see the scope direct URL it ends with task.read and task.write and this is the specific app registration link.
> Once you are with this come back to the App registration
![]()
> Click New registration.

> Name: WebAppDemo
> Supported account types: Choose third one again.
> Redirect URI: Select Web from the drop down, then give the URL https://localhost:80, as i am running it on local the port that is exposed is 80 that’s why i am giving it, so based on your port number you give that port here, and /signin-oidc thats the default you have to provide this, then check for Grant admin consent > Register.


Copy the Client ID and Tenant ID for the Web App as we do previously for the Web API and secure it somewhere as we will need it later.

Now we need to do little for configurations in the webapp.
Now the WebApp is calling Web API, so Web API permission should be there for the Web App.
Certificates & secrets
![]()
> Click on New client secret
![]()
> Add description and Choose Expires this is to how frequently the secret has to be expired. In general, in any organization this will be on rotational basis but for the demo purpose I will choose recommended one for 180 days (6 months).
When you create a client secret or upload a certificate, you must set an expiration date. The “Expires” option indicates when this client secret or certificate will no longer be valid.

> Add
Understand Certificates & Secrets
Certificates: Public key certificates are used to authenticate applications. They can be more secure than client secrets because they are less prone to being accidentally exposed.
Client Secrets: These are essentially passwords that applications use to authenticate themselves to Azure AD B2C.
> Once it created you have to copy this Value and secure/save it somewhere, because once leave this page the value cannot be copied it will be disabled.

In case you forgot to copy the value just delete it and create new to get the value.
API permission
> Navigate to API permission.
![]()
> Click on Add a permission
![]()
> You will be navigated to the Request API permission, It is where you configure the permissions your application needs to access APIs, whether they are Microsoft APIs, third-party APIs, or custom APIs you have registered. These permissions define what your application can do when interacting with these APIs, such as reading user profiles, accessing email, or writing data.
> There are multiple options by default, but we will be going to select our custom WebApiDemo under My APIs.

> Select both scopes task.read and task.write.

> Add permission
> The permissions are added here now Grant admin consent for Practice Blog Ad B2C (Your tenant) just beside the Add permission button and choose Yes.

> Now you can see the status is green for the WebApiDemo.

Code
Let’s go through the code quickly, this demo app I am using for demo is from Microsoft’s official GitHub repository itself you can download it from Microsoft official website or from here
I didn’t do anything fancy other than what I am going to explain you.


There are two projects TodoListClient and TodoListService.

> TodoListClient is a Web Application and TodoListService is a Web API.
> In terms of configuration go to appsettings.json under TodoListClient which is our Web App.
and you can see section called AzureAdB2C.

> Under the above section you can see everything I’ve explained and copied previously such as Instance, Domain, TenantId, SignUpSignInPolicyId, EditProfilePolicyId, ClientSecret, and ClientId.
- In the Instance we will use our sub domain name which practiceblogadb2cdemo along with b2clogin.com
- In the Domain we will use sub domain with .onmicrosoft.com
- TenantId, go to your directory and take the Tenant id from Wep App overview as explained earlier.
- ClientId, take Client id from Web App overview page.
Look below for in a parallel window for the reference.

- SignUpSignInPolicyId and EditProfilePolicyId, go to the user flows and the value should be match with the policy id in user flows.

-
ClientSecret, if you remember I asked to copy secret value on Certificates & secrets Page otherwise you cannot able to see that value once you leave the page. Put that value in ClientSecret.

> Do the same steps for TodoListService which is our Web Api.
Let’s understand how it’s work
Web App
> Let’s go to Startup.cs under the ConfigureServices the cookie will be handled.

> then in order to integrate with AD B2C this piece of code added, this is also preconfigured you do not need to do anything.

> If you see there is Configuration for TodoListScope, Just go to the appsettings.json you can see TodoListScope and it is task.read.
![]()
> Another piece is below, Under the Startup.cs here we have AddMicrosoftIdentityUI, this package will help us to bring up this sign in sign out flow, all these things are preconfigured.

Web Api
> In Startup.cs this will be having a bearer token, Whichever the request is received by this web api will be having an header of bearer token, this will authenticate against the token with Ad B2C configuration which we have done in appsettings.json and it will realize that the incoming token is valid and who is the client and who is the app registration.

Closure
Azure AD B2C is emerging as a powerful tool to address the security challenges of B2C microservices. By leveraging Azure AD B2C, organizations can easily streamline user authentication and authorization, secure communication channels, and centrally manage identities.
From securing user access with OAuth2 and OpenID Connect protocols to encrypting data transmissions to implementing advanced logging and monitoring strategies, Azure AD B2C offers a complete solution to create your microservices environment encounter protection -With support for advance security features, it positions itself as a versatile and reliable identity management service
Adopting Azure AD B2C not only increases the security level of your microservices architecture but also simplifies identity management, allowing developers to focus on building robust applications You can ensure your microservices are secure and work properly by following the best practices outlined in this guide, which provide a seamless and safe user experience
Adopting Azure AD B2C not only enhances the security posture of your microservices architecture but also simplifies identity management, allowing developers to focus on building robust applications. By following the best practices outlined in this guide, you can ensure that your microservices are both secure and efficient, providing a seamless and secure experience for your users.
As you continue to grow and scale your microservices, integrating Azure AD B2C will prove to be a strategic decision, delivering the security and convenience of Embrace Azure AD B2C to create a secure, user-friendly ecosystem de protect your microservices.
