Archive for March, 2025|Monthly archive page

Where are MicrosoftIdentity Area, AccountController, and Action?

The MicrosoftIdentity area and Account controller are part of the Microsoft Identity Web library, which provides integration with Azure AD and Azure AD B2C for ASP.NET Core applications. This library simplifies the process of adding authentication and authorization to your application.

Microsoft Identity Web Library

The Microsoft Identity Web library includes built-in controllers and views for handling common authentication tasks, such as signing in, signing out, and editing user profiles. These are organized within the MicrosoftIdentity area.

Key Components

  1. MicrosoftIdentity Area:
    • The MicrosoftIdentity area contains the built-in controllers and views provided by the Microsoft Identity Web library.
    • This area is automatically registered and used by the library to handle authentication-related actions.
  2. Account Controller:
    • The Account controller within the MicrosoftIdentity area handles actions such as signing in, signing out, and editing user profiles.
    • These actions correspond to the methods provided by the Microsoft Identity Web library to manage user authentication and profile management.

Example of Built-In Actions

  • SignIn: Initiates the sign-in process.
  • SignOut: Initiates the sign-out process.
  • EditProfile: Initiates the profile editing process (if configured).

Example Usage in _LoginPartial.cshtml

In the _LoginPartial.cshtml file, you are using the asp-areaasp-controller, and asp-action attributes to link to the built-in actions provided by the Microsoft Identity Web library:

<ul class="navbar-nav">
@if (User.Identity?.IsAuthenticated == true)
{
    @if (!string.IsNullOrEmpty(options.EditProfilePolicyId))
    {
        <li class="nav-item">
            <a class="nav-link text-dark" asp-area="MicrosoftIdentity" asp-controller="Account" asp-action="EditProfile">Hello @User.Identity?.Name!</a>
        </li>
    }
    else
    {
        <span class="navbar-text text-dark">Hello @User.Identity?.Name!</span>
    }
    <li class="nav-item">
        <a class="nav-link text-dark" asp-area="MicrosoftIdentity" asp-controller="Account" asp-action="SignOut">Sign out</a>
    </li>
}
else
{
    <li class="nav-item">
        <a class="nav-link text-dark" asp-area="MicrosoftIdentity" asp-controller="Account" asp-action="SignIn">Sign in</a>
    </li>
}
</ul>

How do each of the actions know where to go in AAD B2C to accomplish the tasks?

The actions in the _LoginPartial.cshtml file (SignInSignOut, and EditProfile) know where to go in Azure AD B2C to accomplish their tasks because they are configured through the Microsoft Identity Web library, which handles the integration with Azure AD B2C. The configuration in your Program.cs file and the settings in your appsettings.json or appsettings.Development.json file provide the necessary information for these actions to work correctly.

Configuration in Program.cs

In Program.cs file, you configure the authentication middleware to use Azure AD B2C:

using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.Identity.Web;
using Microsoft.Identity.Web.UI;
using System.IdentityModel.Tokens.Jwt;

var builder = WebApplication.CreateBuilder(args);

// This is required to be instantiated before the OpenIdConnectOptions starts getting configured.
// By default, the claims mapping will map claim names in the old format to accommodate older SAML applications.
// This flag ensures that the ClaimsIdentity claims collection will be built from the claims in the token
JwtSecurityTokenHandler.DefaultMapInboundClaims = false;

// The appsettings file containing AAD B2C endpoints for policy endpoints.
var azureAdB2CSection = builder.Configuration.GetSection("AzureAdB2C");

// Add services to the container. Here we are adding the MicrosoftIdentity middleware to have
// those actions for signing in, signing out, or editing the user profile.
builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApp(azureAdB2CSection)
    .EnableTokenAcquisitionToCallDownstreamApi()
    .AddInMemoryTokenCaches();

builder.Services.AddControllersWithViews();
builder.Services.AddRazorPages()
    .AddMicrosoftIdentityUI();

var app = builder.Build();

if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseRouting();

app.UseAuthentication();
app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.MapRazorPages();

app.Run();

Configuration in appsettings.Development.json

appsettings.Development.json file contains the Azure AD B2C settings:

{
  "AzureAdB2C": {
    "Instance": "https://myapp.b2clogin.com",
    "TenantId": "myapp.onmicrosoft.com",
    "ClientId": "49000000-0000-0000-aaaa-cc8844bbdd33",
    "Domain": "tenant.onmicrosoft.com",
    "SignedOutCallbackPath": "/signout/B2C_1_susi",
    "SignUpSignInPolicyId": "B2C_1_SignInSignUp",
    "ResetPasswordPolicyId": "B2C_1_Reset",
    "EditProfilePolicyId": "B2C_1_EditProfile",
    "CallbackPath": "/signin-oidc"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  }
}

The actions in the _LoginPartial.cshtml file (SignIn, SignOut, and EditProfile) know where to go in Azure AD B2C to accomplish their tasks because they are configured through the Microsoft Identity Web library, which handles the integration with Azure AD B2C. The configuration in your Program.cs file and the settings in your appsettings.json or appsettings.Development.json file provide the necessary information for these actions to work correctly.

How Actions Know Where to Go

  1. SignIn:
  • The SignIn action uses the SignUpSignInPolicyId from the configuration to initiate the sign-in process.
  • The Microsoft Identity Web library handles the redirection to the Azure AD B2C sign-in page using the specified policy.
  1. SignOut:
  • The SignOut action uses the SignedOutCallbackPath from the configuration to handle the sign-out process.
  • The Microsoft Identity Web library handles the redirection to the Azure AD B2C sign-out page and then redirects back to the specified callback path.
  1. EditProfile:
  • The EditProfile action uses the EditProfilePolicyId from the configuration to initiate the profile editing process.
  • The Microsoft Identity Web library handles the redirection to the Azure AD B2C profile editing page using the specified policy.

Summary

The actions (SignIn, SignOut, and EditProfile) in the _LoginPartial.cshtml file know where to go in Azure AD B2C because they are configured through the Microsoft Identity Web library. The configuration in your Program.cs file and the settings in your appsettings.Development.json file provide the necessary information for these actions to work correctly. The Microsoft Identity Web library handles the redirection to the appropriate Azure AD B2C pages based on the specified policies.

Azure AD B2C: Custom Policies and User Journeys Explained

Overview: Azure AD B2C custom policies are like the rules that define how users log in and interact with your app. Think of them as the blueprint for creating a secure and personalized user experience.

Key Features:

  • Customizable UI & User Journeys: Imagine customizing the login page to match your app’s theme and guiding users through specific steps based on their actions.
  • Integration with External Providers: You can allow users to log in using their Google or Facebook accounts, making it super convenient.
  • Claims & Business Logic: Claims are like temporary data storage (e.g., user’s name or email) used during the login process. You can transform these claims to fit your app’s needs.

Starter Pack Policies:

  • LocalAccounts: Users log in with local accounts only.
  • SocialAccounts: Users log in with social accounts only.
  • SocialAndLocalAccounts: Users can choose between local and social accounts.
  • SocialAndLocalAccountsWithMFA: Adds multifactor authentication for extra security.

Claims:

  • Definition: Claims are like variables in programming, storing user info temporarily during login. They are stored in a claims bag during this process. Each step pulls claims out of the bag, uses / changes them, and puts them back in the bag for the next step.
  • Usage:
    • Saved, Read, Updated: E.g., updating user profile info.
    • External Providers: E.g., Google or Facebook logins.
    • User Interaction: Collected during sign-up/profile edit.
    • Transformed: Modified before being included in the token.

Customizing UI:

  • Use self-asserted technical profiles to collect user info.
    • Technical profiles are interfaces created to communicate with different types of parties. All interactions where the user is expected to provide input are self-asserted technical profiles.
  • Customize the UI with HTML content via content definition element.
  • Localize strings using the localization element.

Relying Party Policy:

  • Executes specific user journeys for relying party applications (service providers in SAML).
  • Specifies user journey and claims in the token.

User Journeys & Orchestration Steps:

Best Practices:

  • Extension Policy: Create business logic here, not in the base policy.
  • Technical Profile Inclusion: Reduce duplication by sharing core functionality.
  • Avoid Directory Writes During Sign-In: Prevent throttling issues.
  • High Availability: Ensure external dependencies (e.g., REST APIs) are highly available.
  • Global Deployment: Use Azure CDN for custom HTML templates.

Troubleshooting:

Links: