diff --git a/.github/workflows/publish_entraid.yml b/.github/workflows/publish_entraid.yml new file mode 100644 index 0000000..241e424 --- /dev/null +++ b/.github/workflows/publish_entraid.yml @@ -0,0 +1,63 @@ +name: Publish Microsoft Entra ID for Simple Authentication on NuGet + +permissions: + contents: write + id-token: write + +on: + push: + branches: [ master ] + paths: [ 'src/SimpleAuthentication.EntraId/**' ] + workflow_dispatch: + +env: + NET_VERSION: '11.x' + PROJECT_NAME: src/SimpleAuthentication.EntraId + PROJECT_FILE: SimpleAuthentication.EntraId.csproj + TAG_NAME: entraid + RELEASE_NAME: SimpleAuthenticationTools.EntraId + +jobs: + build: + name: Publish Microsoft Entra ID for Simple Authentication on NuGet + runs-on: ubuntu-latest + + steps: + - name: Checkout + uses: actions/checkout@v6 + with: + fetch-depth: 0 # avoid shallow clone so nbgv can do its work. + + - name: Setup .NET SDK ${{ env.NET_VERSION }} + uses: actions/setup-dotnet@v5 + with: + dotnet-version: ${{ env.NET_VERSION }} + dotnet-quality: 'ga' + + - name: Nerdbank.GitVersioning + uses: dotnet/nbgv@v0.4 + id: nbgv + with: + path: ${{ env.PROJECT_NAME }} + + - name: Package + run: dotnet pack -c Release -o . '${{ env.PROJECT_NAME }}/${{ env.PROJECT_FILE }}' + + - name: NuGet login (OIDC → temp API key) + uses: NuGet/login@v1 + id: login + with: + user: ${{ secrets.NUGET_USER }} + + - name: Publish on NuGet + run: dotnet nuget push *.nupkg --api-key ${{steps.login.outputs.NUGET_API_KEY}} -s https://api.nuget.org/v3/index.json + + - name: Create release + uses: softprops/action-gh-release@v2 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + tag_name: v${{ steps.nbgv.outputs.NuGetPackageVersion }} + name: ${{ env.RELEASE_NAME }} ${{ steps.nbgv.outputs.NuGetPackageVersion }} + draft: false + prerelease: false diff --git a/.gitignore b/.gitignore index 400160e..ae2fa48 100644 --- a/.gitignore +++ b/.gitignore @@ -352,3 +352,4 @@ MigrationBackup/ /src/SimpleAuthentication/SimpleAuthentication.xml /src/SimpleAuthentication.Abstractions/SimpleAuthentication.Abstractions.xml /src/SimpleAuthentication.Swashbuckle/SimpleAuthentication.Swashbuckle.xml +/src/SimpleAuthentication.EntraId/SimpleAuthentication.EntraId.xml diff --git a/README.md b/README.md index e57224c..48c9a9a 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ [![NuGet](https://img.shields.io/nuget/dt/SimpleAuthenticationTools)](https://www.nuget.org/packages/SimpleAuthenticationTools) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://github.com/marcominerva/SimpleAuthentication/blob/master/LICENSE) -A library to easily integrate Authentication in ASP.NET Core projects. Currently it supports JWT Bearer, API Key and Basic Authentication in both Controller-based and Minimal API projects. +A library to easily integrate Authentication in ASP.NET Core projects. Currently it supports JWT Bearer, API Key and Basic Authentication in both Controller-based and Minimal API projects. Service-to-service authentication with Microsoft Entra ID is available as an [optional package](#microsoft-entra-id-authentication). > [!IMPORTANT] > **Update from Version 2.x to 3.x** @@ -378,11 +378,58 @@ app.MapGet("api/me", (ClaimsPrincipal user) => .RequireAuthorization(policyNames: "UserProfile") ``` +## Microsoft Entra ID authentication + +If your services use Microsoft Entra ID to talk to each other, you can install the optional [SimpleAuthentication.EntraId](https://github.com/marcominerva/SimpleAuthentication/tree/master/src/SimpleAuthentication.EntraId) package. Search for *SimpleAuthenticationTools.EntraId* in the **Package Manager GUI** or run the following command in the **.NET CLI**: + +```shell +dotnet add package SimpleAuthenticationTools.EntraId +``` + +The package is built on top of [Microsoft.Identity.Web](https://learn.microsoft.com/entra/msidweb/) and adds a Microsoft Entra ID scheme next to the ones you are already using, without changing the default scheme and without adding a fallback policy: + +```csharp +using SimpleAuthentication; + +var builder = WebApplication.CreateBuilder(args); + +// Registers the schemes defined in the Authentication section, then adds a scheme (named EntraId) +// that validates the access tokens issued by a single Microsoft Entra ID tenant. +builder.Services.AddSimpleAuthentication(builder.Configuration) + .AddEntraIdJwtBearer(builder.Configuration.GetSection("AzureAd")) + // The following lines are required only if the application calls other APIs. + .EnableTokenAcquisitionToCallDownstreamApi() + .AddInMemoryTokenCaches(); + +// Registers an HTTP client that calls another API using an app-only access token. +builder.Services.AddEntraIdHttpClient("Inventory", builder.Configuration.GetSection("DownstreamApis:Inventory")) + .AddTypedClient(); + +var app = builder.Build(); + +// ... + +// Requires an app-only access token that contains the Orders.Read application role. +app.MapGet("api/orders", () => TypedResults.Ok()) + .RequireEntraIdApplicationRole("Orders.Read"); + +app.Run(); +``` + +In short: + +- only the endpoints that explicitly require it are protected by Microsoft Entra ID. Policies based on application roles accept app-only tokens and reject the ones issued on behalf of a user; +- HTTP clients acquire app-only tokens using the credentials (for example a managed identity federated with the app registration) and the token cache configured for Microsoft.Identity.Web. They can send requests only to the configured HTTPS base address and never forward the token of the incoming request; +- HTTP clients use timeouts, retries and circuit breaker, but the requests that can write data are never retried automatically. + +Refer to the [documentation of the package](https://github.com/marcominerva/SimpleAuthentication/tree/master/src/SimpleAuthentication.EntraId) for configuration and usage details. + ## Samples - JWT Bearer ([Controller](https://github.com/marcominerva/SimpleAuthentication/tree/master/samples/Controllers/JwtBearerSample) | [Minimal API](https://github.com/marcominerva/SimpleAuthentication/tree/master/samples/MinimalApis/JwtBearerSample)) - API Key ([Controller](https://github.com/marcominerva/SimpleAuthentication/tree/master/samples/Controllers/ApiKeySample) | [Minimal API](https://github.com/marcominerva/SimpleAuthentication/tree/master/samples/MinimalApis/ApiKeySample)) - Basic Authentication ([Controller](https://github.com/marcominerva/SimpleAuthentication/tree/master/samples/Controllers/BasicAuthenticationSample) | [Minimal API](https://github.com/marcominerva/SimpleAuthentication/tree/master/samples/MinimalApis/BasicAuthenticationSample)) +- Microsoft Entra ID ([Minimal API](https://github.com/marcominerva/SimpleAuthentication/tree/master/samples/MinimalApis/EntraIdMicroservices)) ## Contribute diff --git a/SimpleAuthentication.slnx b/SimpleAuthentication.slnx index 3c8b3af..e0bfc87 100644 --- a/SimpleAuthentication.slnx +++ b/SimpleAuthentication.slnx @@ -11,13 +11,21 @@ + + + + + + + + diff --git a/samples/MinimalApis/EntraIdMicroservices/InventoryApi/InventoryApi.csproj b/samples/MinimalApis/EntraIdMicroservices/InventoryApi/InventoryApi.csproj new file mode 100644 index 0000000..7b2db9a --- /dev/null +++ b/samples/MinimalApis/EntraIdMicroservices/InventoryApi/InventoryApi.csproj @@ -0,0 +1,14 @@ + + + + net11.0 + enable + enable + simpleauthentication-entraid-inventoryapi + + + + + + + diff --git a/samples/MinimalApis/EntraIdMicroservices/InventoryApi/Program.cs b/samples/MinimalApis/EntraIdMicroservices/InventoryApi/Program.cs new file mode 100644 index 0000000..995a503 --- /dev/null +++ b/samples/MinimalApis/EntraIdMicroservices/InventoryApi/Program.cs @@ -0,0 +1,34 @@ +using SimpleAuthentication; + +var builder = WebApplication.CreateBuilder(args); + +// Add services to the container. +builder.Services.AddProblemDetails(); + +// This API accepts Microsoft Entra ID tokens only and does not call other APIs, +// so the scheme is added to the standard authentication builder and no credentials are required. +builder.Services.AddAuthentication() + .AddEntraIdJwtBearer(builder.Configuration.GetSection("AzureAd")); + +var app = builder.Build(); + +// Configure the HTTP request pipeline. +app.UseHttpsRedirection(); + +app.UseExceptionHandler(); +app.UseStatusCodePages(); + +app.UseAuthentication(); +app.UseAuthorization(); + +// This endpoint requires an app-only access token that contains the 'Inventory.Read' application role. +app.MapGet("api/products", () => +{ + Product[] products = [new(1, "Keyboard", 12), new(2, "Monitor", 0)]; + return TypedResults.Ok(products); +}) +.RequireEntraIdApplicationRole("Inventory.Read"); + +app.Run(); + +public record class Product(int Id, string Name, int AvailableQuantity); diff --git a/samples/MinimalApis/EntraIdMicroservices/InventoryApi/Properties/launchSettings.json b/samples/MinimalApis/EntraIdMicroservices/InventoryApi/Properties/launchSettings.json new file mode 100644 index 0000000..020f213 --- /dev/null +++ b/samples/MinimalApis/EntraIdMicroservices/InventoryApi/Properties/launchSettings.json @@ -0,0 +1,14 @@ +{ + "$schema": "https://json.schemastore.org/launchsettings.json", + "profiles": { + "InventoryApi": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": false, + "applicationUrl": "https://localhost:7102;http://localhost:5102", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/samples/MinimalApis/EntraIdMicroservices/InventoryApi/appsettings.Development.json b/samples/MinimalApis/EntraIdMicroservices/InventoryApi/appsettings.Development.json new file mode 100644 index 0000000..0c208ae --- /dev/null +++ b/samples/MinimalApis/EntraIdMicroservices/InventoryApi/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/samples/MinimalApis/EntraIdMicroservices/InventoryApi/appsettings.json b/samples/MinimalApis/EntraIdMicroservices/InventoryApi/appsettings.json new file mode 100644 index 0000000..6b3088a --- /dev/null +++ b/samples/MinimalApis/EntraIdMicroservices/InventoryApi/appsettings.json @@ -0,0 +1,14 @@ +{ + "AzureAd": { + "Instance": "https://login.microsoftonline.com/", + "TenantId": "", // Required: the ID of the Microsoft Entra ID tenant + "ClientId": "" // Required: the application (client) ID of the Inventory API + }, + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*" +} diff --git a/samples/MinimalApis/EntraIdMicroservices/OrdersApi/OrdersApi.csproj b/samples/MinimalApis/EntraIdMicroservices/OrdersApi/OrdersApi.csproj new file mode 100644 index 0000000..1bd1d30 --- /dev/null +++ b/samples/MinimalApis/EntraIdMicroservices/OrdersApi/OrdersApi.csproj @@ -0,0 +1,15 @@ + + + + net11.0 + enable + enable + simpleauthentication-entraid-ordersapi + + + + + + + + diff --git a/samples/MinimalApis/EntraIdMicroservices/OrdersApi/Program.cs b/samples/MinimalApis/EntraIdMicroservices/OrdersApi/Program.cs new file mode 100644 index 0000000..4397245 --- /dev/null +++ b/samples/MinimalApis/EntraIdMicroservices/OrdersApi/Program.cs @@ -0,0 +1,53 @@ +using Microsoft.Identity.Web; +using SimpleAuthentication; + +var builder = WebApplication.CreateBuilder(args); + +// Add services to the container. +builder.Services.AddProblemDetails(); + +// Add the authentication schemes defined in the Authentication section of the configuration (none in this sample), +// then add Microsoft Entra ID as an additional scheme. Default schemes and authorization policies are not changed. +builder.Services.AddSimpleAuthentication(builder.Configuration) + .AddEntraIdJwtBearer(builder.Configuration.GetSection("AzureAd")) + // The following lines are needed only because this API calls another API using its own identity. + .EnableTokenAcquisitionToCallDownstreamApi() + .AddInMemoryTokenCaches(); + +// Register the HTTP client that calls the Inventory API using an app-only access token. +builder.Services.AddEntraIdHttpClient("Inventory", builder.Configuration.GetSection("DownstreamApis:Inventory")) + .AddTypedClient(); + +var app = builder.Build(); + +// Configure the HTTP request pipeline. +app.UseHttpsRedirection(); + +app.UseExceptionHandler(); +app.UseStatusCodePages(); + +app.UseAuthentication(); +app.UseAuthorization(); + +// This endpoint requires an app-only access token that contains the 'Orders.Read' application role. +app.MapGet("api/orders", async (InventoryClient inventoryClient, CancellationToken cancellationToken) => +{ + // The availability of the ordered products is provided by the Inventory API. + var products = await inventoryClient.GetProductsAsync(cancellationToken); + var orders = products.Select(product => new Order(product.Id, product.Name, Quantity: 1, IsAvailable: product.AvailableQuantity > 0)); + + return TypedResults.Ok(orders); +}) +.RequireEntraIdApplicationRole("Orders.Read"); + +app.Run(); + +public record class Order(int Id, string ProductName, int Quantity, bool IsAvailable); + +public record class Product(int Id, string Name, int AvailableQuantity); + +public class InventoryClient(HttpClient httpClient) +{ + public async Task> GetProductsAsync(CancellationToken cancellationToken = default) + => await httpClient.GetFromJsonAsync>("api/products", cancellationToken) ?? []; +} diff --git a/samples/MinimalApis/EntraIdMicroservices/OrdersApi/Properties/launchSettings.json b/samples/MinimalApis/EntraIdMicroservices/OrdersApi/Properties/launchSettings.json new file mode 100644 index 0000000..bee0fff --- /dev/null +++ b/samples/MinimalApis/EntraIdMicroservices/OrdersApi/Properties/launchSettings.json @@ -0,0 +1,14 @@ +{ + "$schema": "https://json.schemastore.org/launchsettings.json", + "profiles": { + "OrdersApi": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": false, + "applicationUrl": "https://localhost:7101;http://localhost:5101", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/samples/MinimalApis/EntraIdMicroservices/OrdersApi/appsettings.Development.json b/samples/MinimalApis/EntraIdMicroservices/OrdersApi/appsettings.Development.json new file mode 100644 index 0000000..0c208ae --- /dev/null +++ b/samples/MinimalApis/EntraIdMicroservices/OrdersApi/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/samples/MinimalApis/EntraIdMicroservices/OrdersApi/appsettings.json b/samples/MinimalApis/EntraIdMicroservices/OrdersApi/appsettings.json new file mode 100644 index 0000000..140bd19 --- /dev/null +++ b/samples/MinimalApis/EntraIdMicroservices/OrdersApi/appsettings.json @@ -0,0 +1,42 @@ +{ + "AzureAd": { + "Instance": "https://login.microsoftonline.com/", + "TenantId": "", // Required: the ID of the Microsoft Entra ID tenant + "ClientId": "", // Required: the application (client) ID of the Orders API + // Credentials are needed because this API calls the Inventory API. + // In Azure, use a managed identity that is federated with the app registration, so that no secret is required. + // For local development, see the README file. + "ClientCredentials": [ + { + "SourceType": "SignedAssertionFromManagedIdentity", + "ManagedIdentityClientId": "" + } + ] + }, + "DownstreamApis": { + "Inventory": { + "BaseAddress": "https://localhost:7102/", // Required: it must use HTTPS and end with a trailing slash + "Scope": "api:///.default" // Required: the Application ID URI of the Inventory API, followed by /.default + //"AuthenticationScheme": "EntraId", // Default: EntraId + //"AllowHttpOnLoopback": false, // Default: false + //"Resilience": { + // "TotalRequestTimeout": { + // "Timeout": "00:00:30" // Default: 30 seconds + // }, + // "AttemptTimeout": { + // "Timeout": "00:00:10" // Default: 10 seconds + // }, + // "Retry": { + // "MaxRetryAttempts": 3 // Default: 3 + // } + //} + } + }, + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*" +} diff --git a/samples/MinimalApis/EntraIdMicroservices/README.md b/samples/MinimalApis/EntraIdMicroservices/README.md new file mode 100644 index 0000000..7569c2e --- /dev/null +++ b/samples/MinimalApis/EntraIdMicroservices/README.md @@ -0,0 +1,111 @@ +# Microsoft Entra ID microservices sample + +This sample shows how two APIs can talk to each other using Microsoft Entra ID, without sharing secrets: + +- **OrdersApi** exposes the `GET /api/orders` endpoint, that requires an app-only access token with the `Orders.Read` application role. To build the response, it calls the Inventory API using its own identity. +- **InventoryApi** exposes the `GET /api/products` endpoint, that requires an app-only access token with the `Inventory.Read` application role. + +``` +Client application --(Orders.Read)--> OrdersApi --(Inventory.Read)--> InventoryApi +``` + +The Orders API registers Microsoft Entra ID next to the schemes of [Simple Authentication](https://github.com/marcominerva/SimpleAuthentication) (none is configured in this sample), while the Inventory API uses the standard authentication builder. In both cases Microsoft Entra ID is the only scheme, so ASP.NET Core automatically uses it as the default one, but only the endpoints that call `RequireEntraIdApplicationRole` require a token: the registration doesn't add a fallback policy. + +## Configure Microsoft Entra ID + +The sample needs a Microsoft Entra ID tenant where you can register applications and grant admin consent. The following steps use the [Microsoft Entra admin center](https://entra.microsoft.com). The meaning of each setting is explained in the [Microsoft Entra ID setup](https://github.com/marcominerva/SimpleAuthentication/tree/master/src/SimpleAuthentication.EntraId#microsoft-entra-id-setup) section of the package documentation. + +In this sample, the Inventory API is the *target API* of the Orders API, and the Orders API is in turn the *target API* of the client application: each target API needs its application role and the `idtyp` optional claim. + +**1. Register the Inventory API** + +1. Go to **App registrations** and create a new single-tenant registration named, for example, _Inventory API_. +2. In **Expose an API**, set the **Application ID URI** to the proposed value (`api://`). +3. In **App roles**, create a role with **Allowed member types** set to _Applications_ and **Value** set to `Inventory.Read`. +4. In **Token configuration**, select **Add optional claim**, **Access** and then **idtyp**. This claim allows the API to accept app-only tokens only. +5. In **Manifest**, set `requestedAccessTokenVersion` (in the `api` section) to `2`, so that the API receives version 2.0 access tokens. + +**2. Register the Orders API** + +1. Create another single-tenant registration named, for example, _Orders API_, and repeat the steps 2-5 using `Orders.Read` as the value of the application role. +2. In **API permissions**, select **Add a permission**, **APIs my organization uses**, then choose the Inventory API and add the `Inventory.Read` **application permission**. +3. Select **Grant admin consent**. Now the Orders API is allowed to get tokens for the Inventory API that contain the `Inventory.Read` role. + +**3. Register a client application** + +To call the Orders API you need an application that has been granted the `Orders.Read` role: create a third registration (for example _Orders client_) with a client secret, add the `Orders.Read` application permission of the Orders API and grant admin consent, as in the previous step. + +Refer to the official documentation for more information about [app roles](https://learn.microsoft.com/entra/identity-platform/howto-add-app-roles-in-apps) and [optional claims](https://learn.microsoft.com/entra/identity-platform/optional-claims). + +## Configure the sample + +The _appsettings.json_ files contain placeholders only. The APIs do not start until `TenantId` and `ClientId` contain valid identifiers, so you can immediately see what is missing. + +The projects are already enabled to use [user secrets](https://learn.microsoft.com/aspnet/core/security/app-secrets), that are stored outside of the repository. From the folder of the sample, set the identifiers of the Inventory API (they are not secrets, so you can also write them in its _appsettings.json_ file): + +```shell +dotnet user-secrets set "AzureAd:TenantId" "" --project InventoryApi +dotnet user-secrets set "AzureAd:ClientId" "" --project InventoryApi +``` + +Then, configure the Orders API: + +```shell +dotnet user-secrets set "AzureAd:TenantId" "" --project OrdersApi +dotnet user-secrets set "AzureAd:ClientId" "" --project OrdersApi +dotnet user-secrets set "DownstreamApis:Inventory:Scope" "api:///.default" --project OrdersApi +``` + +The Orders API needs credentials to prove its identity when it requests a token for the Inventory API. + +**Local development** + +Managed identities are not available on a development machine, so use an app registration dedicated to development and provide its credentials with user secrets or environment variables, so that they never end up in source control. For example, create a client secret in **Certificates & secrets** and run the following commands: + +```shell +dotnet user-secrets set "AzureAd:ClientCredentials:0:SourceType" "ClientSecret" --project OrdersApi +dotnet user-secrets set "AzureAd:ClientCredentials:0:ClientSecret" "" --project OrdersApi +``` + +You can also use a certificate: see [Credentials overview for Microsoft.Identity.Web](https://learn.microsoft.com/entra/msidweb/authentication/credentials-overview) for all the supported options. + +**Azure** + +When the Orders API is hosted in Azure, use a managed identity federated with its app registration, so that no secret is needed: + +1. Create a user-assigned managed identity and assign it to the Azure resource that hosts the Orders API. +2. In the app registration of the Orders API, go to **Certificates & secrets**, **Federated credentials** and add a credential with the **Managed Identity** scenario, selecting the managed identity. +3. Set `AzureAd:ClientCredentials:0:ManagedIdentityClientId` to the client ID of the managed identity (the `SignedAssertionFromManagedIdentity` source type is already configured in _appsettings.json_) and `DownstreamApis:Inventory:BaseAddress` to the HTTPS address of the Inventory API. + +The complete procedure is described in [Configure an application to trust a managed identity](https://learn.microsoft.com/entra/workload-id/workload-identity-federation-config-app-trust-managed-identity). + +## Run the sample + +Start both the APIs: + +```shell +dotnet run --project InventoryApi +dotnet run --project OrdersApi +``` + +The Inventory API listens on `https://localhost:7102` and the Orders API on `https://localhost:7101`. They use HTTPS with the ASP.NET Core development certificate: if it is not trusted yet, run `dotnet dev-certs https --trust`. + +Get an app-only token for the Orders API using the client application registered before, then call the endpoint: + +```shell +curl -X POST "https://login.microsoftonline.com//oauth2/v2.0/token" -d "grant_type=client_credentials" -d "client_id=" -d "client_secret=" -d "scope=api:///.default" + +curl "https://localhost:7101/api/orders" -H "Authorization: Bearer " +``` + +The response contains the orders, with the availability of the products provided by the Inventory API. If you call the Orders API without a token, with a token that does not contain the `Orders.Read` role or with a token issued on behalf of a user, the request is rejected. The same happens to the Orders API if it has not been granted the `Inventory.Read` role. + +If something doesn't work, the [Verifying the token](https://github.com/marcominerva/SimpleAuthentication/tree/master/src/SimpleAuthentication.EntraId#verifying-the-token) and [Troubleshooting](https://github.com/marcominerva/SimpleAuthentication/tree/master/src/SimpleAuthentication.EntraId#troubleshooting) sections of the package documentation show how to check the content of the tokens and the most common causes of errors. + +## What to look at + +- The HTTP client of the Orders API can send requests only to the configured base address, that must use HTTPS. To use HTTP on the local machine, set `DownstreamApis:Inventory:AllowHttpOnLoopback` to `true` in the development settings. +- Requests that can write data (_POST_, _PUT_, _PATCH_, _DELETE_) are never retried automatically. Timeouts, retries and circuit breaker can be configured in the `DownstreamApis:Inventory:Resilience` section. +- The token received by the Orders API is never forwarded to the Inventory API. + +See the [documentation of the package](https://github.com/marcominerva/SimpleAuthentication/tree/master/src/SimpleAuthentication.EntraId) for all the details. diff --git a/src/SimpleAuthentication.EntraId/EntraId/EntraIdApplicationRoleRequirement.cs b/src/SimpleAuthentication.EntraId/EntraId/EntraIdApplicationRoleRequirement.cs new file mode 100644 index 0000000..9ba668f --- /dev/null +++ b/src/SimpleAuthentication.EntraId/EntraId/EntraIdApplicationRoleRequirement.cs @@ -0,0 +1,86 @@ +using System.Security.Claims; +using Microsoft.AspNetCore.Authorization; + +namespace SimpleAuthentication.EntraId; + +/// +/// Requires an app-only access token, issued by Microsoft Entra ID and validated by a specific authentication scheme, +/// that contains at least one of the allowed application roles. +/// +/// +/// +/// Only the identities created by are evaluated. In this way, claims that come from other authentication +/// schemes (for example a locally issued JWT that contains a roles claim) can never satisfy the requirement, even when the +/// authorization policy accepts more than one scheme. +/// +/// +/// A token is considered app-only when it contains the idtyp claim with the app value and no delegated scopes. +/// Tokens that are issued on behalf of a user are rejected, even if the user has been assigned to one of the allowed roles. +/// The idtyp claim is optional and must be explicitly added to the access tokens of the API: tokens without it are rejected. +/// See Optional claims reference for more information. +/// +/// +/// +public class EntraIdApplicationRoleRequirement : AuthorizationHandler, IAuthorizationRequirement +{ + private const string IdentityTypeClaimType = "idtyp"; + private const string ApplicationIdentityType = "app"; + private const string RolesClaimType = "roles"; + private const string ScpClaimType = "scp"; + private const string ScopeClaimType = "http://schemas.microsoft.com/identity/claims/scope"; + + private readonly HashSet roles; + + /// + /// Gets the name of the authentication scheme that must have created the identity that holds the application roles. + /// + public string SchemeName { get; } + + /// + /// Gets the application roles that satisfy the requirement. The token must contain at least one of them. + /// + public IEnumerable AllowedRoles => roles; + + /// + /// Creates a new instance of the class. + /// + /// The name of the Microsoft Entra ID authentication scheme. + /// The application roles that satisfy the requirement. + /// is . + /// is empty, or is empty or contains empty values. + public EntraIdApplicationRoleRequirement(string schemeName, IEnumerable allowedRoles) + { + ArgumentException.ThrowIfNullOrWhiteSpace(schemeName); + ArgumentNullException.ThrowIfNull(allowedRoles); + + roles = allowedRoles.ToHashSet(StringComparer.Ordinal); + if (roles.Count == 0 || roles.Any(string.IsNullOrWhiteSpace)) + { + throw new ArgumentException("At least one application role must be specified, and roles cannot be empty.", nameof(allowedRoles)); + } + + SchemeName = schemeName; + } + + /// + protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, EntraIdApplicationRoleRequirement requirement) + { + if (context.User.Identities.Any(requirement.IsSatisfiedBy)) + { + context.Succeed(requirement); + } + + return Task.CompletedTask; + } + + /// + public override string ToString() + => $"{nameof(EntraIdApplicationRoleRequirement)}:The '{SchemeName}' scheme must provide an app-only token with one of the following roles: ({string.Join("|", roles)})"; + + private bool IsSatisfiedBy(ClaimsIdentity identity) + => identity.IsAuthenticated + && string.Equals(identity.AuthenticationType, SchemeName, StringComparison.Ordinal) + && identity.HasClaim(IdentityTypeClaimType, ApplicationIdentityType) + && !identity.HasClaim(claim => claim.Type is ScpClaimType or ScopeClaimType) + && identity.HasClaim(claim => claim.Type is RolesClaimType or ClaimTypes.Role && roles.Contains(claim.Value)); +} diff --git a/src/SimpleAuthentication.EntraId/EntraId/EntraIdDefaultSchemePostConfigureOptions.cs b/src/SimpleAuthentication.EntraId/EntraId/EntraIdDefaultSchemePostConfigureOptions.cs new file mode 100644 index 0000000..fb3415e --- /dev/null +++ b/src/SimpleAuthentication.EntraId/EntraId/EntraIdDefaultSchemePostConfigureOptions.cs @@ -0,0 +1,40 @@ +using Microsoft.AspNetCore.Authentication; +using Microsoft.Extensions.Options; + +namespace SimpleAuthentication.EntraId; + +/// +/// Keeps the default authentication scheme of the application unchanged when Microsoft Entra ID schemes are added. +/// +/// +/// When a single authentication scheme is registered and no default scheme is set, ASP.NET Core automatically uses that scheme as the default one. +/// Adding a Microsoft Entra ID scheme would silently disable this behavior and break the endpoints that rely on it, so the scheme is set explicitly. +/// +internal sealed class EntraIdDefaultSchemePostConfigureOptions(IOptions entraIdSchemeOptions) : IPostConfigureOptions +{ + private const string SuppressAutoDefaultSchemeSwitchName = "Microsoft.AspNetCore.Authentication.SuppressAutoDefaultScheme"; + + public void PostConfigure(string? name, AuthenticationOptions options) + { + if (options.DefaultScheme is not null || (AppContext.TryGetSwitch(SuppressAutoDefaultSchemeSwitchName, out var isSuppressed) && isSuppressed)) + { + return; + } + + var entraIdSchemeNames = entraIdSchemeOptions.Value.SchemeNames; + var otherSchemes = options.Schemes.Where(scheme => !entraIdSchemeNames.Contains(scheme.Name)).Take(2).ToList(); + + if (otherSchemes is [var schemeSelectedAutomatically]) + { + options.DefaultScheme = schemeSelectedAutomatically.Name; + } + } +} + +/// +/// Contains the names of the Microsoft Entra ID schemes registered by the application. +/// +internal sealed class EntraIdSchemeOptions +{ + public HashSet SchemeNames { get; } = []; +} diff --git a/src/SimpleAuthentication.EntraId/EntraId/EntraIdDefaults.cs b/src/SimpleAuthentication.EntraId/EntraId/EntraIdDefaults.cs new file mode 100644 index 0000000..5ccdb9c --- /dev/null +++ b/src/SimpleAuthentication.EntraId/EntraId/EntraIdDefaults.cs @@ -0,0 +1,12 @@ +namespace SimpleAuthentication.EntraId; + +/// +/// Default values used by Microsoft Entra ID authentication. +/// +public static class EntraIdDefaults +{ + /// + /// Default value for AuthenticationScheme property. + /// + public const string AuthenticationScheme = "EntraId"; +} diff --git a/src/SimpleAuthentication.EntraId/EntraId/EntraIdHttpClientKeys.cs b/src/SimpleAuthentication.EntraId/EntraId/EntraIdHttpClientKeys.cs new file mode 100644 index 0000000..bceb1e7 --- /dev/null +++ b/src/SimpleAuthentication.EntraId/EntraId/EntraIdHttpClientKeys.cs @@ -0,0 +1,21 @@ +using Polly; + +namespace SimpleAuthentication.EntraId; + +internal static class EntraIdHttpClientKeys +{ + /// + /// Set by the caller on a request to state that it is idempotent, even if its HTTP method is not safe. + /// + public static readonly HttpRequestOptionsKey Idempotent = new("SimpleAuthentication.EntraId.Idempotent"); + + /// + /// Set by on the requests whose destination and headers have been validated. + /// + public static readonly HttpRequestOptionsKey Validated = new("SimpleAuthentication.EntraId.Validated"); + + /// + /// Set by on the resilience context of every attempt. The value tells whether the request can be retried. + /// + public static readonly ResiliencePropertyKey RetryAllowed = new("SimpleAuthentication.EntraId.RetryAllowed"); +} diff --git a/src/SimpleAuthentication.EntraId/EntraId/EntraIdHttpClientSettings.cs b/src/SimpleAuthentication.EntraId/EntraId/EntraIdHttpClientSettings.cs new file mode 100644 index 0000000..160ec63 --- /dev/null +++ b/src/SimpleAuthentication.EntraId/EntraId/EntraIdHttpClientSettings.cs @@ -0,0 +1,41 @@ +namespace SimpleAuthentication.EntraId; + +/// +/// Options class provides information needed to call an API that is protected by Microsoft Entra ID using an app-only access token. +/// +public class EntraIdHttpClientSettings +{ + /// + /// Gets or sets the base address of the API to call. It must be an absolute HTTPS URI that ends with a trailing slash. + /// + /// + /// The HTTP client can send requests only to addresses that start with this value, so that the access token cannot be sent to a different destination. + /// + /// + public Uri BaseAddress { get; set; } = null!; + + /// + /// Gets or sets the scope that is used to request the access token, in the {Application ID URI}/.default format + /// (for example api://00000000-0000-0000-0000-000000000000/.default). + /// + /// + /// App-only tokens are always requested for all the application roles that have been granted to the caller on a single API, + /// so exactly one scope that ends with /.default is required. + /// + public string Scope { get; set; } = null!; + + /// + /// Gets or sets the name of the authentication scheme whose Microsoft Entra ID configuration (client ID and credentials) is used to acquire the access token (Default: EntraId). + /// + /// + public string AuthenticationScheme { get; set; } = EntraIdDefaults.AuthenticationScheme; + + /// + /// Gets or sets a value indicating whether can use HTTP instead of HTTPS when it refers to the local machine (Default: ). + /// + /// + /// This option exists for local development only. Addresses that do not refer to the loopback interface always require HTTPS, + /// because the access token must never be sent over an unencrypted connection. + /// + public bool AllowHttpOnLoopback { get; set; } +} diff --git a/src/SimpleAuthentication.EntraId/EntraId/EntraIdRequestGuardHandler.cs b/src/SimpleAuthentication.EntraId/EntraId/EntraIdRequestGuardHandler.cs new file mode 100644 index 0000000..fcfe7ed --- /dev/null +++ b/src/SimpleAuthentication.EntraId/EntraId/EntraIdRequestGuardHandler.cs @@ -0,0 +1,67 @@ +using Microsoft.Net.Http.Headers; + +namespace SimpleAuthentication.EntraId; + +/// +/// Ensures that the requests sent by an Entra ID HTTP client can only reach the configured base address and cannot carry +/// credentials chosen by the caller. +/// +/// +/// It is the outermost handler of the client, so it validates the request exactly as it has been created by the caller, +/// before any other handler (for example service discovery) has the opportunity to change it. Validated requests are marked, +/// so that adds the access token only to them. +/// +internal sealed class EntraIdRequestGuardHandler(string clientName, Uri baseAddress) : DelegatingHandler +{ + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + if (!IsAllowedDestination(request.RequestUri)) + { + throw new InvalidOperationException($"The request targets a destination outside the base address configured for the Entra ID HTTP client '{clientName}'."); + } + + if (request.Headers.NonValidated.Contains(HeaderNames.Authorization)) + { + throw new InvalidOperationException($"The Authorization header cannot be set on the requests sent by the Entra ID HTTP client '{clientName}', because the app-only access token is added automatically."); + } + + if (request.Headers.NonValidated.Contains(HeaderNames.Host)) + { + throw new InvalidOperationException($"The Host header cannot be set on the requests sent by the Entra ID HTTP client '{clientName}'."); + } + + request.Options.Set(EntraIdHttpClientKeys.Validated, true); + + return base.SendAsync(request, cancellationToken); + } + + protected override HttpResponseMessage Send(HttpRequestMessage request, CancellationToken cancellationToken) + => throw new NotSupportedException($"The Entra ID HTTP client '{clientName}' does not support synchronous requests, because access tokens are acquired asynchronously."); + + private bool IsAllowedDestination(Uri? requestUri) + => requestUri is { IsAbsoluteUri: true } + && requestUri.UserInfo.Length == 0 + && string.Equals(requestUri.Scheme, baseAddress.Scheme, StringComparison.Ordinal) + && string.Equals(requestUri.IdnHost, baseAddress.IdnHost, StringComparison.OrdinalIgnoreCase) + && requestUri.Port == baseAddress.Port + && requestUri.AbsolutePath.StartsWith(baseAddress.AbsolutePath, StringComparison.Ordinal) + && !ContainsDotSegment(requestUri.AbsolutePath); + + private static bool ContainsDotSegment(string path) + { + // Uri removes dot segments, but not the ones hidden behind percent-encoded slashes (for example "..%2F") or followed by + // path parameters (for example "..;"). Servers and proxies may interpret them anyway, moving the request outside the base address. + if (!path.Contains('%') && !path.Contains(';')) + { + return false; + } + + string decodedPath; + while ((decodedPath = Uri.UnescapeDataString(path)) != path) + { + path = decodedPath; + } + + return path.Split('/', '\\').Any(segment => segment.Split(';')[0] is "." or ".."); + } +} diff --git a/src/SimpleAuthentication.EntraId/EntraId/EntraIdTokenHandler.cs b/src/SimpleAuthentication.EntraId/EntraId/EntraIdTokenHandler.cs new file mode 100644 index 0000000..d587667 --- /dev/null +++ b/src/SimpleAuthentication.EntraId/EntraId/EntraIdTokenHandler.cs @@ -0,0 +1,56 @@ +using System.Net.Http.Headers; +using Microsoft.Identity.Abstractions; + +namespace SimpleAuthentication.EntraId; + +/// +/// Adds to the requests an app-only access token acquired through Microsoft.Identity.Web. +/// +/// +/// It runs right inside the resilience pipeline, so every attempt uses a current token (served by the token cache of the host) +/// and token acquisition is subject to the configured timeouts. +/// +internal sealed class EntraIdTokenHandler(string clientName, EntraIdHttpClientSettings settings, IAuthorizationHeaderProvider authorizationHeaderProvider) : DelegatingHandler +{ + protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + // The token is added only to the requests whose destination has been validated by EntraIdRequestGuardHandler: + // a request created by an intermediate handler is not marked as validated. + if (!request.Options.TryGetValue(EntraIdHttpClientKeys.Validated, out var isValidated) || !isValidated) + { + throw new InvalidOperationException($"The Entra ID HTTP client '{clientName}' cannot add the access token to a request whose destination has not been validated. Message handlers must forward the request they receive instead of creating a new one."); + } + + // Tells the retry strategy, which evaluates the outcome of this attempt, whether the request can be sent again. + request.GetResilienceContext()?.Properties.Set(EntraIdHttpClientKeys.RetryAllowed, IsRetryAllowed(request)); + + var options = new AuthorizationHeaderProviderOptions + { + AcquireTokenOptions = new() + { + AuthenticationOptionsName = settings.AuthenticationScheme + } + }; + + var authorizationHeader = await authorizationHeaderProvider.CreateAuthorizationHeaderForAppAsync(settings.Scope, options, cancellationToken); + request.Headers.Authorization = AuthenticationHeaderValue.Parse(authorizationHeader); + + try + { + return await base.SendAsync(request, cancellationToken); + } + finally + { + // The same request instance is used for every retry and is still reachable by the caller after the response: + // the token must not outlive the attempt it has been acquired for. + request.Headers.Authorization = null; + } + } + + private static bool IsRetryAllowed(HttpRequestMessage request) + => request.Method == HttpMethod.Get + || request.Method == HttpMethod.Head + || request.Method == HttpMethod.Options + || request.Method == HttpMethod.Trace + || (request.Options.TryGetValue(EntraIdHttpClientKeys.Idempotent, out var isIdempotent) && isIdempotent); +} diff --git a/src/SimpleAuthentication.EntraId/EntraIdAuthenticationExtensions.cs b/src/SimpleAuthentication.EntraId/EntraIdAuthenticationExtensions.cs new file mode 100644 index 0000000..72787fa --- /dev/null +++ b/src/SimpleAuthentication.EntraId/EntraIdAuthenticationExtensions.cs @@ -0,0 +1,121 @@ +using System.Diagnostics.CodeAnalysis; +using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.Authentication.JwtBearer; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using Microsoft.Extensions.Options; +using Microsoft.Identity.Web; +using SimpleAuthentication.EntraId; + +namespace SimpleAuthentication; + +/// +/// Provides extension methods for adding Microsoft Entra ID authentication support in ASP.NET Core. +/// +/// +public static class EntraIdAuthenticationExtensions +{ + /// + /// Registers a named JWT Bearer authentication scheme that validates access tokens issued by a single Microsoft Entra ID tenant, + /// reading configuration from the specified . + /// + /// The to add the scheme to. + /// + /// The that holds Microsoft Entra ID settings, in the format used by Microsoft.Identity.Web + /// (Instance, TenantId, ClientId and, when the application needs to call other APIs, ClientCredentials). + /// + /// The name of the authentication scheme to register (default: EntraId). + /// + /// A that can be used to enable token acquisition, + /// for example calling EnableTokenAcquisitionToCallDownstreamApi() followed by the registration of a token cache. + /// + /// or is . + /// is empty, or TenantId or ClientId is not a GUID. + /// + /// + /// The scheme is added next to the ones that are already registered, without changing the default scheme and without adding a fallback policy, + /// so every endpoint that must accept Microsoft Entra ID tokens has to opt in explicitly, for example using + /// . + /// If the application has a single scheme, which ASP.NET Core automatically uses as the default one, that scheme remains the default one. + /// + /// + /// Token validation is delegated to Microsoft.Identity.Web. Signature, issuer, audience and lifetime are always validated, even if the + /// configuration tries to disable these checks, and tokens whose tid claim does not match the configured tenant are rejected. + /// + /// The configuration is validated when the application starts, so that an invalid setup is reported immediately instead of at the first request. + /// + /// + /// + /// builder.Services.AddSimpleAuthentication(builder.Configuration) + /// .AddEntraIdJwtBearer(builder.Configuration.GetSection("AzureAd")) + /// .EnableTokenAcquisitionToCallDownstreamApi() + /// .AddInMemoryTokenCaches(); + /// + /// + /// + /// + /// + [RequiresUnreferencedCode("Microsoft Entra ID settings are bound from configuration using reflection.")] + [RequiresDynamicCode("Microsoft Entra ID settings are bound from configuration using reflection.")] + public static MicrosoftIdentityWebApiAuthenticationBuilderWithConfiguration AddEntraIdJwtBearer(this AuthenticationBuilder builder, IConfigurationSection configurationSection, string schemeName = EntraIdDefaults.AuthenticationScheme) + { + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(configurationSection); + ArgumentException.ThrowIfNullOrWhiteSpace(schemeName); + + var tenantId = GetIdentifier(configurationSection, "TenantId", "Only single-tenant applications are supported: values such as 'common' or 'organizations' are not allowed."); + GetIdentifier(configurationSection, "ClientId", "Use the application (client) ID of the app registration that represents the API."); + + var identityBuilder = builder.AddMicrosoftIdentityWebApi(configurationSection, schemeName); + + builder.Services.Configure(options => options.SchemeNames.Add(schemeName)); + builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton, EntraIdDefaultSchemePostConfigureOptions>()); + + builder.Services.AddOptions(schemeName) + .PostConfigure(options => + { + var tokenValidationParameters = options.TokenValidationParameters; + + // Identities created by this scheme must be recognizable, so that application role requirements can ignore + // claims coming from the other authentication schemes. + tokenValidationParameters.AuthenticationType = schemeName; + + tokenValidationParameters.RequireSignedTokens = true; + tokenValidationParameters.RequireExpirationTime = true; + tokenValidationParameters.ValidateIssuer = true; + tokenValidationParameters.ValidateAudience = true; + tokenValidationParameters.ValidateLifetime = true; + + options.Events ??= new(); + + var onTokenValidated = options.Events.OnTokenValidated; + options.Events.OnTokenValidated = context => + { + // Issuer validation already binds tokens to the tenant. This check keeps the scheme single-tenant + // even if issuer validation has been customized. + if (!string.Equals(context.Principal?.GetTenantId(), tenantId, StringComparison.OrdinalIgnoreCase)) + { + context.Fail("The token has not been issued by the configured Microsoft Entra ID tenant."); + return Task.CompletedTask; + } + + return onTokenValidated(context); + }; + }) + .ValidateOnStart(); + + return identityBuilder; + } + + private static string GetIdentifier(IConfigurationSection configurationSection, string key, string hint) + { + var value = configurationSection[key]; + if (!Guid.TryParseExact(value, "D", out _)) + { + throw new ArgumentException($"The configuration value '{configurationSection.Path}:{key}' is required and must be a GUID. {hint}", key); + } + + return value; + } +} diff --git a/src/SimpleAuthentication.EntraId/EntraIdAuthorizationExtensions.cs b/src/SimpleAuthentication.EntraId/EntraIdAuthorizationExtensions.cs new file mode 100644 index 0000000..93b016e --- /dev/null +++ b/src/SimpleAuthentication.EntraId/EntraIdAuthorizationExtensions.cs @@ -0,0 +1,90 @@ +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Builder; +using SimpleAuthentication.EntraId; + +namespace SimpleAuthentication; + +/// +/// Provides extension methods for adding authorization based on Microsoft Entra ID application roles in ASP.NET Core. +/// +public static class EntraIdAuthorizationExtensions +{ + /// + /// Requires an app-only access token, validated by the default Microsoft Entra ID authentication scheme, that contains at least one of the specified application roles. + /// + /// The to add the requirement to. + /// The application roles to require. The token must contain at least one of them. + /// A reference to this instance after the operation has completed. + /// or is . + /// is empty or contains empty values. + /// + /// The policy is bound to the scheme, so it works even if Microsoft Entra ID + /// is not the default authentication scheme of the application. Tokens issued on behalf of a user are rejected. + /// + /// + /// + /// builder.Services.AddAuthorizationBuilder() + /// .AddPolicy("OrdersRead", policy => policy.RequireEntraIdApplicationRole("Orders.Read")); + /// + /// + /// + /// + public static AuthorizationPolicyBuilder RequireEntraIdApplicationRole(this AuthorizationPolicyBuilder builder, params string[] roles) + => builder.RequireEntraIdApplicationRole(roles, EntraIdDefaults.AuthenticationScheme); + + /// + /// Requires an app-only access token, validated by the specified Microsoft Entra ID authentication scheme, that contains at least one of the specified application roles. + /// + /// The to add the requirement to. + /// The application roles to require. The token must contain at least one of them. + /// The name of the Microsoft Entra ID authentication scheme, as specified when calling AddEntraIdJwtBearer. + /// A reference to this instance after the operation has completed. + /// or is . + /// is empty, or is empty or contains empty values. + /// + /// The scheme is added to the of the policy, so it is used to authenticate + /// the request even if it is not the default one. Tokens issued on behalf of a user are rejected. + /// + /// + /// + public static AuthorizationPolicyBuilder RequireEntraIdApplicationRole(this AuthorizationPolicyBuilder builder, IEnumerable roles, string schemeName) + { + ArgumentNullException.ThrowIfNull(builder); + + var requirement = new EntraIdApplicationRoleRequirement(schemeName, roles); + + if (!builder.AuthenticationSchemes.Contains(schemeName)) + { + builder.AddAuthenticationSchemes(schemeName); + } + + return builder.AddRequirements(requirement); + } + + /// + /// Adds to the endpoint(s) an authorization policy that requires an app-only access token, validated by the default Microsoft Entra ID authentication scheme, + /// that contains at least one of the specified application roles. + /// + /// The to add policy to. + /// The application roles to require. The token must contain at least one of them. + /// The original parameter. + /// or is . + /// is empty or contains empty values. + /// + /// As for any other policy added using RequireAuthorization, the requirements are evaluated together with the ones + /// of the default authorization policy of the application. + /// + /// + /// + /// app.MapGet("api/orders", () => TypedResults.Ok()) + /// .RequireEntraIdApplicationRole("Orders.Read"); + /// + /// + /// + public static TBuilder RequireEntraIdApplicationRole(this TBuilder builder, params string[] roles) where TBuilder : IEndpointConventionBuilder + { + ArgumentNullException.ThrowIfNull(builder); + + return builder.RequireAuthorization(policy => policy.RequireEntraIdApplicationRole(roles)); + } +} diff --git a/src/SimpleAuthentication.EntraId/EntraIdHttpClientExtensions.cs b/src/SimpleAuthentication.EntraId/EntraIdHttpClientExtensions.cs new file mode 100644 index 0000000..000650e --- /dev/null +++ b/src/SimpleAuthentication.EntraId/EntraIdHttpClientExtensions.cs @@ -0,0 +1,226 @@ +using System.Diagnostics.CodeAnalysis; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Http; +using Microsoft.Extensions.Http.Resilience; +using Microsoft.Extensions.Options; +using Microsoft.Identity.Abstractions; +using Microsoft.Net.Http.Headers; +using SimpleAuthentication.EntraId; + +namespace SimpleAuthentication; + +/// +/// Provides extension methods for registering HTTP clients that call APIs protected by Microsoft Entra ID using app-only access tokens. +/// +public static class EntraIdHttpClientExtensions +{ + private const string DefaultScopeSuffix = "/.default"; + private const string ResilienceSectionName = "Resilience"; + + /// + /// Registers a named that calls an API protected by Microsoft Entra ID using an app-only access token, + /// reading configuration from the specified . + /// + /// The to add services to. + /// The logical name of the to configure. + /// + /// The that is bound to . It can contain a Resilience + /// section, bound to , to configure timeouts, retries and circuit breaker. + /// + /// An optional delegate to configure timeouts, retries and circuit breaker. It is applied after the Resilience configuration section. + /// An that can be used to further configure the client, for example to bind it to a typed client using AddTypedClient. + /// or is . + /// is empty. + /// + /// + /// Tokens are acquired through Microsoft.Identity.Web, using the credentials and the token cache that the application has registered for the + /// authentication scheme specified in : call EnableTokenAcquisitionToCallDownstreamApi() + /// on the builder returned by AddEntraIdJwtBearer and add a token cache. The token of the incoming request is never forwarded. + /// + /// + /// The client can send requests only to addresses that start with . Requests that + /// target a different destination, or that contain an Authorization or Host header, fail with an . + /// Redirects are not followed and cookies are not used, when the primary handler is a or an . + /// + /// + /// The client uses its own standard resilience pipeline: resilience handlers inherited from the defaults are removed, so that retries are not multiplied, + /// while adding or removing resilience handlers on the returned builder causes an when the client is created. + /// Only the requests that use a safe HTTP method (GET, HEAD, OPTIONS and TRACE) are retried. The other ones can write data, so they are + /// sent only once unless the caller explicitly declares that they are idempotent with . + /// + /// Settings are validated when the application starts. + /// + /// + /// + /// builder.Services.AddEntraIdHttpClient("Inventory", builder.Configuration.GetSection("DownstreamApis:Inventory")) + /// .AddTypedClient<InventoryClient>(); + /// + /// + /// + /// + [RequiresUnreferencedCode("HTTP client settings are bound from configuration using reflection.")] + [RequiresDynamicCode("HTTP client settings are bound from configuration using reflection.")] + public static IHttpClientBuilder AddEntraIdHttpClient(this IServiceCollection services, string name, IConfigurationSection configurationSection, Action? configureResilience = null) + { + ArgumentNullException.ThrowIfNull(services); + ArgumentException.ThrowIfNullOrWhiteSpace(name); + ArgumentNullException.ThrowIfNull(configurationSection); + + services.AddOptions(name) + .Bind(configurationSection) + .Validate(HasValidBaseAddress, $"{nameof(EntraIdHttpClientSettings.BaseAddress)} must be an absolute HTTPS URI that ends with a trailing slash and does not contain user information, query string or fragment. HTTP is allowed only for loopback addresses, when {nameof(EntraIdHttpClientSettings.AllowHttpOnLoopback)} is true.") + .Validate(HasValidScope, $"{nameof(EntraIdHttpClientSettings.Scope)} must contain a single scope in the '{{Application ID URI}}{DefaultScopeSuffix}' format.") + .Validate(settings => !string.IsNullOrWhiteSpace(settings.AuthenticationScheme), $"{nameof(EntraIdHttpClientSettings.AuthenticationScheme)} is required.") + .ValidateOnStart(); + + var builder = services.AddHttpClient(name, (serviceProvider, client) => client.BaseAddress = GetSettings(serviceProvider, name).BaseAddress); + + // Removes the handlers added by the HttpClient defaults or by a previous registration of the same client, + // so that there is always a single resilience pipeline and a single token. + builder.ConfigureAdditionalHttpMessageHandlers(static (handlers, _) => + { + for (var i = handlers.Count - 1; i >= 0; i--) + { + if (handlers[i] is ResilienceHandler or EntraIdRequestGuardHandler or EntraIdTokenHandler) + { + handlers.RemoveAt(i); + } + } + }); + + var resilienceBuilder = builder.AddStandardResilienceHandler(); + + var resilienceSection = configurationSection.GetSection(ResilienceSectionName); + if (resilienceSection.Exists()) + { + resilienceBuilder.Configure(resilienceSection); + } + + if (configureResilience is not null) + { + resilienceBuilder.Configure(configureResilience); + } + + // Applied after any other configuration, so that requests that can write data are never retried by mistake. + services.PostConfigure(resilienceBuilder.PipelineName, static options => + { + var shouldHandle = options.Retry.ShouldHandle; + options.Retry.ShouldHandle = args => args.Context.Properties.GetValue(EntraIdHttpClientKeys.RetryAllowed, false) ? shouldHandle(args) : ValueTask.FromResult(false); + }); + + builder.AddHttpMessageHandler(serviceProvider => + { + var authorizationHeaderProvider = serviceProvider.GetService() + ?? throw new InvalidOperationException($"The Entra ID HTTP client '{name}' requires the token acquisition services of Microsoft.Identity.Web. Call EnableTokenAcquisitionToCallDownstreamApi() on the builder returned by AddEntraIdJwtBearer and add a token cache, for example with AddInMemoryTokenCaches()."); + + return new EntraIdTokenHandler(name, GetSettings(serviceProvider, name), authorizationHeaderProvider); + }); + + builder.ConfigureAdditionalHttpMessageHandlers((handlers, serviceProvider) => handlers.Insert(0, new EntraIdRequestGuardHandler(name, GetSettings(serviceProvider, name).BaseAddress))); + + // Applied after any other configuration, so that the access token never ends up in the logs, redirects and cookies + // stay disabled even if the primary handler is replaced, and resilience handlers added later are detected. + services.PostConfigure(name, options => + { + var shouldRedactHeaderValue = options.ShouldRedactHeaderValue; + options.ShouldRedactHeaderValue = headerName => string.Equals(headerName, HeaderNames.Authorization, StringComparison.OrdinalIgnoreCase) || shouldRedactHeaderValue(headerName); + + options.HttpMessageHandlerBuilderActions.Add(handlerBuilder => + { + EnsureSingleResiliencePipeline(name, handlerBuilder.AdditionalHandlers); + DisableRedirectsAndCookies(handlerBuilder.PrimaryHandler); + }); + }); + + return builder; + } + + /// + /// Declares that the request is idempotent, so that an HTTP client registered with AddEntraIdHttpClient can retry it in case of transient failures, + /// even if its HTTP method is not safe. + /// + /// The to mark as idempotent. + /// The original parameter. + /// is . + /// + /// + /// Requests that use methods like POST, PUT, PATCH or DELETE are never retried automatically, because the API may have already processed + /// them even if the response has not been received. Use this method only if sending the same request more than once produces the same result, + /// for example because the API supports idempotency keys. + /// + /// The content of the request must be reusable: stream-based contents cannot be sent more than once. + /// + /// + /// + /// using var request = new HttpRequestMessage(HttpMethod.Put, "products/42") { Content = JsonContent.Create(product) }; + /// using var response = await client.SendAsync(request.MarkAsIdempotent(), cancellationToken); + /// + /// + public static HttpRequestMessage MarkAsIdempotent(this HttpRequestMessage request) + { + ArgumentNullException.ThrowIfNull(request); + + request.Options.Set(EntraIdHttpClientKeys.Idempotent, true); + return request; + } + + private static EntraIdHttpClientSettings GetSettings(IServiceProvider serviceProvider, string name) + => serviceProvider.GetRequiredService>().Get(name); + + private static void EnsureSingleResiliencePipeline(string name, IList handlers) + { + var resilienceHandlers = 0; + var tokenHandlerIndex = -1; + + for (var i = 0; i < handlers.Count; i++) + { + switch (handlers[i]) + { + case ResilienceHandler: + resilienceHandlers++; + break; + + case EntraIdTokenHandler: + tokenHandlerIndex = i; + break; + } + } + + // The retry strategy must run right around the token handler, which tells it whether each request can be sent again. + if (resilienceHandlers != 1 || tokenHandlerIndex < 1 || handlers[tokenHandlerIndex - 1] is not ResilienceHandler) + { + throw new InvalidOperationException($"The Entra ID HTTP client '{name}' must use only the resilience pipeline added by AddEntraIdHttpClient. To change timeouts, retries and circuit breaker, use the '{ResilienceSectionName}' configuration section or the configureResilience argument instead of adding or removing resilience handlers."); + } + } + + private static void DisableRedirectsAndCookies(HttpMessageHandler primaryHandler) + { + switch (primaryHandler) + { + case SocketsHttpHandler socketsHttpHandler: + socketsHttpHandler.AllowAutoRedirect = false; + socketsHttpHandler.UseCookies = false; + break; + + case HttpClientHandler httpClientHandler: + httpClientHandler.AllowAutoRedirect = false; + httpClientHandler.UseCookies = false; + break; + } + } + + private static bool HasValidBaseAddress(EntraIdHttpClientSettings settings) + => settings.BaseAddress is { IsAbsoluteUri: true } baseAddress + && baseAddress.UserInfo.Length == 0 + && baseAddress.Query.Length == 0 + && baseAddress.Fragment.Length == 0 + && baseAddress.AbsolutePath.EndsWith('/') + && (baseAddress.Scheme == Uri.UriSchemeHttps || (settings.AllowHttpOnLoopback && baseAddress.Scheme == Uri.UriSchemeHttp && baseAddress.IsLoopback)); + + private static bool HasValidScope(EntraIdHttpClientSettings settings) + => settings.Scope is { Length: > 0 } scope + && scope.Length > DefaultScopeSuffix.Length + && scope.EndsWith(DefaultScopeSuffix, StringComparison.Ordinal) + && !scope.Any(char.IsWhiteSpace); +} diff --git a/src/SimpleAuthentication.EntraId/README.md b/src/SimpleAuthentication.EntraId/README.md new file mode 100644 index 0000000..f1313cc --- /dev/null +++ b/src/SimpleAuthentication.EntraId/README.md @@ -0,0 +1,527 @@ +# Microsoft Entra ID extensions for Simple Authentication + +An optional package for [Simple Authentication for ASP.NET Core](https://github.com/marcominerva/SimpleAuthentication) that adds service-to-service authentication based on Microsoft Entra ID: + +- a named JWT Bearer authentication scheme that validates the access tokens issued by a single Microsoft Entra ID tenant; +- authorization policies based on application roles, that accept app-only tokens and reject the ones issued on behalf of a user; +- HTTP clients that call other APIs using app-only tokens, with timeouts, retries and circuit breaker. + +``` + 1. token request (client credentials) + ┌──────────────┐ ───────────────────────────────────────────▶ ┌──────────────────────┐ + │ Client API │ ◀─────────────────────────────────────────── │ Microsoft Entra ID │ + │ (the caller) │ 2. app-only access token └──────────────────────┘ + └──────────────┘ + │ 3. HTTP request with "Authorization: Bearer " + ▼ + ┌──────────────┐ + │ Target API │ 4. validates the token and checks the application role + └──────────────┘ +``` + +The package is built on top of [Microsoft.Identity.Web](https://learn.microsoft.com/entra/msidweb/) and [Microsoft.Extensions.Http.Resilience](https://learn.microsoft.com/dotnet/core/resilience/http-resilience). It works next to the authentication schemes and the authorization policies that are already registered in the application, without replacing them or changing their defaults. + +> [!NOTE] +> User-delegated scenarios, like signing-in users or calling an API on behalf of the current user (On-Behalf-Of), are not supported by this package. + +**Contents** + +- [Installation](#installation) +- [Quick start](#quick-start) +- [How it works](#how-it-works) +- [Microsoft Entra ID setup](#microsoft-entra-id-setup) +- [Protecting an API](#protecting-an-api) +- [Calling another API](#calling-another-api) +- [Credentials](#credentials) +- [Migrating from API keys](#migrating-from-api-keys) +- [Verifying the token](#verifying-the-token) +- [Troubleshooting](#troubleshooting) +- [Requirements and limitations](#requirements-and-limitations) + +## Installation + +The library is available on [NuGet](https://www.nuget.org/packages/SimpleAuthenticationTools.EntraId). Search for *SimpleAuthenticationTools.EntraId* in the **Package Manager GUI** or run the following command in the **.NET CLI**: + +```shell +dotnet add package SimpleAuthenticationTools.EntraId +``` + +## Quick start + +If you are already familiar with Microsoft Entra ID, this is everything you need. The rest of this document explains each step. + +**Target API** (receives the calls), with an app registration that exposes the `Orders.Read` application role and emits the `idtyp` optional claim: + +```json +"AzureAd": { + "Instance": "https://login.microsoftonline.com/", + "TenantId": "", + "ClientId": "" +} +``` + +```csharp +builder.Services.AddSimpleAuthentication(builder.Configuration) + .AddEntraIdJwtBearer(builder.Configuration.GetSection("AzureAd")); + +// ... + +app.MapGet("api/orders", () => TypedResults.Ok()) + .RequireEntraIdApplicationRole("Orders.Read"); +``` + +**Client API** (makes the calls), with an app registration that has been granted the `Orders.Read` application permission (with admin consent) and has a credential: + +```json +"AzureAd": { + "Instance": "https://login.microsoftonline.com/", + "TenantId": "", + "ClientId": "", + "ClientCredentials": [ + { "SourceType": "SignedAssertionFromManagedIdentity", "ManagedIdentityClientId": "" } + ] +}, +"DownstreamApis": { + "Orders": { + "BaseAddress": "https://orders.example.com/", + "Scope": "api:///.default" + } +} +``` + +```csharp +builder.Services.AddSimpleAuthentication(builder.Configuration) + .AddEntraIdJwtBearer(builder.Configuration.GetSection("AzureAd")) + .EnableTokenAcquisitionToCallDownstreamApi() + .AddInMemoryTokenCaches(); + +builder.Services.AddEntraIdHttpClient("Orders", builder.Configuration.GetSection("DownstreamApis:Orders")) + .AddTypedClient(); +``` + +## How it works + +Two applications are always involved, and each one has its own app registration in Microsoft Entra ID: + +- the **target API** is the application that *receives* the token: its app registration defines the application roles and the content of the tokens issued for it; +- the **client** is the application that *requests* the token to call the target API: its app registration is granted the roles and owns the credential used to prove its identity. + +The client uses the [client credentials flow](https://learn.microsoft.com/entra/identity-platform/v2-oauth2-client-creds-grant-flow) to get an **app-only** token, that is a token issued to the application itself, without any user. When the target API receives the token, the following checks are performed, in this order: + +| Check | Claims involved | Performed by | Result if it fails | +| --- | --- | --- | --- | +| The token has been issued by the configured tenant | `iss`, `tid` | Microsoft.Identity.Web and this package | 401 | +| The token has been issued for this API | `aud` | Microsoft.Identity.Web | 401 | +| The token is signed by Microsoft Entra ID and is not expired | signature, `exp`, `nbf` | Microsoft.Identity.Web | 401 | +| The token contains at least a role or a scope | `roles`, `scp` | Microsoft.Identity.Web | 401 (`IDW10201`) | +| The token has been issued to an application, not to a user | `idtyp`, `scp` | this package | 403 | +| The token contains one of the required application roles | `roles` | this package | 403 | + +The first four checks are part of authentication: a token that fails them is not accepted at all. The last two are part of authorization, and are performed only on the endpoints that require an application role. + +> [!IMPORTANT] +> Microsoft Entra ID issues a token for an API to **any** application of the tenant that has a credential, even if it has not been granted any role: such a token simply has no `roles` claim. For this reason, the application role is what actually decides which applications can call the API, and it is always required. + +## Microsoft Entra ID setup + +Each setting belongs to exactly one of the two app registrations. Most configuration errors come from applying a setting to the wrong one. + +**Target API app registration** (the application that receives the token) + +| Setting | Where (Microsoft Entra admin center) | Why | +| --- | --- | --- | +| Application ID URI, for example `api://` | **Expose an API** | Identifies the API when the client requests a token (`/.default`) | +| An application role, for example `Orders.Read`, with **Allowed member types** set to **Applications** | **App roles** | It is the permission granted to the clients. Don't reuse roles meant for users: Microsoft recommends keeping user and application roles separate | +| The **`idtyp`** optional claim, for the **Access** token type | **Token configuration** → **Add optional claim** | Lets the API tell app-only tokens from user tokens. Without it, every token is rejected with 403 | +| `requestedAccessTokenVersion` set to `2` (optional) | **Manifest** (`api` section) | Tokens are version 1.0 by default. Both versions are accepted, but the audience differs (see [Protecting an API](#protecting-an-api)) | + +**Client app registration** (the application that requests the token) + +| Setting | Where (Microsoft Entra admin center) | Why | +| --- | --- | --- | +| The application permission that corresponds to the role, for example `Orders.Read` | **API permissions** → **Add a permission** → **APIs my organization uses** → **Application permissions** | Declares that the client needs the role | +| **Grant admin consent** | **API permissions** | Actually assigns the role to the client. Without it, the token has no `roles` claim and is rejected with 401 | +| A credential | **Certificates & secrets** (certificate or secret) or **Federated credentials** (managed identity) | Proves the identity of the client when it requests the token. See [Credentials](#credentials) | + +> [!NOTE] +> The **`idtyp`** claim (identity type) must not be confused with **`idp`** (identity provider): only `idtyp` is used by this package. Its value is `app` in app-only tokens. See [Optional claims reference](https://learn.microsoft.com/entra/identity-platform/optional-claims-reference). + +Changes to the app registrations apply to the tokens issued afterwards. Tokens are cached by the client for about an hour: restart it to get a new token immediately. + +## Protecting an API + +Add to the _appsettings.json_ file a section that contains the settings of the app registration of the API, in the format used by Microsoft.Identity.Web: + +```json +"AzureAd": { + "Instance": "https://login.microsoftonline.com/", + "TenantId": "", // Required: it must be the GUID of a single tenant + "ClientId": "" // Required + //"Audience": "api://custom-uri" // Optional: see below +} +``` + +Then, add the Microsoft Entra ID scheme to the authentication builder. If the application uses Simple Authentication, just chain the call to the existing registration: + +```csharp +using SimpleAuthentication; + +var builder = WebApplication.CreateBuilder(args); + +// Registers the schemes defined in the Authentication section, then adds Microsoft Entra ID. +builder.Services.AddSimpleAuthentication(builder.Configuration) + .AddEntraIdJwtBearer(builder.Configuration.GetSection("AzureAd")); + +// Otherwise, add the scheme to the standard authentication builder. +//builder.Services.AddAuthentication() +// .AddEntraIdJwtBearer(builder.Configuration.GetSection("AzureAd")); +``` + +The scheme is named **EntraId** (you can specify a different name using the second argument of the method) and has the following characteristics: + +- it does not change the default scheme and does not add a fallback policy, so no endpoint becomes protected or anonymous because of the registration: every endpoint that must accept Microsoft Entra ID tokens has to opt in explicitly (see below). If the application has a single scheme, which ASP.NET Core automatically uses as the default one, that scheme remains the default one even after adding Microsoft Entra ID; +- tokens are validated by Microsoft.Identity.Web. Signature, issuer, audience and lifetime are always checked, even if the configuration tries to disable these validations; +- only single-tenant applications are supported. _TenantId_ must be a GUID (values like _common_ or _organizations_ are rejected at startup) and tokens issued by other tenants are refused; +- both version 1.0 and 2.0 access tokens are accepted. By default, the audience must be the client ID of the API for version 2.0 tokens, and `api://` for version 1.0 tokens: if the Application ID URI of the API is different, specify it with the _Audience_ setting; +- the configuration is validated when the application starts. + +> [!NOTE] +> If Microsoft Entra ID is the only scheme of the application, ASP.NET Core automatically uses it as the default one. Moreover, Microsoft.Identity.Web adds to the default authorization policy the requirements that enforce its `RequiredScope` and `RequiredScopeOrAppPermission` attributes: they have no effect on the endpoints that don't use these attributes. + +**Requiring application roles** + +Use the `RequireEntraIdApplicationRole` extension method to require that the caller is an application that has been granted at least one of the specified [application roles](https://learn.microsoft.com/entra/identity-platform/howto-add-app-roles-in-apps): + +```csharp +// In a Minimal API +app.MapGet("api/orders", () => TypedResults.Ok()) + .RequireEntraIdApplicationRole("Orders.Read"); +``` + +It is also possible to create a policy and then use it in Controllers or Minimal APIs: + +```csharp +builder.Services.AddAuthorizationBuilder() + .AddPolicy("OrdersRead", policy => policy.RequireEntraIdApplicationRole("Orders.Read", "Orders.ReadWrite")); + +// ... + +// In a Controller +[Authorize(Policy = "OrdersRead")] +public IActionResult Get() => Ok(); + +// In a Minimal API +app.MapGet("api/orders", () => TypedResults.Ok()) + .RequireAuthorization("OrdersRead"); +``` + +The policy is bound to the Microsoft Entra ID scheme, so it works even if another scheme is the default one, and it evaluates only the claims of the token validated by that scheme: a token accepted by another scheme cannot satisfy the requirement, even if it contains the same claims. Roles are case-sensitive. If you have registered the scheme with a custom name, pass it to the policy: + +```csharp +builder.Services.AddAuthorizationBuilder() + .AddPolicy("OrdersRead", policy => policy.RequireEntraIdApplicationRole(["Orders.Read"], schemeName: "Partners")); +``` + +Only **app-only** tokens are accepted: a token is considered app-only when it contains the `idtyp` claim with the `app` value and no `scp` claim. Tokens issued on behalf of a user are rejected, even if the user has been assigned to the required role. + +## Calling another API + +An API can call another API protected by Microsoft Entra ID using its own identity. Add the credentials of the application to the Microsoft Entra ID section (see [Credentials](#credentials)) and create a section for every API to call: + +```json +"AzureAd": { + "Instance": "https://login.microsoftonline.com/", + "TenantId": "", + "ClientId": "", + "ClientCredentials": [ + { + "SourceType": "SignedAssertionFromManagedIdentity", + "ManagedIdentityClientId": "" + } + ] +}, +"DownstreamApis": { + "Inventory": { + "BaseAddress": "https://inventory.example.com/", // Required: it must use HTTPS and end with a trailing slash + "Scope": "api:///.default" // Required + //"AuthenticationScheme": "EntraId", // Default: EntraId + //"AllowHttpOnLoopback": false, // Default: false + //"Resilience": { + // "TotalRequestTimeout": { + // "Timeout": "00:00:30" // Default: 30 seconds + // }, + // "AttemptTimeout": { + // "Timeout": "00:00:10" // Default: 10 seconds + // }, + // "Retry": { + // "MaxRetryAttempts": 3 // Default: 3 + // } + //} + } +} +``` + +Enable token acquisition, choose a token cache and register the HTTP client: + +```csharp +builder.Services.AddSimpleAuthentication(builder.Configuration) + .AddEntraIdJwtBearer(builder.Configuration.GetSection("AzureAd")) + .EnableTokenAcquisitionToCallDownstreamApi() + .AddInMemoryTokenCaches(); // or AddDistributedTokenCaches() + +builder.Services.AddEntraIdHttpClient("Inventory", builder.Configuration.GetSection("DownstreamApis:Inventory")) + .AddTypedClient(); + +// ... + +public class InventoryClient(HttpClient httpClient) +{ + public async Task> GetProductsAsync(CancellationToken cancellationToken = default) + => await httpClient.GetFromJsonAsync>("api/products", cancellationToken) ?? []; +} +``` + +Tokens are acquired by Microsoft.Identity.Web using the credentials of the authentication scheme and the token cache registered by the application, so they are reused until they are about to expire. The client always uses the identity of the application: the token of the incoming request is never forwarded. + +The following settings are available: + +| Setting | Description | +| --- | --- | +| _BaseAddress_ | The base address of the API. It must be an absolute HTTPS URI that ends with a trailing slash. | +| _Scope_ | The scope used to request the token: the Application ID URI of the target API followed by `/.default`. App-only tokens always contain all the roles granted to the client on that API. | +| _AuthenticationScheme_ | The name of the Microsoft.Identity.Web scheme whose configuration (client ID and credentials) is used to acquire the token (default: _EntraId_). | +| _AllowHttpOnLoopback_ | Set it to `true` to allow a _BaseAddress_ that uses HTTP, only if it refers to the local machine (for example `http://localhost:5000/`), where the token never leaves the computer. Use it for local development only (default: `false`). | +| _Resilience_ | The optional settings of the resilience pipeline, bound to [HttpStandardResilienceOptions](https://learn.microsoft.com/dotnet/api/microsoft.extensions.http.resilience.httpstandardresilienceoptions). | + +Settings are validated when the application starts. + +**Reusing an existing Microsoft.Identity.Web scheme** + +If the application already protects its endpoints with Microsoft.Identity.Web (for example for its users), you don't need to call `AddEntraIdJwtBearer` just to call other APIs: enable token acquisition on the existing registration and set _AuthenticationScheme_ to the name of that scheme. The credentials go in the configuration section of the existing scheme. + +```csharp +builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) + .AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("AzureAdSettings")) + .EnableTokenAcquisitionToCallDownstreamApi() + .AddInMemoryTokenCaches(); + +// In the configuration of the client: "AuthenticationScheme": "Bearer" +builder.Services.AddEntraIdHttpClient("Inventory", builder.Configuration.GetSection("DownstreamApis:Inventory")); +``` + +**Using Refit** + +The client is a standard `IHttpClientBuilder`, so it can be used with [Refit](https://github.com/reactiveui/refit) interfaces: + +```csharp +builder.Services.AddEntraIdHttpClient("Inventory", builder.Configuration.GetSection("DownstreamApis:Inventory")) + .AddTypedClient(client => RestService.For(client)); +``` + +Refit combines the base address and the relative paths of the methods (for example `[Get("/products")]`) correctly, even if the base address ends with a slash. + +**Security** + +The access token identifies the application, so the HTTP client makes sure that it can be sent only to the API it has been requested for: + +- requests can be sent only to addresses that start with _BaseAddress_. A request that targets another host, port, scheme or path fails with an `InvalidOperationException`, before acquiring the token. Changing `HttpClient.BaseAddress` at runtime does not change the allowed destination; +- requests cannot contain the _Authorization_ or _Host_ headers; +- redirects are not followed and cookies are not used, when the primary handler is a `SocketsHttpHandler` or an `HttpClientHandler` (as by default); +- the access token is never written in the logs of the HTTP client, and it is removed from the request as soon as the response has been received; +- synchronous requests are not supported. + +**Resilience** + +The client uses the [standard resilience pipeline](https://learn.microsoft.com/dotnet/core/resilience/http-resilience#standard-resilience-handler-defaults) of .NET, that provides rate limiter, total request timeout, retries, circuit breaker and attempt timeout. Token acquisition is part of every attempt, so it is subject to the same timeouts. You can change the defaults using the _Resilience_ section shown above or in code (code is applied after the configuration): + +```csharp +builder.Services.AddEntraIdHttpClient("Inventory", builder.Configuration.GetSection("DownstreamApis:Inventory"), options => +{ + options.AttemptTimeout.Timeout = TimeSpan.FromSeconds(5); + options.Retry.MaxRetryAttempts = 2; +}); +``` + +The client always uses a single pipeline, otherwise retries would be multiplied: resilience handlers added to all the HTTP clients using `ConfigureHttpClientDefaults` are removed, while adding or removing resilience handlers on the builder returned by `AddEntraIdHttpClient` causes an `InvalidOperationException` when the client is created. + +Only the requests that use a safe HTTP method (_GET_, _HEAD_, _OPTIONS_ and _TRACE_) are retried. The other ones can write data, and the API may have already processed them even if the response has not been received, so they are sent only once and this behavior cannot be changed with the resilience settings. If you know that a request is idempotent (for example because the API supports idempotency keys), you can explicitly allow retries for it: + +```csharp +using var request = new HttpRequestMessage(HttpMethod.Put, $"api/products/{id}") { Content = JsonContent.Create(product) }; +using var response = await httpClient.SendAsync(request.MarkAsIdempotent(), cancellationToken); +``` + +## Credentials + +Credentials are required only by the applications that call other APIs. They are configured with the _ClientCredentials_ setting of Microsoft.Identity.Web, in the same section that contains the client ID. + +_ClientCredentials_ is an **ordered list**: Microsoft.Identity.Web tries the credentials in order and uses the first one that works. In configuration keys, the index identifies the element of the list: for example `AzureAd:ClientCredentials:0:SourceType` is the `SourceType` of the first credential. The name must be exactly _ClientCredentials_: settings with a different name are silently ignored, and the error appears only when the first token is requested. + +The recommended credential depends on where the application runs: + +| Environment | Credential | `SourceType` | +| --- | --- | --- | +| Azure (App Service, Container Apps, AKS, ...) | Managed identity federated with the app registration: no secret at all | `SignedAssertionFromManagedIdentity` | +| Local development or on-premises | Certificate stored in Azure Key Vault, downloaded with the identity of the developer or of the server | `KeyVault` | +| Local development or on-premises | Certificate in the certificate store | `StoreWithThumbprint`, `StoreWithDistinguishedName` | +| Local development only | Client secret, with a short expiration | `ClientSecret` | + +For example, the following configuration uses the managed identity in Azure and falls back to a certificate stored in Key Vault elsewhere: + +```json +"ClientCredentials": [ + { + "SourceType": "SignedAssertionFromManagedIdentity", + "ManagedIdentityClientId": "" + }, + { + "SourceType": "KeyVault", + "KeyVaultUrl": "https://.vault.azure.net/", + "KeyVaultCertificateName": "" + } +] +``` + +To use a **managed identity**, assign a user-assigned managed identity to the Azure resource, add it as federated credential of the app registration (**Certificates & secrets** → **Federated credentials** → **Managed Identity** scenario) and set its client ID in _ManagedIdentityClientId_. Refer to the [official documentation](https://learn.microsoft.com/entra/msidweb/authentication/certificateless) for the complete procedure. + +To use a **certificate**, upload its public part to the app registration (**Certificates & secrets** → **Certificates**). See [Credentials overview for Microsoft.Identity.Web](https://learn.microsoft.com/entra/msidweb/authentication/credentials-overview) for all the supported sources. + +> [!WARNING] +> Never store client secrets in the _appsettings.json_ files or in other files under source control. Leave an empty value in the files and provide the secret with [user secrets](https://learn.microsoft.com/aspnet/core/security/app-secrets) during development, or with environment variables or Azure Key Vault in the other environments. A secret that has been exposed (for example committed, logged or pasted in a chat) must be deleted and replaced. + +For example, during development: + +```json +"ClientCredentials": [ + { "SourceType": "ClientSecret", "ClientSecret": "" } +] +``` + +```shell +dotnet user-secrets set "AzureAd:ClientCredentials:0:ClientSecret" "" +``` + +## Migrating from API keys + +When an API that is called with API keys starts accepting Microsoft Entra ID tokens, the existing clients usually need to keep working until they are migrated. In this case, the endpoints must accept **either** the API key **or** an app-only token with the required role. + +The requirements of an authorization policy are all mandatory, so the alternative must be expressed with a single assertion. The policy authenticates the request with both schemes, accepts it if the API key scheme has authenticated the caller, and otherwise evaluates the application role requirement: + +```csharp +builder.Services.AddSimpleAuthentication(builder.Configuration) + .AddEntraIdJwtBearer(builder.Configuration.GetSection("AzureAd")); + +var apiKeySchemeName = "ApiKey"; // The SchemeName of the API key settings +var applicationRoleRequirement = new EntraIdApplicationRoleRequirement(EntraIdDefaults.AuthenticationScheme, ["Orders.Read"]); + +builder.Services.AddAuthorizationBuilder() + .SetDefaultPolicy(new AuthorizationPolicyBuilder(apiKeySchemeName, EntraIdDefaults.AuthenticationScheme) + .RequireAssertion(async context => + { + // Simple Authentication uses the scheme name as authentication type of the identities it creates. + if (context.User.Identities.Any(identity => identity.IsAuthenticated && identity.AuthenticationType == apiKeySchemeName)) + { + return true; + } + + var entraIdContext = new AuthorizationHandlerContext([applicationRoleRequirement], context.User, context.Resource); + await applicationRoleRequirement.HandleAsync(entraIdContext); + + return entraIdContext.HasSucceeded; + }) + .Build()); +``` + +In this example the policy replaces the default one, so it applies to all the endpoints that use `[Authorize]` or `RequireAuthorization()` without a policy name. To limit it to specific endpoints, register it as a named policy instead. + +On the client side, replace the HTTP client that sends the API key with the one registered by `AddEntraIdHttpClient`. When all the clients have been migrated, remove the API key scheme and use `RequireEntraIdApplicationRole` directly. + +## Verifying the token + +To check the content of the token that a client receives, request one with the same credentials and decode it locally. The following PowerShell script uses a client secret stored in the user secrets of the client project, and prints only the claims, never the secret or the token: + +```powershell +$line = dotnet user-secrets list --project | Select-String '^AzureAd:ClientCredentials:0:ClientSecret = ' +$secret = ($line.ToString() -split ' = ', 2)[1] +$body = @{ + grant_type = 'client_credentials' + client_id = '' + client_secret = $secret + scope = 'api:///.default' +} +$token = (Invoke-RestMethod -Method Post -Uri 'https://login.microsoftonline.com//oauth2/v2.0/token' -Body $body).access_token +Remove-Variable secret, body, line +$payload = $token.Split('.')[1].Replace('-', '+').Replace('_', '/') +switch ($payload.Length % 4) { 2 { $payload += '==' } 3 { $payload += '=' } } +[Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($payload)) | ConvertFrom-Json | ConvertTo-Json +``` + +An app-only token that satisfies the requirements of this package contains: + +| Claim | Expected value | +| --- | --- | +| `aud` | `api://` (version 1.0) or `` (version 2.0) | +| `iss` | `https://sts.windows.net//` (version 1.0) or `https://login.microsoftonline.com//v2.0` (version 2.0) | +| `tid` | `` | +| `appid` (version 1.0) or `azp` (version 2.0) | `` | +| `idtyp` | `app` | +| `roles` | the roles granted to the client, for example `["Orders.Read"]` | +| `scp` | **absent** | + +> [!WARNING] +> An access token works as a password until it expires. Don't paste it in online decoders or in issue trackers. + +To see the claims of the tokens actually received by the target API, you can temporarily log them during development, chaining the events of the scheme: + +```csharp +if (builder.Environment.IsDevelopment()) +{ + builder.Services.PostConfigure(EntraIdDefaults.AuthenticationScheme, options => + { + var onTokenValidated = options.Events.OnTokenValidated; + options.Events.OnTokenValidated = async context => + { + await onTokenValidated(context); + + var logger = context.HttpContext.RequestServices.GetRequiredService>(); + var claims = context.SecurityToken is JsonWebToken token ? token.Claims : context.Principal?.Claims ?? []; + logger.LogInformation("Microsoft Entra ID token for {Path}: {Claims}", context.Request.Path, string.Join(", ", claims.Select(claim => $"{claim.Type}={claim.Value}"))); + }; + }); +} +``` + +## Troubleshooting + +| Symptom | Likely cause | Fix | +| --- | --- | --- | +| The application doesn't start: `TenantId` or `ClientId` must be a GUID | Missing configuration, or a multi-tenant value like `common` | Set the GUIDs of the tenant and of the app registration | +| The application doesn't start: `OptionsValidationException` on _BaseAddress_ or _Scope_ | Invalid settings of an HTTP client | Use an HTTPS base address that ends with `/` and a scope in the `/.default` format | +| `AADSTS7000215` in the log of the client | Wrong or expired client secret | Create a new credential | +| `AADSTS700016` in the log of the client | Wrong client ID or tenant | Check `ClientId` and `TenantId` of the client | +| `AADSTS500011` in the log of the client | The scope doesn't match the Application ID URI of the target API | Check _Scope_ and **Expose an API** of the target API | +| The client reports that no credential is configured | _ClientCredentials_ is missing or misspelled | Check the name of the setting and the index of the elements | +| 401 on the target API with `IDW10201` | The token has neither roles nor scopes: the client has not been granted any role | Grant the application permission and admin consent to the client | +| 401 on the target API with `IDX10214` | Audience not valid | Use the right scope in the client, or set _Audience_ in the target API | +| 401 on the target API with an issuer or tenant error | The token comes from another tenant | Check `TenantId` on both sides | +| 403 on the target API | `idtyp` missing, `scp` present, or role missing | Add the `idtyp` optional claim to the **target API** registration and grant the role to the client; then restart the client to drop the cached token | +| The client fails with `InvalidOperationException` before sending the request | Destination outside _BaseAddress_, or `Authorization`/`Host` header set by the caller | Use relative paths and don't add authentication headers | +| The client fails with `InvalidOperationException` when it is created | Token acquisition not enabled, or resilience handlers added or removed after the registration | Call `EnableTokenAcquisitionToCallDownstreamApi()` and a token cache; configure resilience with the _Resilience_ section | +| The caller returns 404 or 500 but the target API has no errors | The caller converts the errors of the target API | Check the log of the target API, not only the one of the caller | + +## Requirements and limitations + +- .NET 8, 9, 10 or 11, and the ASP.NET Core shared framework, also for the applications that only call other APIs (for example worker services). +- The package depends on Microsoft.Identity.Web, Microsoft.Extensions.Http.Resilience and on the latest patch of `Microsoft.AspNetCore.Authentication.JwtBearer` for each target framework. If the application references an older patch directly, NuGet reports a downgrade error (`NU1605`): update that reference. +- Only single-tenant applications are supported. +- User-delegated scenarios (sign-in of users, On-Behalf-Of) are not supported. +- Handlers of other libraries that retry requests (for example the policies of _Microsoft.Extensions.Http.Polly_) are not detected: don't add them to all the HTTP clients with `ConfigureHttpClientDefaults`, otherwise requests that can write data could be retried. +- Redirects and cookies are disabled only when the primary handler is a `SocketsHttpHandler` or an `HttpClientHandler`. + +## Samples + +The [EntraIdMicroservices](https://github.com/marcominerva/SimpleAuthentication/tree/master/samples/MinimalApis/EntraIdMicroservices) sample contains two APIs: the first one requires an application role and calls the second one using its own identity. + +## Contribute + +The project is constantly evolving. Contributions are welcome. Feel free to file issues and pull requests in the repository, and we'll address them as we can. diff --git a/src/SimpleAuthentication.EntraId/SimpleAuthentication.EntraId.csproj b/src/SimpleAuthentication.EntraId/SimpleAuthentication.EntraId.csproj new file mode 100644 index 0000000..fed4a69 --- /dev/null +++ b/src/SimpleAuthentication.EntraId/SimpleAuthentication.EntraId.csproj @@ -0,0 +1,63 @@ + + + + net8.0;net9.0;net10.0;net11.0 + enable + enable + latest + SimpleAuthentication + SimpleAuthentication.EntraId.xml + Marco Minerva + Marco Minerva + Microsoft Entra ID extensions for Simple Authentication for ASP.NET Core + Microsoft Entra ID extensions for Simple Authentication for ASP.NET Core + A library to easily integrate Microsoft Entra ID service-to-service authentication and resilient authenticated HTTP clients in ASP.NET Core projects + SimpleAuthenticationTools.EntraId + MIT + https://github.com/marcominerva/SimpleAuthentication + Toolbox.png + csharp visualstudio aspnetcore webapi minimal-api authentication jwt jwt-bearer entra-id azure-ad microsoft-identity managed-identity httpclient resilience utilities helpers + git + https://github.com/marcominerva/SimpleAuthentication.git + master + README.md + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + True + + + + + + diff --git a/src/SimpleAuthentication.EntraId/version.json b/src/SimpleAuthentication.EntraId/version.json new file mode 100644 index 0000000..62a74ce --- /dev/null +++ b/src/SimpleAuthentication.EntraId/version.json @@ -0,0 +1,11 @@ +{ + "$schema": "https://raw.githubusercontent.com/dotnet/Nerdbank.GitVersioning/master/src/NerdBank.GitVersioning/version.schema.json", + "version": "3.1", + "publicReleaseRefSpec": [ + "^refs/heads/master$" // we release out of master + ], + "nugetPackageVersion": { + "semVer": 2 + }, + "pathFilters": [ "." ] +} diff --git a/tests/SimpleAuthentication.EntraId.Tests/EntraIdAuthenticationTests.cs b/tests/SimpleAuthentication.EntraId.Tests/EntraIdAuthenticationTests.cs new file mode 100644 index 0000000..da28c61 --- /dev/null +++ b/tests/SimpleAuthentication.EntraId.Tests/EntraIdAuthenticationTests.cs @@ -0,0 +1,442 @@ +using System.Net; +using System.Net.Http.Headers; +using System.Security.Claims; +using System.Security.Cryptography; +using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Authorization.Infrastructure; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.TestHost; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Options; +using Microsoft.IdentityModel.Tokens; +using SimpleAuthentication.EntraId.Tests.Infrastructure; +using SimpleAuthentication.JwtBearer; + +namespace SimpleAuthentication.EntraId.Tests; + +public class EntraIdAuthenticationTests +{ + private const string LocalSchemeName = "Bearer"; + private const string RequiredRole = "Orders.Read"; + + [Fact] + public async Task AppOnlyTokenWithRequiredRole_IsAuthorizedAsync() + { + await using var api = await TestApi.StartAsync(); + + var statusCode = await api.GetAsync("/entra", api.CreateToken()); + + Assert.Equal(HttpStatusCode.OK, statusCode); + } + + [Fact] + public async Task Version1TokenWithRequiredRole_IsAuthorizedAsync() + { + await using var api = await TestApi.StartAsync(); + + var statusCode = await api.GetAsync("/entra", api.CreateVersion1Token()); + + Assert.Equal(HttpStatusCode.OK, statusCode); + } + + [Fact] + public async Task ConfiguredAudience_ReplacesDefaultOneAsync() + { + const string audience = "api://orders.example.com"; + await using var api = await TestApi.StartAsync(configuration => configuration["AzureAd:Audience"] = audience); + + Assert.Equal(HttpStatusCode.OK, await api.GetAsync("/entra", api.CreateToken(audience: audience))); + Assert.Equal(HttpStatusCode.Unauthorized, await api.GetAsync("/entra", api.CreateToken())); + } + + [Fact] + public async Task MissingToken_IsUnauthorizedAsync() + { + await using var api = await TestApi.StartAsync(); + + var statusCode = await api.GetAsync("/entra", token: null); + + Assert.Equal(HttpStatusCode.Unauthorized, statusCode); + } + + [Theory] + [InlineData("WrongAudience")] + [InlineData("OtherTenant")] + [InlineData("UntrustedIssuer")] + [InlineData("Expired")] + [InlineData("NotYetValid")] + [InlineData("WrongSignature")] + [InlineData("Unsigned")] + [InlineData("WithoutExpiration")] + public async Task InvalidToken_IsUnauthorizedAsync(string kind) + { + await using var api = await TestApi.StartAsync(); + + var statusCode = await api.GetAsync("/entra", api.CreateInvalidToken(kind)); + + Assert.Equal(HttpStatusCode.Unauthorized, statusCode); + } + + [Fact] + public async Task TokenOfAnotherTenant_IsUnauthorized_EvenIfConfigurationAcceptsIssuersOfAnyTenantAsync() + { + await using var api = await TestApi.StartAsync(configuration => + configuration["AzureAd:TokenValidationParameters:ValidIssuers:0"] = "https://login.microsoftonline.com/{tenantid}/v2.0"); + + var statusCode = await api.GetAsync("/entra", api.CreateInvalidToken("OtherTenant")); + + Assert.Equal(HttpStatusCode.Unauthorized, statusCode); + Assert.Equal(HttpStatusCode.OK, await api.GetAsync("/entra", api.CreateToken())); + } + + [Theory] + [InlineData("WrongAudience")] + [InlineData("OtherTenant")] + [InlineData("UntrustedIssuer")] + [InlineData("Expired")] + [InlineData("Unsigned")] + [InlineData("WithoutExpiration")] + public async Task InvalidToken_IsUnauthorized_EvenIfConfigurationDisablesValidationAsync(string kind) + { + // The issuer of the signing keys is not published, so that the validations enforced by the scheme are the only ones that can reject the token. + await using var api = await TestApi.StartAsync(configuration => + { + configuration["AzureAd:TokenValidationParameters:RequireSignedTokens"] = "false"; + configuration["AzureAd:TokenValidationParameters:RequireExpirationTime"] = "false"; + configuration["AzureAd:TokenValidationParameters:ValidateIssuer"] = "false"; + configuration["AzureAd:TokenValidationParameters:ValidateAudience"] = "false"; + configuration["AzureAd:TokenValidationParameters:ValidateLifetime"] = "false"; + }, + signingKeyIssuerIsPublished: false); + + var statusCode = await api.GetAsync("/entra", api.CreateInvalidToken(kind)); + + Assert.Equal(HttpStatusCode.Unauthorized, statusCode); + Assert.Equal(HttpStatusCode.OK, await api.GetAsync("/entra", api.CreateToken())); + } + + [Fact] + public async Task AppOnlyTokenWithoutRequiredRole_IsForbiddenAsync() + { + await using var api = await TestApi.StartAsync(); + + var statusCode = await api.GetAsync("/entra", api.CreateToken(roles: ["Orders.Write"])); + + Assert.Equal(HttpStatusCode.Forbidden, statusCode); + } + + [Theory] + [InlineData(null, "Orders.Read")] + [InlineData("user", null)] + [InlineData("user", "Orders.Read")] + [InlineData("app", "Orders.Read")] + [InlineData(null, null)] + public async Task TokenThatIsNotAppOnly_IsForbidden_EvenIfItContainsRequiredRoleAsync(string? identityType, string? scope) + { + await using var api = await TestApi.StartAsync(); + + var statusCode = await api.GetAsync("/entra", api.CreateToken(identityType: identityType, scope: scope)); + + Assert.Equal(HttpStatusCode.Forbidden, statusCode); + } + + [Theory] + [InlineData("Orders.Write", HttpStatusCode.OK)] + [InlineData("Orders.Admin", HttpStatusCode.OK)] + [InlineData("Orders.Read", HttpStatusCode.Forbidden)] + public async Task NamedPolicy_RequiresOneOfItsRolesAsync(string role, HttpStatusCode expectedStatusCode) + { + await using var api = await TestApi.StartAsync(); + + var statusCode = await api.GetAsync("/entra/policy", api.CreateToken(roles: [role])); + + Assert.Equal(expectedStatusCode, statusCode); + } + + [Fact] + public async Task Registration_DoesNotChangeDefaultSchemesAndPoliciesAsync() + { + await using var api = await TestApi.StartAsync(); + + // The local scheme was the only one, so ASP.NET Core used it as the default scheme: it must remain the default one. + var authenticationOptions = api.Services.GetRequiredService>().Value; + Assert.Equal(LocalSchemeName, authenticationOptions.DefaultScheme); + Assert.Equal(LocalSchemeName, authenticationOptions.DefaultAuthenticateScheme); + Assert.Equal(LocalSchemeName, authenticationOptions.DefaultChallengeScheme); + + var authorizationOptions = api.Services.GetRequiredService>().Value; + Assert.Null(authorizationOptions.FallbackPolicy); + Assert.Empty(authorizationOptions.DefaultPolicy.AuthenticationSchemes); + Assert.Contains(authorizationOptions.DefaultPolicy.Requirements, requirement => requirement is DenyAnonymousAuthorizationRequirement); + } + + [Fact] + public async Task EndpointProtectedByDefaultPolicy_KeepsUsingSchemeSelectedAutomaticallyAsync() + { + // Without a default scheme, ASP.NET Core automatically uses the only scheme registered by the application. + await using var api = await TestApi.StartAsync(configuration => configuration.Remove("Authentication:DefaultScheme")); + + Assert.Equal(HttpStatusCode.OK, await api.GetAsync("/local", await api.CreateLocalTokenAsync())); + Assert.Equal(HttpStatusCode.Unauthorized, await api.GetAsync("/local", api.CreateToken())); + Assert.Equal(HttpStatusCode.OK, await api.GetAsync("/entra", api.CreateToken())); + } + + [Theory] + [InlineData(0, null, null)] + [InlineData(1, null, LocalSchemeName)] + [InlineData(2, null, null)] + [InlineData(1, EntraIdDefaults.AuthenticationScheme, EntraIdDefaults.AuthenticationScheme)] + public async Task DefaultScheme_IsSetOnlyToPreserveSchemeSelectedAutomaticallyAsync(int schemesOfHost, string? defaultSchemeOfHost, string? expectedDefaultScheme) + { + await using var api = await TestApi.StartAsync(configuration => + { + configuration.Remove("Authentication:DefaultScheme"); + + if (schemesOfHost == 0) + { + foreach (var key in configuration.Keys.Where(key => key.StartsWith("Authentication:JwtBearer:", StringComparison.Ordinal)).ToList()) + { + configuration.Remove(key); + } + } + else if (schemesOfHost == 2) + { + configuration["Authentication:ApiKey:HeaderName"] = "x-api-key"; + configuration["Authentication:ApiKey:ApiKeyValue"] = Guid.NewGuid().ToString("N"); + configuration["Authentication:ApiKey:UserName"] = "local-service"; + } + }, + configureServices: services => services.Configure(options => options.DefaultScheme ??= defaultSchemeOfHost)); + + var authenticationOptions = api.Services.GetRequiredService>().Value; + + Assert.Equal(schemesOfHost + 1, authenticationOptions.Schemes.Count()); + Assert.Equal(expectedDefaultScheme, authenticationOptions.DefaultScheme); + Assert.Equal(HttpStatusCode.OK, await api.GetAsync("/entra", api.CreateToken())); + } + + [Fact] + public async Task EndpointWithoutAuthorization_RemainsAnonymousAsync() + { + await using var api = await TestApi.StartAsync(); + + var statusCode = await api.GetAsync("/anonymous", token: null); + + Assert.Equal(HttpStatusCode.OK, statusCode); + } + + [Fact] + public async Task EndpointProtectedByDefaultPolicy_KeepsUsingDefaultSchemeAsync() + { + await using var api = await TestApi.StartAsync(); + + Assert.Equal(HttpStatusCode.OK, await api.GetAsync("/local", await api.CreateLocalTokenAsync())); + Assert.Equal(HttpStatusCode.Unauthorized, await api.GetAsync("/local", api.CreateToken())); + Assert.Equal(HttpStatusCode.Unauthorized, await api.GetAsync("/local", token: null)); + } + + [Fact] + public async Task TokenOfAnotherScheme_IsUnauthorized_EvenIfItContainsApplicationRoleClaimsAsync() + { + await using var api = await TestApi.StartAsync(); + + var statusCode = await api.GetAsync("/entra", await api.CreateLocalTokenAsync()); + + Assert.Equal(HttpStatusCode.Unauthorized, statusCode); + } + + [Fact] + public async Task PolicyThatAcceptsMultipleSchemes_EvaluatesRolesOfEntraIdIdentityOnlyAsync() + { + await using var api = await TestApi.StartAsync(); + + Assert.Equal(HttpStatusCode.Forbidden, await api.GetAsync("/entra/mixed", await api.CreateLocalTokenAsync())); + Assert.Equal(HttpStatusCode.OK, await api.GetAsync("/entra/mixed", api.CreateToken())); + } + + [Fact] + public async Task CustomSchemeName_IsUsedByPoliciesThatReferenceItAsync() + { + await using var api = await TestApi.StartAsync(schemeName: "Partners"); + + Assert.Equal(HttpStatusCode.OK, await api.GetAsync("/entra/policy", api.CreateToken(roles: ["Orders.Write"]))); + Assert.Equal(HttpStatusCode.Forbidden, await api.GetAsync("/entra/policy", api.CreateToken())); + Assert.Equal(HttpStatusCode.Unauthorized, await api.GetAsync("/entra/policy", await api.CreateLocalTokenAsync())); + } + + [Theory] + [InlineData("TenantId", null)] + [InlineData("TenantId", "common")] + [InlineData("TenantId", "organizations")] + [InlineData("TenantId", "contoso.onmicrosoft.com")] + [InlineData("TenantId", "{11111111-1111-1111-1111-111111111111}")] + [InlineData("ClientId", null)] + [InlineData("ClientId", "orders-api")] + public void InvalidIdentifier_IsRejectedAtRegistration(string key, string? value) + { + using var authority = new FakeEntraAuthority(); + var settings = authority.CreateEntraIdConfiguration(Guid.NewGuid().ToString()); + settings[$"AzureAd:{key}"] = value; + + var configuration = new ConfigurationBuilder().AddInMemoryCollection(settings).Build(); + var builder = new ServiceCollection().AddAuthentication(); + + var exception = Assert.Throws(() => builder.AddEntraIdJwtBearer(configuration.GetSection("AzureAd"))); + + Assert.Equal(key, exception.ParamName); + Assert.Contains($"AzureAd:{key}", exception.Message); + } + + [Fact] + public void InvalidArguments_AreRejectedAtRegistration() + { + var configuration = new ConfigurationBuilder().Build(); + var builder = new ServiceCollection().AddAuthentication(); + + Assert.Throws(() => EntraIdAuthenticationExtensions.AddEntraIdJwtBearer(null!, configuration.GetSection("AzureAd"))); + Assert.Throws(() => builder.AddEntraIdJwtBearer(null!)); + Assert.Throws(() => builder.AddEntraIdJwtBearer(configuration.GetSection("AzureAd"), " ")); + } + + [Fact] + public async Task IncompleteConfiguration_IsReportedWhenApplicationStartsAsync() + { + var exception = await Assert.ThrowsAnyAsync(() => TestApi.StartAsync(configuration => configuration.Remove("AzureAd:Instance")).AsTask()); + + Assert.Contains("Instance", exception.Message); + } + + private sealed class TestApi(FakeEntraAuthority authority, string clientId, WebApplication application) : IAsyncDisposable + { + private readonly HttpClient client = application.GetTestClient(); + + public IServiceProvider Services => application.Services; + + public static async ValueTask StartAsync(Action>? configure = null, string schemeName = EntraIdDefaults.AuthenticationScheme, + bool signingKeyIssuerIsPublished = true, Action? configureServices = null) + { + var authority = new FakeEntraAuthority(signingKeyIssuerIsPublished); + var clientId = Guid.NewGuid().ToString(); + + var configuration = authority.CreateEntraIdConfiguration(clientId); + configuration["Authentication:DefaultScheme"] = LocalSchemeName; + configuration["Authentication:JwtBearer:SecurityKey"] = Convert.ToBase64String(RandomNumberGenerator.GetBytes(64)); + configuration["Authentication:JwtBearer:Issuers:0"] = "local-issuer"; + configuration["Authentication:JwtBearer:Audiences:0"] = "local-audience"; + configure?.Invoke(configuration); + + var builder = TestApplication.CreateBuilder(configuration); + + builder.Services.AddSimpleAuthentication(builder.Configuration) + .AddEntraIdJwtBearer(builder.Configuration.GetSection("AzureAd"), schemeName); + + builder.Services.AddFakeEntraAuthority(authority, schemeName); + configureServices?.Invoke(builder.Services); + + builder.Services.AddAuthorizationBuilder() + .AddPolicy("OrdersWrite", policy => policy.RequireEntraIdApplicationRole(["Orders.Write", "Orders.Admin"], schemeName)); + + var application = builder.Build(); + + application.UseAuthentication(); + application.UseAuthorization(); + + application.MapGet("/anonymous", () => Results.Ok()); + application.MapGet("/local", () => Results.Ok()).RequireAuthorization(); + application.MapGet("/entra/policy", () => Results.Ok()).RequireAuthorization("OrdersWrite"); + + if (schemeName == EntraIdDefaults.AuthenticationScheme) + { + application.MapGet("/entra", () => Results.Ok()).RequireEntraIdApplicationRole(RequiredRole); + application.MapGet("/entra/mixed", () => Results.Ok()) + .RequireAuthorization(policy => policy.AddAuthenticationSchemes(LocalSchemeName).RequireEntraIdApplicationRole(RequiredRole)); + } + + try + { + await application.StartAsync(TestContext.Current.CancellationToken); + } + catch + { + await application.DisposeAsync(); + authority.Dispose(); + throw; + } + + return new(authority, clientId, application); + } + + public string CreateToken(IEnumerable? roles = null, string? identityType = "app", string? scope = null, string? audience = null) + => authority.CreateToken(audience ?? clientId, roles ?? [RequiredRole], identityType, scope); + + /// + /// Creates a version 1.0 access token, that uses a different issuer and the Application ID URI of the API as audience. + /// + public string CreateVersion1Token() + => authority.CreateToken($"api://{clientId}", [RequiredRole], version1: true); + + public string CreateInvalidToken(string kind) + { + var now = DateTime.UtcNow; + + return kind switch + { + "WrongAudience" => authority.CreateToken(Guid.NewGuid().ToString(), [RequiredRole]), + "OtherTenant" => authority.CreateToken(clientId, [RequiredRole], tenantId: Guid.NewGuid().ToString()), + "UntrustedIssuer" => authority.CreateToken(clientId, [RequiredRole], issuer: "https://login.example.com/v2.0"), + "Expired" => authority.CreateToken(clientId, [RequiredRole], notBefore: now.AddHours(-2), expires: now.AddHours(-1)), + "NotYetValid" => authority.CreateToken(clientId, [RequiredRole], notBefore: now.AddHours(1), expires: now.AddHours(2)), + "WrongSignature" => CreateTokenSignedByAnotherKey(), + "Unsigned" => authority.CreateToken(clientId, [RequiredRole], signed: false), + "WithoutExpiration" => authority.CreateToken(clientId, [RequiredRole], hasExpiration: false), + _ => throw new ArgumentOutOfRangeException(nameof(kind)) + }; + } + + /// + /// Creates a token for the default scheme of the application that pretends to be an app-only Microsoft Entra ID token with the required role. + /// + public Task CreateLocalTokenAsync() + { + var claims = new Claim[] + { + new("roles", RequiredRole), + new(ClaimTypes.Role, RequiredRole), + new("idtyp", "app"), + new("tid", authority.TenantId) + }; + + return Services.GetRequiredService().CreateTokenAsync("local-user", claims, "local-issuer", "local-audience"); + } + + public async Task GetAsync(string path, string? token) + { + using var request = new HttpRequestMessage(HttpMethod.Get, path); + if (token is not null) + { + request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); + } + + using var response = await client.SendAsync(request, TestContext.Current.CancellationToken); + return response.StatusCode; + } + + public async ValueTask DisposeAsync() + { + client.Dispose(); + await application.DisposeAsync(); + authority.Dispose(); + } + + private string CreateTokenSignedByAnotherKey() + { + using var rsa = RSA.Create(2048); + var securityKey = new RsaSecurityKey(rsa) { KeyId = authority.SigningCredentials.Key.KeyId }; + + return authority.CreateToken(clientId, [RequiredRole], signingCredentials: new(securityKey, SecurityAlgorithms.RsaSha256)); + } + } +} diff --git a/tests/SimpleAuthentication.EntraId.Tests/EntraIdAuthorizationTests.cs b/tests/SimpleAuthentication.EntraId.Tests/EntraIdAuthorizationTests.cs new file mode 100644 index 0000000..92ca2a7 --- /dev/null +++ b/tests/SimpleAuthentication.EntraId.Tests/EntraIdAuthorizationTests.cs @@ -0,0 +1,146 @@ +using System.Security.Claims; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Builder; +using Microsoft.Extensions.DependencyInjection; +using NSubstitute; + +namespace SimpleAuthentication.EntraId.Tests; + +public class EntraIdAuthorizationTests +{ + private const string OtherSchemeName = "Bearer"; + private const string ScopeClaimType = "http://schemas.microsoft.com/identity/claims/scope"; + + [Theory] + [InlineData("roles")] + [InlineData(ClaimTypes.Role)] + public async Task AppOnlyIdentityWithAllowedRole_IsAuthorizedAsync(string roleClaimType) + { + var identity = CreateIdentity(EntraIdDefaults.AuthenticationScheme, ("idtyp", "app"), (roleClaimType, "Orders.Write"), (roleClaimType, "Orders.Read")); + + Assert.True(await AuthorizeAsync(policy => policy.RequireEntraIdApplicationRole("Orders.Read", "Orders.Admin"), identity)); + } + + [Fact] + public async Task Roles_AreCaseSensitiveAsync() + { + var identity = CreateIdentity(EntraIdDefaults.AuthenticationScheme, ("idtyp", "app"), ("roles", "orders.read")); + + Assert.False(await AuthorizeAsync(policy => policy.RequireEntraIdApplicationRole("Orders.Read"), identity)); + } + + [Theory] + [InlineData(null, null)] + [InlineData("user", null)] + [InlineData("APP", null)] + [InlineData("app", "scp")] + [InlineData("app", ScopeClaimType)] + public async Task IdentityThatIsNotAppOnly_IsNotAuthorizedAsync(string? identityType, string? scopeClaimType) + { + var identity = CreateIdentity(EntraIdDefaults.AuthenticationScheme, ("roles", "Orders.Read")); + + if (identityType is not null) + { + identity.AddClaim(new("idtyp", identityType)); + } + + if (scopeClaimType is not null) + { + identity.AddClaim(new(scopeClaimType, "Orders.Read")); + } + + Assert.False(await AuthorizeAsync(policy => policy.RequireEntraIdApplicationRole("Orders.Read"), identity)); + } + + [Fact] + public async Task IdentityOfAnotherScheme_IsNotAuthorizedAsync() + { + var identity = CreateIdentity(OtherSchemeName, ("idtyp", "app"), ("roles", "Orders.Read")); + + Assert.False(await AuthorizeAsync(policy => policy.RequireEntraIdApplicationRole("Orders.Read"), identity)); + } + + [Fact] + public async Task UnauthenticatedIdentity_IsNotAuthorizedAsync() + { + var identity = new ClaimsIdentity([new("idtyp", "app"), new("roles", "Orders.Read")]); + + Assert.False(await AuthorizeAsync(policy => policy.RequireEntraIdApplicationRole("Orders.Read"), identity)); + } + + [Fact] + public async Task ClaimsOfDifferentIdentities_AreNotCombinedAsync() + { + var entraIdIdentity = CreateIdentity(EntraIdDefaults.AuthenticationScheme, ("idtyp", "app"), ("roles", "Orders.Write")); + var otherIdentity = CreateIdentity(OtherSchemeName, ("idtyp", "app"), ("roles", "Orders.Read")); + + Assert.False(await AuthorizeAsync(policy => policy.RequireEntraIdApplicationRole("Orders.Read"), entraIdIdentity, otherIdentity)); + Assert.True(await AuthorizeAsync(policy => policy.RequireEntraIdApplicationRole("Orders.Write"), otherIdentity, entraIdIdentity)); + } + + [Fact] + public async Task CustomScheme_IsRequiredByPolicyAsync() + { + var identity = CreateIdentity("Partners", ("idtyp", "app"), ("roles", "Orders.Read")); + + Assert.True(await AuthorizeAsync(policy => policy.RequireEntraIdApplicationRole(["Orders.Read"], "Partners"), identity)); + Assert.False(await AuthorizeAsync(policy => policy.RequireEntraIdApplicationRole("Orders.Read"), identity)); + } + + [Fact] + public void Policy_AuthenticatesRequestsUsingEntraIdScheme() + { + var policy = new AuthorizationPolicyBuilder(OtherSchemeName, EntraIdDefaults.AuthenticationScheme) + .RequireEntraIdApplicationRole("Orders.Read") + .RequireEntraIdApplicationRole(["Orders.Write"], "Partners") + .Build(); + + string[] expectedSchemes = [OtherSchemeName, EntraIdDefaults.AuthenticationScheme, "Partners"]; + Assert.Equal(expectedSchemes, policy.AuthenticationSchemes); + + var requirements = policy.Requirements.OfType().ToList(); + Assert.Equal(2, requirements.Count); + Assert.Equal(EntraIdDefaults.AuthenticationScheme, requirements[0].SchemeName); + Assert.Equal("Orders.Read", Assert.Single(requirements[0].AllowedRoles)); + Assert.Equal("Partners", requirements[1].SchemeName); + Assert.Equal("Orders.Write", Assert.Single(requirements[1].AllowedRoles)); + } + + [Fact] + public void InvalidArguments_AreRejected() + { + var builder = new AuthorizationPolicyBuilder(); + + Assert.Throws(() => EntraIdAuthorizationExtensions.RequireEntraIdApplicationRole(null!, "Orders.Read")); + Assert.Throws(() => builder.RequireEntraIdApplicationRole(null!)); + Assert.Throws(() => builder.RequireEntraIdApplicationRole()); + Assert.Throws(() => builder.RequireEntraIdApplicationRole("Orders.Read", " ")); + Assert.Throws(() => builder.RequireEntraIdApplicationRole(["Orders.Read"], " ")); + + Assert.Empty(builder.AuthenticationSchemes); + Assert.Empty(builder.Requirements); + + var endpoint = Substitute.For(); + + Assert.Throws(() => EntraIdAuthorizationExtensions.RequireEntraIdApplicationRole(null!, "Orders.Read")); + Assert.Throws(() => endpoint.RequireEntraIdApplicationRole()); + Assert.Throws(() => endpoint.RequireEntraIdApplicationRole("Orders.Read", " ")); + + Assert.Empty(endpoint.ReceivedCalls()); + } + + private static ClaimsIdentity CreateIdentity(string authenticationType, params (string Type, string Value)[] claims) + => new(claims.Select(claim => new Claim(claim.Type, claim.Value)), authenticationType); + + private static async Task AuthorizeAsync(Action configurePolicy, params ClaimsIdentity[] identities) + { + var policyBuilder = new AuthorizationPolicyBuilder(); + configurePolicy(policyBuilder); + + await using var serviceProvider = new ServiceCollection().AddLogging().AddAuthorization().BuildServiceProvider(); + var authorizationService = serviceProvider.GetRequiredService(); + + var result = await authorizationService.AuthorizeAsync(new ClaimsPrincipal(identities), resource: null, policyBuilder.Build()); + return result.Succeeded; + } +} diff --git a/tests/SimpleAuthentication.EntraId.Tests/EntraIdHttpClientTests.cs b/tests/SimpleAuthentication.EntraId.Tests/EntraIdHttpClientTests.cs new file mode 100644 index 0000000..49df943 --- /dev/null +++ b/tests/SimpleAuthentication.EntraId.Tests/EntraIdHttpClientTests.cs @@ -0,0 +1,763 @@ +using System.Collections.Concurrent; +using System.Net; +using System.Net.Http.Headers; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Http.Resilience; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using Microsoft.Identity.Abstractions; +using NSubstitute; +using Polly; +using Polly.CircuitBreaker; +using Polly.Timeout; +using SimpleAuthentication.EntraId.Tests.Infrastructure; + +namespace SimpleAuthentication.EntraId.Tests; + +public class EntraIdHttpClientTests +{ + private const string ClientName = "Inventory"; + private const string BaseAddress = "https://inventory.example.com/api/"; + private const string Scope = "api://inventory/.default"; + private const string AccessToken = "app-only-access-token"; + + private static CancellationToken CancellationToken => TestContext.Current.CancellationToken; + + [Fact] + public async Task Request_IsSentWithAppOnlyTokenAsync() + { + await using var fixture = Fixture.Create(StubHttpMessageHandler.Returning(HttpStatusCode.OK)); + + using var response = await fixture.Client.GetAsync("products?page=2", CancellationToken); + + var request = Assert.Single(fixture.PrimaryHandler.Requests); + Assert.Equal("https://inventory.example.com/api/products?page=2", request.RequestUri.AbsoluteUri); + Assert.Equal($"Bearer {AccessToken}", request.Authorization); + + await fixture.AuthorizationHeaderProvider.Received(1).CreateAuthorizationHeaderForAppAsync(Scope, + Arg.Is(options => options.AcquireTokenOptions.AuthenticationOptionsName == EntraIdDefaults.AuthenticationScheme), Arg.Any()); + } + + [Fact] + public async Task Token_IsAcquiredUsingConfiguredAuthenticationSchemeAsync() + { + await using var fixture = Fixture.Create(StubHttpMessageHandler.Returning(HttpStatusCode.OK), settings => settings[$"{ClientName}:AuthenticationScheme"] = "Partners"); + + using var response = await fixture.Client.GetAsync("products", CancellationToken); + + await fixture.AuthorizationHeaderProvider.Received(1).CreateAuthorizationHeaderForAppAsync(Scope, + Arg.Is(options => options.AcquireTokenOptions.AuthenticationOptionsName == "Partners"), Arg.Any()); + } + + [Fact] + public async Task Token_IsRemovedFromRequest_WhenResponseIsReceivedAsync() + { + await using var fixture = Fixture.Create(StubHttpMessageHandler.Returning(HttpStatusCode.OK)); + using var request = new HttpRequestMessage(HttpMethod.Get, "products"); + + using var response = await fixture.Client.SendAsync(request, CancellationToken); + + Assert.Equal($"Bearer {AccessToken}", Assert.Single(fixture.PrimaryHandler.Requests).Authorization); + Assert.Null(request.Headers.Authorization); + } + + [Theory] + [InlineData("products", "https://inventory.example.com/api/products")] + [InlineData("products/42?expand=stock", "https://inventory.example.com/api/products/42?expand=stock")] + [InlineData("products/a%2Fb", "https://inventory.example.com/api/products/a%2Fb")] + [InlineData("products;version=2", "https://inventory.example.com/api/products;version=2")] + [InlineData("", "https://inventory.example.com/api/")] + [InlineData("https://INVENTORY.example.com:443/api/products", "https://inventory.example.com/api/products")] + public async Task RequestInsideBaseAddress_IsSentAsync(string requestUri, string expectedUri) + { + await using var fixture = Fixture.Create(StubHttpMessageHandler.Returning(HttpStatusCode.OK)); + + using var response = await fixture.Client.GetAsync(requestUri, CancellationToken); + + Assert.Equal(expectedUri, Assert.Single(fixture.PrimaryHandler.Requests).RequestUri.AbsoluteUri); + } + + [Theory] + [InlineData("https://other.example.com/api/products")] + [InlineData("https://inventory.example.com.other.example/api/products")] + [InlineData("http://inventory.example.com/api/products")] + [InlineData("https://inventory.example.com:8443/api/products")] + [InlineData("https://user@inventory.example.com/api/products")] + [InlineData("//other.example.com/api/products")] + [InlineData("https://inventory.example.com/api")] + [InlineData("https://inventory.example.com/API/products")] + [InlineData("/products")] + [InlineData("../products")] + [InlineData("%2e%2e/products")] + [InlineData("..%2Fproducts")] + [InlineData("..%5Cproducts")] + [InlineData("%252e%252e%252Fproducts")] + [InlineData("..;/products")] + [InlineData("%2e%2e;/products")] + [InlineData("products/..;/..;/admin")] + public async Task RequestOutsideBaseAddress_IsRejectedBeforeAcquiringTokenAsync(string requestUri) + { + await using var fixture = Fixture.Create(StubHttpMessageHandler.Returning(HttpStatusCode.OK)); + + await Assert.ThrowsAsync(() => fixture.Client.GetAsync(requestUri, CancellationToken)); + + Assert.Empty(fixture.PrimaryHandler.Requests); + Assert.Empty(fixture.AuthorizationHeaderProvider.ReceivedCalls()); + } + + [Theory] + [InlineData("RequestHeader")] + [InlineData("RequestHeaderWithoutValidation")] + [InlineData("DefaultRequestHeader")] + [InlineData("HostHeader")] + [InlineData("ClientBaseAddress")] + public async Task RequestThatOverridesDestinationOrCredentials_IsRejectedBeforeAcquiringTokenAsync(string kind) + { + await using var fixture = Fixture.Create(StubHttpMessageHandler.Returning(HttpStatusCode.OK)); + using var request = new HttpRequestMessage(HttpMethod.Get, "products"); + + switch (kind) + { + case "RequestHeader": + request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", "token-of-the-incoming-request"); + break; + + case "RequestHeaderWithoutValidation": + request.Headers.TryAddWithoutValidation("Authorization", "token-of-the-incoming-request"); + break; + + case "DefaultRequestHeader": + fixture.Client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "token-of-the-incoming-request"); + break; + + case "HostHeader": + request.Headers.Host = "other.example.com"; + break; + + case "ClientBaseAddress": + fixture.Client.BaseAddress = new Uri("https://other.example.com/api/"); + break; + } + + await Assert.ThrowsAsync(() => fixture.Client.SendAsync(request, CancellationToken)); + + Assert.Empty(fixture.PrimaryHandler.Requests); + Assert.Empty(fixture.AuthorizationHeaderProvider.ReceivedCalls()); + } + + [Fact] + public async Task SynchronousRequest_IsNotSupportedAsync() + { + await using var fixture = Fixture.Create(StubHttpMessageHandler.Returning(HttpStatusCode.OK)); + using var request = new HttpRequestMessage(HttpMethod.Get, "products"); + + var exception = Assert.Throws(() => fixture.Client.Send(request, CancellationToken)); + + Assert.Contains(ClientName, exception.Message); + Assert.Empty(fixture.PrimaryHandler.Requests); + } + + [Fact] + public async Task RequestCreatedByAnotherHandler_DoesNotReceiveTokenAsync() + { + await using var fixture = Fixture.Create(StubHttpMessageHandler.Returning(HttpStatusCode.OK), + configureServices: services => services.ConfigureHttpClientDefaults(builder => builder.AddHttpMessageHandler(() => new ReplacingRequestHandler()))); + + await Assert.ThrowsAsync(() => fixture.Client.GetAsync("products", CancellationToken)); + + Assert.Empty(fixture.PrimaryHandler.Requests); + Assert.Empty(fixture.AuthorizationHeaderProvider.ReceivedCalls()); + } + + [Fact] + public async Task RequestRoutedByAnotherHandler_IsValidatedUsingAddressChosenByCallerAsync() + { + await using var fixture = Fixture.Create(StubHttpMessageHandler.Returning(HttpStatusCode.OK), + configureServices: services => services.ConfigureHttpClientDefaults(builder => builder.AddHttpMessageHandler(() => new EndpointResolvingHandler()))); + + using var response = await fixture.Client.GetAsync("products", CancellationToken); + + var request = Assert.Single(fixture.PrimaryHandler.Requests); + Assert.Equal("https://10.0.0.4:8443/api/products", request.RequestUri.AbsoluteUri); + Assert.Equal($"Bearer {AccessToken}", request.Authorization); + } + + [Fact] + public async Task SafeRequest_IsRetried_UsingCurrentTokenForEveryAttemptAsync() + { + await using var fixture = Fixture.Create(StubHttpMessageHandler.Returning(HttpStatusCode.ServiceUnavailable, HttpStatusCode.BadGateway, HttpStatusCode.OK)); + + using var response = await fixture.Client.GetAsync("products", CancellationToken); + + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal(3, fixture.PrimaryHandler.Requests.Count); + Assert.All(fixture.PrimaryHandler.Requests, request => Assert.Equal($"Bearer {AccessToken}", request.Authorization)); + Assert.Equal(3, fixture.AuthorizationHeaderProvider.ReceivedCalls().Count()); + } + + [Theory] + [InlineData("GET")] + [InlineData("HEAD")] + [InlineData("OPTIONS")] + [InlineData("TRACE")] + public async Task SafeRequest_IsRetried_WhenConnectionFailsAsync(string method) + { + await using var fixture = Fixture.Create(new StubHttpMessageHandler((_, _) => throw new HttpRequestException("The connection has been reset.")), + configureResilience: options => options.Retry.MaxRetryAttempts = 2); + using var request = new HttpRequestMessage(new HttpMethod(method), "products"); + + await Assert.ThrowsAsync(() => fixture.Client.SendAsync(request, CancellationToken)); + + Assert.Equal(3, fixture.PrimaryHandler.Requests.Count); + } + + [Theory] + [InlineData("POST")] + [InlineData("PUT")] + [InlineData("PATCH")] + [InlineData("DELETE")] + [InlineData("MERGE")] + public async Task RequestThatCanWriteData_IsNotRetried_WhenResponseIsTransientErrorAsync(string method) + { + await using var fixture = Fixture.Create(StubHttpMessageHandler.Returning(HttpStatusCode.ServiceUnavailable)); + using var request = new HttpRequestMessage(new HttpMethod(method), "products") { Content = new StringContent("{}") }; + + using var response = await fixture.Client.SendAsync(request, CancellationToken); + + Assert.Equal(HttpStatusCode.ServiceUnavailable, response.StatusCode); + Assert.Single(fixture.PrimaryHandler.Requests); + } + + [Theory] + [InlineData("POST")] + [InlineData("PUT")] + [InlineData("PATCH")] + [InlineData("DELETE")] + public async Task RequestThatCanWriteData_IsNotRetried_WhenConnectionFailsAsync(string method) + { + await using var fixture = Fixture.Create(new StubHttpMessageHandler((_, _) => throw new HttpRequestException("The connection has been reset."))); + using var request = new HttpRequestMessage(new HttpMethod(method), "products") { Content = new StringContent("{}") }; + + await Assert.ThrowsAsync(() => fixture.Client.SendAsync(request, CancellationToken)); + + Assert.Single(fixture.PrimaryHandler.Requests); + } + + [Theory] + [InlineData("GET", 3)] + [InlineData("POST", 1)] + public async Task AttemptTimeout_IsApplied_AndRetriesOnlySafeRequestsAsync(string method, int expectedRequests) + { + await using var fixture = Fixture.Create(new StubHttpMessageHandler(async (_, cancellationToken) => + { + await Task.Delay(Timeout.InfiniteTimeSpan, cancellationToken); + return new HttpResponseMessage(HttpStatusCode.OK); + }), + configureResilience: options => + { + options.AttemptTimeout.Timeout = TimeSpan.FromMilliseconds(100); + options.Retry.MaxRetryAttempts = 2; + }); + using var request = new HttpRequestMessage(new HttpMethod(method), "products"); + + await Assert.ThrowsAsync(() => fixture.Client.SendAsync(request, CancellationToken)); + + Assert.Equal(expectedRequests, fixture.PrimaryHandler.Requests.Count); + } + + [Fact] + public async Task RequestMarkedAsIdempotent_IsRetriedAsync() + { + await using var fixture = Fixture.Create(StubHttpMessageHandler.Returning(HttpStatusCode.ServiceUnavailable, HttpStatusCode.OK)); + using var request = new HttpRequestMessage(HttpMethod.Put, "products/42") { Content = new StringContent("{}") }; + + using var response = await fixture.Client.SendAsync(request.MarkAsIdempotent(), CancellationToken); + + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal(2, fixture.PrimaryHandler.Requests.Count); + } + + [Fact] + public async Task ResilienceConfiguration_CannotEnableRetriesOfRequestsThatCanWriteDataAsync() + { + await using var fixture = Fixture.Create(StubHttpMessageHandler.Returning(HttpStatusCode.NotFound), configureResilience: options => + { + options.Retry.MaxRetryAttempts = 2; + options.Retry.ShouldHandle = _ => ValueTask.FromResult(true); + }); + + using var postResponse = await fixture.Client.PostAsync("products", new StringContent("{}"), CancellationToken); + Assert.Single(fixture.PrimaryHandler.Requests); + + using var getResponse = await fixture.Client.GetAsync("products", CancellationToken); + Assert.Equal(4, fixture.PrimaryHandler.Requests.Count); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public async Task ResilienceHandlerOfHttpClientDefaults_IsNotStackedAsync(bool defaultsAreRegisteredFirst) + { + static void ConfigureDefaults(IServiceCollection services) + => services.ConfigureHttpClientDefaults(builder => builder.AddStandardResilienceHandler(ConfigureFastRetries)); + + await using var fixture = Fixture.Create(StubHttpMessageHandler.Returning(HttpStatusCode.ServiceUnavailable), + configureResilience: options => options.Retry.MaxRetryAttempts = 2, + configureServices: defaultsAreRegisteredFirst ? ConfigureDefaults : null, + configureClient: defaultsAreRegisteredFirst ? null : builder => ConfigureDefaults(builder.Services)); + + using var response = await fixture.Client.GetAsync("products", CancellationToken); + + Assert.Equal(3, fixture.PrimaryHandler.Requests.Count); + } + + [Fact] + public async Task ClientRegisteredTwice_UsesSinglePipelineAndSingleTokenAsync() + { + var settings = CreateSettings(); + + await using var fixture = Fixture.Create(StubHttpMessageHandler.Returning(HttpStatusCode.ServiceUnavailable), + configureResilience: options => options.Retry.MaxRetryAttempts = 2, + configureClient: builder => builder.Services.AddEntraIdHttpClient(ClientName, settings, options => + { + ConfigureFastRetries(options); + options.Retry.MaxRetryAttempts = 2; + })); + + using var response = await fixture.Client.GetAsync("products", CancellationToken); + + Assert.Equal(3, fixture.PrimaryHandler.Requests.Count); + Assert.Equal(3, fixture.AuthorizationHeaderProvider.ReceivedCalls().Count()); + } + + [Fact] + public async Task Resilience_IsConfiguredFromConfigurationSection_ThenFromCodeAsync() + { + static void ConfigureSettings(Dictionary settings) => settings[$"{ClientName}:Resilience:Retry:MaxRetryAttempts"] = "1"; + + await using var configuredFromSection = Fixture.Create(StubHttpMessageHandler.Returning(HttpStatusCode.ServiceUnavailable), ConfigureSettings); + using var firstResponse = await configuredFromSection.Client.GetAsync("products", CancellationToken); + Assert.Equal(2, configuredFromSection.PrimaryHandler.Requests.Count); + + await using var configuredFromCode = Fixture.Create(StubHttpMessageHandler.Returning(HttpStatusCode.ServiceUnavailable), ConfigureSettings, options => options.Retry.MaxRetryAttempts = 2); + using var secondResponse = await configuredFromCode.Client.GetAsync("products", CancellationToken); + Assert.Equal(3, configuredFromCode.PrimaryHandler.Requests.Count); + } + + [Fact] + public async Task CircuitBreaker_StopsRequests_AfterRepeatedFailuresAsync() + { + await using var fixture = Fixture.Create(StubHttpMessageHandler.Returning(HttpStatusCode.ServiceUnavailable), configureResilience: options => + { + options.CircuitBreaker.MinimumThroughput = 2; + options.CircuitBreaker.FailureRatio = 0.5; + options.CircuitBreaker.BreakDuration = TimeSpan.FromSeconds(30); + }); + + await Assert.ThrowsAnyAsync(() => fixture.Client.GetAsync("products", CancellationToken)); + var requestsBeforeBreak = fixture.PrimaryHandler.Requests.Count; + + await Assert.ThrowsAnyAsync(() => fixture.Client.GetAsync("products", CancellationToken)); + + Assert.Equal(2, requestsBeforeBreak); + Assert.Equal(requestsBeforeBreak, fixture.PrimaryHandler.Requests.Count); + } + + [Fact(Timeout = 15_000)] + public async Task Cancellation_IsPropagatedToTokenAcquisitionAsync() + { + await using var fixture = Fixture.Create(StubHttpMessageHandler.Returning(HttpStatusCode.OK)); + + fixture.AuthorizationHeaderProvider.CreateAuthorizationHeaderForAppAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(async call => + { + await Task.Delay(Timeout.InfiniteTimeSpan, call.Arg()); + return $"Bearer {AccessToken}"; + }); + + using var cancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(TestContext.Current.CancellationToken); + cancellationTokenSource.CancelAfter(TimeSpan.FromMilliseconds(100)); + + await Assert.ThrowsAnyAsync(() => fixture.Client.GetAsync("products", cancellationTokenSource.Token)); + + Assert.Single(fixture.AuthorizationHeaderProvider.ReceivedCalls()); + Assert.Empty(fixture.PrimaryHandler.Requests); + } + + [Fact(Timeout = 15_000)] + public async Task Cancellation_IsPropagatedToRequest_WithoutRetriesAsync() + { + await using var fixture = Fixture.Create(new StubHttpMessageHandler(async (_, cancellationToken) => + { + await Task.Delay(Timeout.InfiniteTimeSpan, cancellationToken); + return new HttpResponseMessage(HttpStatusCode.OK); + })); + + using var cancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(TestContext.Current.CancellationToken); + cancellationTokenSource.CancelAfter(TimeSpan.FromMilliseconds(100)); + + await Assert.ThrowsAnyAsync(() => fixture.Client.GetAsync("products", cancellationTokenSource.Token)); + + Assert.Single(fixture.PrimaryHandler.Requests); + } + + [Fact(Timeout = 15_000)] + public async Task CancellationRequestedByAnotherHandler_IsPropagatedToRequestAsync() + { + await using var fixture = Fixture.Create(new StubHttpMessageHandler(async (_, cancellationToken) => + { + await Task.Delay(Timeout.InfiniteTimeSpan, cancellationToken); + return new HttpResponseMessage(HttpStatusCode.OK); + }), + configureServices: services => services.ConfigureHttpClientDefaults(builder => builder.AddHttpMessageHandler(() => new CancellingHandler(TimeSpan.FromMilliseconds(100))))); + + await Assert.ThrowsAnyAsync(() => fixture.Client.GetAsync("products", TestContext.Current.CancellationToken)); + + Assert.Single(fixture.PrimaryHandler.Requests); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task AccessToken_IsNeverLoggedAsync(bool hostDisablesRedaction) + { + var loggerProvider = new CollectingLoggerProvider(); + + await using var fixture = Fixture.Create(StubHttpMessageHandler.Returning(HttpStatusCode.OK), + configureServices: services => services.AddLogging(builder => builder.SetMinimumLevel(LogLevel.Trace).AddProvider(loggerProvider)), + configureClient: builder => + { + if (hostDisablesRedaction) + { + builder.RedactLoggedHeaders(_ => false); + } + }); + + using var response = await fixture.Client.GetAsync("products", CancellationToken); + + Assert.Contains(loggerProvider.Messages, message => message.Contains("Authorization: *")); + Assert.DoesNotContain(loggerProvider.Messages, message => message.Contains(AccessToken)); + } + + [Theory] + [InlineData(null)] + [InlineData(nameof(SocketsHttpHandler))] + [InlineData(nameof(HttpClientHandler))] + public async Task RealConnection_AllowsHttpOnLoopback_WithoutFollowingRedirectsOrUsingCookiesAsync(string? primaryHandlerChosenByHost) + { + var builder = WebApplication.CreateBuilder(); + builder.Logging.ClearProviders(); + builder.WebHost.UseUrls("http://127.0.0.1:0"); + + await using var api = builder.Build(); + var requestedPaths = new ConcurrentQueue(); + + api.Use((context, next) => + { + requestedPaths.Enqueue(context.Request.Path); + return next(context); + }); + + api.MapGet("/api/redirect", () => Results.Redirect("/api/authorization")); + api.MapGet("/api/authorization", (HttpRequest request) => request.Headers.Authorization.ToString()); + api.MapGet("/api/cookie", (HttpContext context) => + { + context.Response.Cookies.Append("session", "1"); + return context.Request.Headers.Cookie.ToString(); + }); + + await api.StartAsync(CancellationToken); + + await using var fixture = Fixture.Create(primaryHandler: null, settings => + { + settings[$"{ClientName}:BaseAddress"] = $"{api.Urls.Single()}/api/"; + settings[$"{ClientName}:AllowHttpOnLoopback"] = "true"; + }, + configureClient: builder => + { + // The host can replace the primary handler after the registration of the client, for example to customize TLS settings. + if (primaryHandlerChosenByHost is nameof(SocketsHttpHandler)) + { + builder.ConfigurePrimaryHttpMessageHandler(() => new SocketsHttpHandler()); + } + else if (primaryHandlerChosenByHost is nameof(HttpClientHandler)) + { + builder.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler()); + } + }); + + using var redirectResponse = await fixture.Client.GetAsync("redirect", CancellationToken); + Assert.Equal(HttpStatusCode.Redirect, redirectResponse.StatusCode); + Assert.Equal("/api/redirect", Assert.Single(requestedPaths)); + + Assert.Equal($"Bearer {AccessToken}", await fixture.Client.GetStringAsync("authorization", CancellationToken)); + + await fixture.Client.GetStringAsync("cookie", CancellationToken); + Assert.Empty(await fixture.Client.GetStringAsync("cookie", CancellationToken)); + } + + [Theory] + [InlineData("Added")] + [InlineData("Removed")] + [InlineData("Replaced")] + public void ResilienceHandlersChangedAfterRegistration_AreReportedWhenClientIsCreated(string change) + { + static void RemoveResilienceHandlers(IList handlers) + { + foreach (var handler in handlers.OfType().ToList()) + { + handlers.Remove(handler); + } + } + + var services = new ServiceCollection(); + services.AddLogging(); + services.AddScoped(_ => Substitute.For()); + + var builder = services.AddEntraIdHttpClient(ClientName, CreateSettings()); + + switch (change) + { + case "Added": + builder.AddStandardResilienceHandler(); + break; + + case "Removed": + builder.ConfigureAdditionalHttpMessageHandlers((handlers, _) => RemoveResilienceHandlers(handlers)); + break; + + case "Replaced": + builder.ConfigureAdditionalHttpMessageHandlers((handlers, _) => RemoveResilienceHandlers(handlers)); + builder.AddResilienceHandler("custom", pipeline => pipeline.AddRetry(new HttpRetryStrategyOptions())); + break; + } + + using var serviceProvider = services.BuildServiceProvider(); + var httpClientFactory = serviceProvider.GetRequiredService(); + + var exception = Assert.Throws(() => httpClientFactory.CreateClient(ClientName)); + + Assert.Contains(ClientName, exception.Message); + Assert.Contains("resilience", exception.Message); + } + + [Fact] + public void MissingTokenAcquisitionServices_AreReportedWhenClientIsCreated() + { + var services = new ServiceCollection(); + services.AddEntraIdHttpClient(ClientName, CreateSettings()); + + using var serviceProvider = services.BuildServiceProvider(); + var httpClientFactory = serviceProvider.GetRequiredService(); + + var exception = Assert.Throws(() => httpClientFactory.CreateClient(ClientName)); + + Assert.Contains("EnableTokenAcquisitionToCallDownstreamApi", exception.Message); + } + + [Theory] + [InlineData(null, Scope, null, false, nameof(EntraIdHttpClientSettings.BaseAddress))] + [InlineData("inventory", Scope, null, false, nameof(EntraIdHttpClientSettings.BaseAddress))] + [InlineData("ftp://inventory.example.com/", Scope, null, false, nameof(EntraIdHttpClientSettings.BaseAddress))] + [InlineData("http://inventory.example.com/", Scope, null, false, nameof(EntraIdHttpClientSettings.BaseAddress))] + [InlineData("http://inventory.example.com/", Scope, null, true, nameof(EntraIdHttpClientSettings.BaseAddress))] + [InlineData("http://localhost.example.com/", Scope, null, true, nameof(EntraIdHttpClientSettings.BaseAddress))] + [InlineData("http://localhost:5080/", Scope, null, false, nameof(EntraIdHttpClientSettings.BaseAddress))] + [InlineData("https://inventory.example.com/api", Scope, null, false, nameof(EntraIdHttpClientSettings.BaseAddress))] + [InlineData("https://inventory.example.com/?version=1", Scope, null, false, nameof(EntraIdHttpClientSettings.BaseAddress))] + [InlineData("https://inventory.example.com/#fragment", Scope, null, false, nameof(EntraIdHttpClientSettings.BaseAddress))] + [InlineData("https://user@inventory.example.com/", Scope, null, false, nameof(EntraIdHttpClientSettings.BaseAddress))] + [InlineData(BaseAddress, null, null, false, nameof(EntraIdHttpClientSettings.Scope))] + [InlineData(BaseAddress, "/.default", null, false, nameof(EntraIdHttpClientSettings.Scope))] + [InlineData(BaseAddress, "api://inventory/Products.Read", null, false, nameof(EntraIdHttpClientSettings.Scope))] + [InlineData(BaseAddress, "api://inventory/.default api://orders/.default", null, false, nameof(EntraIdHttpClientSettings.Scope))] + [InlineData(BaseAddress, Scope, " ", false, nameof(EntraIdHttpClientSettings.AuthenticationScheme))] + public async Task InvalidSettings_AreReportedWhenApplicationStartsAsync(string? baseAddress, string? scope, string? authenticationScheme, bool allowHttpOnLoopback, string invalidSetting) + { + using var host = CreateHost(baseAddress, scope, authenticationScheme, allowHttpOnLoopback); + + var exception = await Assert.ThrowsAsync(() => host.StartAsync(CancellationToken)); + + Assert.Equal(ClientName, exception.OptionsName); + Assert.StartsWith(invalidSetting, Assert.Single(exception.Failures)); + } + + [Theory] + [InlineData("https://inventory.example.com/", false)] + [InlineData("https://inventory.example.com/api/v1/", false)] + [InlineData("https://localhost:7080/", false)] + [InlineData("http://localhost:5080/", true)] + [InlineData("http://127.0.0.1:5080/api/", true)] + [InlineData("http://[::1]:5080/", true)] + public async Task ValidSettings_AreAcceptedAsync(string baseAddress, bool allowHttpOnLoopback) + { + using var host = CreateHost(baseAddress, "00000003-0000-0000-c000-000000000000/.default", authenticationScheme: null, allowHttpOnLoopback); + + await host.StartAsync(CancellationToken); + + var settings = host.Services.GetRequiredService>().Get(ClientName); + Assert.Equal(new Uri(baseAddress), settings.BaseAddress); + Assert.Equal(EntraIdDefaults.AuthenticationScheme, settings.AuthenticationScheme); + } + + [Fact] + public void InvalidArguments_AreRejectedAtRegistration() + { + var services = new ServiceCollection(); + var settings = CreateSettings(); + + Assert.Throws(() => EntraIdHttpClientExtensions.AddEntraIdHttpClient(null!, ClientName, settings)); + Assert.Throws(() => services.AddEntraIdHttpClient(" ", settings)); + Assert.Throws(() => services.AddEntraIdHttpClient(ClientName, null!)); + Assert.Throws(() => EntraIdHttpClientExtensions.MarkAsIdempotent(null!)); + } + + private static IConfigurationSection CreateSettings(Action>? configure = null) + { + var settings = new Dictionary + { + [$"{ClientName}:BaseAddress"] = BaseAddress, + [$"{ClientName}:Scope"] = Scope + }; + + configure?.Invoke(settings); + + return new ConfigurationBuilder().AddInMemoryCollection(settings).Build().GetSection(ClientName); + } + + private static IHost CreateHost(string? baseAddress, string? scope, string? authenticationScheme, bool allowHttpOnLoopback) + { + // Settings that are not specified must be missing from the configuration: a null value would be bound to the property. + var settings = new Dictionary { [$"{ClientName}:AllowHttpOnLoopback"] = allowHttpOnLoopback.ToString() }; + + foreach (var (key, value) in new[] { ("BaseAddress", baseAddress), ("Scope", scope), ("AuthenticationScheme", authenticationScheme) }) + { + if (value is not null) + { + settings[$"{ClientName}:{key}"] = value; + } + } + + var configuration = new ConfigurationBuilder().AddInMemoryCollection(settings).Build(); + + return new HostBuilder().ConfigureServices(services => services.AddEntraIdHttpClient(ClientName, configuration.GetSection(ClientName))).Build(); + } + + private static void ConfigureFastRetries(HttpStandardResilienceOptions options) + { + options.Retry.BackoffType = DelayBackoffType.Constant; + options.Retry.Delay = TimeSpan.Zero; + options.Retry.UseJitter = false; + } + + private sealed class Fixture(ServiceProvider serviceProvider, StubHttpMessageHandler? primaryHandler, IAuthorizationHeaderProvider authorizationHeaderProvider) : IAsyncDisposable + { + public HttpClient Client { get; } = serviceProvider.GetRequiredService().CreateClient(ClientName); + + public StubHttpMessageHandler PrimaryHandler => primaryHandler ?? throw new InvalidOperationException("The client uses a real connection."); + + public IAuthorizationHeaderProvider AuthorizationHeaderProvider => authorizationHeaderProvider; + + /// + /// Creates the HTTP client under test. Token acquisition is replaced by a substitute that is registered as scoped, like the real + /// service, and the service provider validates scopes. When is , requests are sent over the network. + /// + public static Fixture Create(StubHttpMessageHandler? primaryHandler, Action>? configureSettings = null, + Action? configureResilience = null, Action? configureServices = null, Action? configureClient = null) + { + var authorizationHeaderProvider = Substitute.For(); + authorizationHeaderProvider.CreateAuthorizationHeaderForAppAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns($"Bearer {AccessToken}"); + + var services = new ServiceCollection(); + services.AddLogging(); + services.AddScoped(_ => authorizationHeaderProvider); + configureServices?.Invoke(services); + + var builder = services.AddEntraIdHttpClient(ClientName, CreateSettings(configureSettings), options => + { + ConfigureFastRetries(options); + configureResilience?.Invoke(options); + }); + + if (primaryHandler is not null) + { + builder.ConfigurePrimaryHttpMessageHandler(() => primaryHandler); + } + + configureClient?.Invoke(builder); + + return new(services.BuildServiceProvider(new ServiceProviderOptions { ValidateScopes = true, ValidateOnBuild = true }), primaryHandler, authorizationHeaderProvider); + } + + public async ValueTask DisposeAsync() + { + Client.Dispose(); + await serviceProvider.DisposeAsync(); + } + } + + /// + /// Simulates a handler that does not forward the request it receives, for example because it follows redirects by itself. + /// + private sealed class ReplacingRequestHandler : DelegatingHandler + { + protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + using var newRequest = new HttpRequestMessage(request.Method, "https://other.example.com/api/products"); + return await base.SendAsync(newRequest, cancellationToken); + } + } + + /// + /// Simulates service discovery, that replaces the logical address of a service with the address of one of its instances. + /// + private sealed class EndpointResolvingHandler : DelegatingHandler + { + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + request.RequestUri = new UriBuilder(request.RequestUri!) { Host = "10.0.0.4", Port = 8443 }.Uri; + return base.SendAsync(request, cancellationToken); + } + } + + /// + /// Simulates a handler that limits the duration of the requests, passing a different cancellation token to the next handlers. + /// + private sealed class CancellingHandler(TimeSpan delay) : DelegatingHandler + { + protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + using var cancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + cancellationTokenSource.CancelAfter(delay); + + return await base.SendAsync(request, cancellationTokenSource.Token); + } + } + + private sealed class CollectingLoggerProvider : ILoggerProvider + { + public ConcurrentQueue Messages { get; } = new(); + + public ILogger CreateLogger(string categoryName) => new Logger(Messages); + + public void Dispose() + { + } + + private sealed class Logger(ConcurrentQueue messages) : ILogger + { + public IDisposable? BeginScope(TState state) where TState : notnull => null; + + public bool IsEnabled(LogLevel logLevel) => true; + + public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func formatter) + => messages.Enqueue(formatter(state, exception)); + } + } +} diff --git a/tests/SimpleAuthentication.EntraId.Tests/EntraIdServiceToServiceTests.cs b/tests/SimpleAuthentication.EntraId.Tests/EntraIdServiceToServiceTests.cs new file mode 100644 index 0000000..2e18afa --- /dev/null +++ b/tests/SimpleAuthentication.EntraId.Tests/EntraIdServiceToServiceTests.cs @@ -0,0 +1,176 @@ +using System.Net; +using System.Net.Http.Headers; +using System.Net.Http.Json; +using System.Security.Claims; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.TestHost; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Identity.Web; +using SimpleAuthentication.EntraId.Tests.Infrastructure; + +namespace SimpleAuthentication.EntraId.Tests; + +/// +/// Exercises the whole flow between two APIs using the real Microsoft.Identity.Web and MSAL implementations: only the endpoints +/// of Microsoft Entra ID are simulated, by . +/// +public class EntraIdServiceToServiceTests +{ + private static CancellationToken CancellationToken => TestContext.Current.CancellationToken; + + [Fact] + public async Task OrdersApi_CallsInventoryApi_UsingItsOwnAppOnlyTokenAsync() + { + await using var services = await Services.StartAsync("Inventory.Read"); + var callerToken = services.CreateOrdersApiToken(); + + var firstResponse = await services.GetOrdersAsync(callerToken); + var secondResponse = await services.GetOrdersAsync(callerToken); + + Assert.Equal(HttpStatusCode.OK, firstResponse.StatusCode); + Assert.Equal(HttpStatusCode.OK, secondResponse.StatusCode); + + // The Inventory API has been called by the Orders API itself, not by the application that called the Orders API. + Assert.Equal(services.OrdersClientId, firstResponse.InventoryCaller); + Assert.Equal(services.OrdersClientId, secondResponse.InventoryCaller); + + // The second call uses the token cache registered by the host. + var tokenRequest = Assert.Single(services.Authority.TokenRequests); + Assert.Equal("client_credentials", tokenRequest["grant_type"]); + Assert.Equal(services.OrdersClientId, tokenRequest["client_id"]); + Assert.Equal($"api://{services.InventoryClientId}/.default", tokenRequest["scope"]); + Assert.DoesNotContain("assertion", tokenRequest.Keys); + Assert.DoesNotContain(callerToken, tokenRequest.Values); + } + + [Theory] + [InlineData("Inventory.Write", HttpStatusCode.Forbidden)] + [InlineData(null, HttpStatusCode.Unauthorized)] + public async Task InventoryApi_RejectsOrdersApi_WhenRequiredApplicationRoleHasNotBeenGrantedAsync(string? grantedRole, HttpStatusCode expectedStatusCode) + { + await using var services = await Services.StartAsync(grantedRole); + + var response = await services.GetOrdersAsync(services.CreateOrdersApiToken()); + + Assert.Equal(expectedStatusCode, response.StatusCode); + } + + [Fact] + public async Task InventoryApi_CanBeCalled_OutsideOfIncomingRequestAsync() + { + await using var services = await Services.StartAsync("Inventory.Read"); + using var client = services.OrdersApi.Services.GetRequiredService().CreateClient("Inventory"); + + var caller = await client.GetFromJsonAsync("products/caller", CancellationToken); + + Assert.Equal(services.OrdersClientId, caller); + } + + private sealed record OrdersResponse(HttpStatusCode StatusCode, string? InventoryCaller); + + private sealed class Services(FakeEntraAuthority authority, string ordersClientId, string inventoryClientId, WebApplication ordersApi, WebApplication inventoryApi) : IAsyncDisposable + { + private readonly HttpClient client = ordersApi.GetTestClient(); + + public FakeEntraAuthority Authority => authority; + + public string OrdersClientId => ordersClientId; + + public string InventoryClientId => inventoryClientId; + + public WebApplication OrdersApi => ordersApi; + + public static async ValueTask StartAsync(string? roleGrantedToOrdersApi) + { + var authority = new FakeEntraAuthority(); + var ordersClientId = Guid.NewGuid().ToString(); + var inventoryClientId = Guid.NewGuid().ToString(); + + if (roleGrantedToOrdersApi is not null) + { + authority.GrantApplicationRoles(inventoryClientId, roleGrantedToOrdersApi); + } + + var inventoryApi = await StartInventoryApiAsync(authority, inventoryClientId); + var ordersApi = await StartOrdersApiAsync(authority, ordersClientId, inventoryClientId, inventoryApi.GetTestServer()); + + return new(authority, ordersClientId, inventoryClientId, ordersApi, inventoryApi); + } + + public string CreateOrdersApiToken() => authority.CreateToken(ordersClientId, ["Orders.Read"]); + + public async Task GetOrdersAsync(string token) + { + using var request = new HttpRequestMessage(HttpMethod.Get, "/orders"); + request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); + + using var response = await client.SendAsync(request, CancellationToken); + var inventoryCaller = response.IsSuccessStatusCode ? await response.Content.ReadFromJsonAsync(CancellationToken) : null; + + return new(response.StatusCode, inventoryCaller); + } + + public async ValueTask DisposeAsync() + { + client.Dispose(); + await ordersApi.DisposeAsync(); + await inventoryApi.DisposeAsync(); + authority.Dispose(); + } + + private static async Task StartInventoryApiAsync(FakeEntraAuthority authority, string clientId) + { + var builder = TestApplication.CreateBuilder(authority.CreateEntraIdConfiguration(clientId)); + + builder.Services.AddAuthentication() + .AddEntraIdJwtBearer(builder.Configuration.GetSection("AzureAd")); + + builder.Services.AddFakeEntraAuthority(authority); + + var application = builder.Build(); + + // Returns the identifier of the application that has called the API. + application.MapGet("/products/caller", (ClaimsPrincipal user) => Results.Json(user.FindFirstValue("azp"))) + .RequireEntraIdApplicationRole("Inventory.Read"); + + await application.StartAsync(CancellationToken); + return application; + } + + private static async Task StartOrdersApiAsync(FakeEntraAuthority authority, string clientId, string inventoryClientId, TestServer inventoryApi) + { + var configuration = authority.CreateEntraIdConfiguration(clientId); + configuration["DownstreamApis:Inventory:BaseAddress"] = "https://inventory.example.com/"; + configuration["DownstreamApis:Inventory:Scope"] = $"api://{inventoryClientId}/.default"; + + var builder = TestApplication.CreateBuilder(configuration); + + builder.Services.AddAuthentication() + .AddEntraIdJwtBearer(builder.Configuration.GetSection("AzureAd")) + .EnableTokenAcquisitionToCallDownstreamApi() + .AddInMemoryTokenCaches(); + + builder.Services.AddFakeEntraAuthority(authority); + + builder.Services.AddEntraIdHttpClient("Inventory", builder.Configuration.GetSection("DownstreamApis:Inventory")) + .ConfigurePrimaryHttpMessageHandler(inventoryApi.CreateHandler); + + var application = builder.Build(); + + application.MapGet("/orders", async (IHttpClientFactory httpClientFactory, CancellationToken cancellationToken) => + { + using var inventoryClient = httpClientFactory.CreateClient("Inventory"); + using var response = await inventoryClient.GetAsync("products/caller", cancellationToken); + + return response.IsSuccessStatusCode + ? Results.Json(await response.Content.ReadFromJsonAsync(cancellationToken)) + : Results.StatusCode((int)response.StatusCode); + }) + .RequireEntraIdApplicationRole("Orders.Read"); + + await application.StartAsync(CancellationToken); + return application; + } + } +} diff --git a/tests/SimpleAuthentication.EntraId.Tests/Infrastructure/FakeEntraAuthority.cs b/tests/SimpleAuthentication.EntraId.Tests/Infrastructure/FakeEntraAuthority.cs new file mode 100644 index 0000000..c8400a4 --- /dev/null +++ b/tests/SimpleAuthentication.EntraId.Tests/Infrastructure/FakeEntraAuthority.cs @@ -0,0 +1,203 @@ +using System.Collections.Concurrent; +using System.Net; +using System.Net.Http.Json; +using System.Security.Cryptography; +using Microsoft.AspNetCore.WebUtilities; +using Microsoft.IdentityModel.JsonWebTokens; +using Microsoft.IdentityModel.Tokens; + +namespace SimpleAuthentication.EntraId.Tests.Infrastructure; + +/// +/// Simulates the endpoints of a single Microsoft Entra ID tenant (metadata, signing keys and token endpoint), so that the real +/// token validation and token acquisition code runs without accessing the network. +/// +internal sealed class FakeEntraAuthority : IDisposable +{ + private const string Host = "https://login.microsoftonline.com"; + + private readonly RSA rsa = RSA.Create(2048); + private readonly ConcurrentQueue> tokenRequests = new(); + private readonly ConcurrentDictionary applicationRoles = new(StringComparer.OrdinalIgnoreCase); + private readonly bool signingKeyIssuerIsPublished; + + /// + /// Creates a new instance of the class. + /// + /// + /// to publish the issuer of the signing keys, as Microsoft Entra ID does. In this case Microsoft.Identity.Web + /// also verifies that the issuer of a token matches the issuer of the key that has signed it. + /// + public FakeEntraAuthority(bool signingKeyIssuerIsPublished = true) + { + this.signingKeyIssuerIsPublished = signingKeyIssuerIsPublished; + SigningCredentials = new(new RsaSecurityKey(rsa) { KeyId = Guid.NewGuid().ToString("N") }, SecurityAlgorithms.RsaSha256); + } + + public string TenantId { get; } = Guid.NewGuid().ToString(); + + public const string Instance = $"{Host}/"; + + public SigningCredentials SigningCredentials { get; } + + /// + /// Gets the form parameters of the requests received by the token endpoint. + /// + public IReadOnlyList> TokenRequests => [.. tokenRequests]; + + public HttpMessageHandler CreateHandler() => new Handler(this); + + /// + /// Sets the application roles that the token endpoint adds to the app-only tokens issued for the specified API. + /// + public void GrantApplicationRoles(string apiClientId, params string[] roles) => applicationRoles[apiClientId] = roles; + + public string CreateToken(string audience, IEnumerable? roles = null, string? identityType = "app", string? scope = null, string? tenantId = null, + string? issuer = null, DateTime? notBefore = null, DateTime? expires = null, bool signed = true, SigningCredentials? signingCredentials = null, string? clientId = null, + bool version1 = false, bool hasExpiration = true) + { + tenantId ??= TenantId; + clientId ??= Guid.NewGuid().ToString(); + + var claims = new Dictionary + { + ["tid"] = tenantId, + ["ver"] = version1 ? "1.0" : "2.0", + [version1 ? "appid" : "azp"] = clientId, + ["oid"] = clientId, + ["sub"] = clientId + }; + + if (roles is not null) + { + claims["roles"] = roles.ToArray(); + } + + if (identityType is not null) + { + claims["idtyp"] = identityType; + } + + if (scope is not null) + { + claims["scp"] = scope; + } + + var now = DateTime.UtcNow; + + return new JsonWebTokenHandler { SetDefaultTimesOnTokenCreation = hasExpiration }.CreateToken(new SecurityTokenDescriptor + { + Issuer = issuer ?? (version1 ? GetVersion1Issuer(tenantId) : GetIssuer(tenantId)), + Audience = audience, + Claims = claims, + IssuedAt = notBefore ?? now, + NotBefore = notBefore ?? now.AddMinutes(-1), + Expires = hasExpiration ? expires ?? now.AddMinutes(10) : null, + SigningCredentials = signed ? signingCredentials ?? SigningCredentials : null + }); + } + + public void Dispose() => rsa.Dispose(); + + private static string GetIssuer(string tenantId) => $"{Host}/{tenantId}/v2.0"; + + private static string GetVersion1Issuer(string tenantId) => $"https://sts.windows.net/{tenantId}/"; + + private async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + var uri = request.RequestUri!; + var path = uri.AbsolutePath; + + if (uri.GetLeftPart(UriPartial.Authority) == Host) + { + if (request.Method == HttpMethod.Get && path == $"/{TenantId}/v2.0/.well-known/openid-configuration") + { + return CreateResponse(new + { + issuer = GetIssuer(TenantId), + authorization_endpoint = $"{Host}/{TenantId}/oauth2/v2.0/authorize", + token_endpoint = $"{Host}/{TenantId}/oauth2/v2.0/token", + jwks_uri = $"{Host}/{TenantId}/discovery/v2.0/keys", + response_types_supported = new[] { "code", "id_token", "token" }, + subject_types_supported = new[] { "pairwise" }, + id_token_signing_alg_values_supported = new[] { SecurityAlgorithms.RsaSha256 } + }); + } + + if (request.Method == HttpMethod.Get && path == $"/{TenantId}/.well-known/openid-configuration") + { + return CreateResponse(new + { + issuer = GetVersion1Issuer(TenantId), + authorization_endpoint = $"{Host}/{TenantId}/oauth2/authorize", + token_endpoint = $"{Host}/{TenantId}/oauth2/token", + jwks_uri = $"{Host}/{TenantId}/discovery/v2.0/keys" + }); + } + + if (request.Method == HttpMethod.Get && path == $"/{TenantId}/discovery/v2.0/keys") + { + var parameters = rsa.ExportParameters(includePrivateParameters: false); + + return CreateResponse(new + { + keys = new[] + { + new + { + kty = "RSA", + use = "sig", + kid = SigningCredentials.Key.KeyId, + n = Base64UrlEncoder.Encode(parameters.Modulus), + e = Base64UrlEncoder.Encode(parameters.Exponent), + issuer = signingKeyIssuerIsPublished ? GetIssuer("{tenantid}") : null + } + } + }); + } + + if (request.Method == HttpMethod.Get && path == "/common/discovery/instance") + { + return CreateResponse(new + { + tenant_discovery_endpoint = $"{Host}/{TenantId}/v2.0/.well-known/openid-configuration", + metadata = new[] + { + new + { + preferred_network = "login.microsoftonline.com", + preferred_cache = "login.windows.net", + aliases = new[] { "login.microsoftonline.com", "login.windows.net" } + } + } + }); + } + + if (request.Method == HttpMethod.Post && path == $"/{TenantId}/oauth2/v2.0/token") + { + var form = QueryHelpers.ParseQuery(await request.Content!.ReadAsStringAsync(cancellationToken)).ToDictionary(p => p.Key, p => p.Value.ToString()); + tokenRequests.Enqueue(form); + + var apiClientId = form["scope"].Replace("api://", string.Empty).Replace("/.default", string.Empty); + applicationRoles.TryGetValue(apiClientId, out var roles); + + return CreateResponse(new + { + token_type = "Bearer", + expires_in = 3600, + access_token = CreateToken(apiClientId, roles, clientId: form["client_id"]) + }); + } + } + + throw new InvalidOperationException($"The fake Microsoft Entra ID authority received an unexpected request: {request.Method} {uri}"); + } + + private static HttpResponseMessage CreateResponse(object content) => new(HttpStatusCode.OK) { Content = JsonContent.Create(content) }; + + private sealed class Handler(FakeEntraAuthority authority) : HttpMessageHandler + { + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + => authority.SendAsync(request, cancellationToken); + } +} diff --git a/tests/SimpleAuthentication.EntraId.Tests/Infrastructure/StubHttpMessageHandler.cs b/tests/SimpleAuthentication.EntraId.Tests/Infrastructure/StubHttpMessageHandler.cs new file mode 100644 index 0000000..c573dcf --- /dev/null +++ b/tests/SimpleAuthentication.EntraId.Tests/Infrastructure/StubHttpMessageHandler.cs @@ -0,0 +1,36 @@ +using System.Collections.Concurrent; +using System.Net; + +namespace SimpleAuthentication.EntraId.Tests.Infrastructure; + +/// +/// Replaces the network: records the requests that reach the primary handler of an HTTP client and creates the responses. +/// +internal sealed class StubHttpMessageHandler(Func> send) : HttpMessageHandler +{ + private readonly ConcurrentQueue requests = new(); + + public IReadOnlyList Requests => [.. requests]; + + /// + /// Creates a handler that returns the specified status codes in sequence, repeating the last one. + /// + public static StubHttpMessageHandler Returning(params HttpStatusCode[] statusCodes) + { + var index = -1; + + return new((request, _) => + { + var statusCode = statusCodes[Math.Min(Interlocked.Increment(ref index), statusCodes.Length - 1)]; + return Task.FromResult(new HttpResponseMessage(statusCode) { RequestMessage = request }); + }); + } + + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + requests.Enqueue(new(request.Method, request.RequestUri!, request.Headers.Authorization?.ToString())); + return send(request, cancellationToken); + } +} + +internal sealed record RecordedRequest(HttpMethod Method, Uri RequestUri, string? Authorization); diff --git a/tests/SimpleAuthentication.EntraId.Tests/Infrastructure/TestApplication.cs b/tests/SimpleAuthentication.EntraId.Tests/Infrastructure/TestApplication.cs new file mode 100644 index 0000000..174aca4 --- /dev/null +++ b/tests/SimpleAuthentication.EntraId.Tests/Infrastructure/TestApplication.cs @@ -0,0 +1,70 @@ +using Microsoft.AspNetCore.Authentication.JwtBearer; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.DataProtection; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.TestHost; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using Microsoft.Identity.Client; +using Microsoft.Identity.Web; + +namespace SimpleAuthentication.EntraId.Tests.Infrastructure; + +internal static class TestApplication +{ + private const string MetadataHttpClientName = nameof(FakeEntraAuthority); + + /// + /// Creates an in-memory application that runs in the Development environment, so that the service provider validates scopes. + /// + public static WebApplicationBuilder CreateBuilder(IEnumerable> configuration) + { + var builder = WebApplication.CreateBuilder(new WebApplicationOptions { EnvironmentName = Environments.Development }); + + builder.WebHost.UseTestServer(); + builder.Logging.ClearProviders(); + builder.Configuration.AddInMemoryCollection(configuration); + builder.Services.AddDataProtection().UseEphemeralDataProtectionProvider(); + + return builder; + } + + /// + /// Creates the settings of an application that is registered in the tenant of the fake authority. + /// + public static Dictionary CreateEntraIdConfiguration(this FakeEntraAuthority authority, string clientId, string sectionName = "AzureAd") + => new() + { + [$"{sectionName}:Instance"] = FakeEntraAuthority.Instance, + [$"{sectionName}:TenantId"] = authority.TenantId, + [$"{sectionName}:ClientId"] = clientId, + [$"{sectionName}:ClientCredentials:0:SourceType"] = "ClientSecret", + [$"{sectionName}:ClientCredentials:0:ClientSecret"] = Guid.NewGuid().ToString("N") + }; + + /// + /// Redirects to the fake authority the requests that the Microsoft Entra ID scheme and MSAL send to Microsoft Entra ID. + /// Everything else (token validation, token acquisition and caching) is the real implementation. + /// + public static IServiceCollection AddFakeEntraAuthority(this IServiceCollection services, FakeEntraAuthority authority, string schemeName = EntraIdDefaults.AuthenticationScheme) + { + services.AddHttpClient(MetadataHttpClientName).ConfigurePrimaryHttpMessageHandler(authority.CreateHandler); + services.Configure(options => options.HttpClientName = MetadataHttpClientName); + services.Configure(schemeName, options => options.BackchannelHttpHandler = authority.CreateHandler()); + + services.RemoveAll(); + services.AddSingleton(new MsalHttpClientFactory(authority)); + + return services; + } + + private sealed class MsalHttpClientFactory(FakeEntraAuthority authority) : IMsalHttpClientFactory + { + private readonly HttpClient httpClient = new(authority.CreateHandler()); + + public HttpClient GetHttpClient() => httpClient; + } +} diff --git a/tests/SimpleAuthentication.EntraId.Tests/SimpleAuthentication.EntraId.Tests.csproj b/tests/SimpleAuthentication.EntraId.Tests/SimpleAuthentication.EntraId.Tests.csproj new file mode 100644 index 0000000..da29e51 --- /dev/null +++ b/tests/SimpleAuthentication.EntraId.Tests/SimpleAuthentication.EntraId.Tests.csproj @@ -0,0 +1,48 @@ + + + + net8.0;net9.0;net10.0;net11.0 + Exe + enable + enable + latest + false + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +