Gadget Fest Docs Help

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

  1. 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

  1. 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.

  1. Azure AD B2C Issues JWT Token:

  • Upon successful authentication, Azure AD B2C returns an ID Token and an Access Token.

  1. Frontend Calls WebAPI:

  • The frontend includes the access token in the Authorization header:

    Authorization: Bearer <access_token>
  1. WebAPI Validates Token:

  • The backend verifies the token using Microsoft Identity libraries.

  1. 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:

dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer

2. Configure Authentication in Program.cs

using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.Identity.Web; var policyName = builder.Configuration["AzureAdB2C:PolicyName"] ?? throw new InvalidOperationException("Azure AD configuration: PolicyName is missing."); var clientId = builder.Configuration["AzureAdB2C:ClientId"] ?? throw new InvalidOperationException("Azure AD configuration: ClientId is missing."); var instance = builder.Configuration["AzureAdB2C:Instance"] ?? throw new InvalidOperationException("Azure AD configuration: Instance is missing."); var domain = builder.Configuration["AzureAdB2C:Domain"] ?? throw new InvalidOperationException("Azure AD configuration: Domain is missing."); var authority = $"https://{instance}/tfp/{domain}/{policyName}/v2.0/"; builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddMicrosoftIdentityWebApi( options => { options.Authority = authority; options.Audience = clientId; options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters { ValidateIssuer = true, ValidIssuer = $"https://{instance}/{domain}/v2.0/", ValidateAudience = true, ValidAudience = clientId, ValidateLifetime = true }; options.Events = new JwtBearerEvents { OnAuthenticationFailed = context => { Console.WriteLine($"Authentication failed: {context.Exception}"); return Task.CompletedTask; } }; }, options => { builder.Configuration.Bind("AzureAdB2C", options); } );

3. Configuring appsettings.json

"AzureAdB2C": { "ClientId": "<GUID>", "TenantId": "<TenantId>", "Instance": "<B2CTenantName>.b2clogin.com", "Domain": "<B2CTenantName>.onmicrosoft.com", "ScopeName": "https://<B2CTenantName>.onmicrosoft.com/<ClientId>/user_impersonation", "PolicyName": "B2C_1_susi" }

4. Protecting API Endpoints

Apply the [Authorize] attribute to secure endpoints:

using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; [ApiController] [Route("api/[controller]")] public class SecureController : ControllerBase { [HttpGet] [Authorize] public IActionResult GetSecureData() { return Ok(new { message = "This is a secured endpoint." }); } }

Testing the Authentication Flow

  1. Obtain an access token from Azure AD B2C by logging in via the frontend.

  2. Send a request to the protected API endpoint with the access token:

    GET /api/secure Authorization: Bearer <access_token>
  3. 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.

10 July 2025