B2C Authentication Flow
Overview
This document outlines the authentication flow for a Business-to-Consumer (B2C) authentication mechanism in .NET 8 WebAPI project using Azure AD B2C.
Prerequisites
.NET 8 SDK installed
An Azure AD B2C tenant
Registered applications in Azure AD B2C
Articles
https://learn.microsoft.com/en-us/azure/active-directory-b2c/enable-authentication-web-api?tabs=csharpclient
https://learn.microsoft.com/en-us/azure/active-directory-b2c/identity-provider-microsoft-account?wt.mc_id=searchAPI_azureportal_inproduct_rmskilling&sessionId=14d080a26e254332abb9dc7f60aad7a5&pivots=b2c-user-flow
Authentication Flow
User Initiates Authentication:
The frontend (SPA or mobile app) redirects the user to the Azure AD B2C sign-in page.
Alternatively developer can use the swagger page to sign in
User Logs In or Registers:
If the user is new, they register using email, phone number, or social accounts.
If the user exists, they log in.
Azure AD B2C Issues JWT Token:
Upon successful authentication, Azure AD B2C returns an ID Token and an Access Token.
Frontend Calls WebAPI:
The frontend includes the access token in the Authorization header:
Authorization: Bearer <access_token>
WebAPI Validates Token:
The backend verifies the token using Microsoft Identity libraries.
API Returns Response:
If the token is valid, the API processes the request and returns data.
If the token is invalid, an unauthorized response (401) is returned.
Implementation
1. Setting Up Authentication in Gadgetfest WebAPI
Add the required NuGet package:
2. Configure Authentication in Program.cs
3. Configuring appsettings.json
4. Protecting API Endpoints
Apply the [Authorize] attribute to secure endpoints:
Testing the Authentication Flow
Obtain an access token from Azure AD B2C by logging in via the frontend.
Send a request to the protected API endpoint with the access token:
GET /api/secure Authorization: Bearer <access_token>If the token is valid, the API returns a success response; otherwise, it returns 401 Unauthorized.
Conclusion
This guide provides a structured approach to implementing Azure AD B2C authentication in a .NET 8 WebAPI project. By following this setup, you can secure API endpoints and enable seamless authentication for your B2C users.