Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions Microsoft.Identity.Web.sln
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.Identity.Web.Oidc
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.Identity.Web.UI.Test", "tests\Microsoft.Identity.Web.UI.Test\Microsoft.Identity.Web.UI.Test.csproj", "{CF31F33A-E5F5-DB57-4FEF-81BDAFD497C8}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "daemon-app-msi", "tests\DevApps\daemon-app\daemon-app-msi\daemon-app-msi.csproj", "{A8181404-23E0-D38B-454C-D16ECDB18B9F}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand Down Expand Up @@ -387,6 +389,10 @@ Global
{CF31F33A-E5F5-DB57-4FEF-81BDAFD497C8}.Debug|Any CPU.Build.0 = Debug|Any CPU
{CF31F33A-E5F5-DB57-4FEF-81BDAFD497C8}.Release|Any CPU.ActiveCfg = Release|Any CPU
{CF31F33A-E5F5-DB57-4FEF-81BDAFD497C8}.Release|Any CPU.Build.0 = Release|Any CPU
{A8181404-23E0-D38B-454C-D16ECDB18B9F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{A8181404-23E0-D38B-454C-D16ECDB18B9F}.Debug|Any CPU.Build.0 = Debug|Any CPU
{A8181404-23E0-D38B-454C-D16ECDB18B9F}.Release|Any CPU.ActiveCfg = Release|Any CPU
{A8181404-23E0-D38B-454C-D16ECDB18B9F}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down Expand Up @@ -461,6 +467,7 @@ Global
{E927D215-A96C-626C-9A1A-CF99876FE7B4} = {45B20A78-91F8-4DD2-B9AD-F12D3A93536C}
{8DA7A2C6-00D4-4CF1-8145-448D7B7B4E5A} = {1DDE1AAC-5AE6-4725-94B6-A26C58D3423F}
{CF31F33A-E5F5-DB57-4FEF-81BDAFD497C8} = {B4E72F1C-603F-437C-AAA1-153A604CD34A}
{A8181404-23E0-D38B-454C-D16ECDB18B9F} = {E37CDBC1-18F6-4C06-A3EE-532C9106721F}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {104367F1-CE75-4F40-B32F-F14853973187}
Expand Down
Binary file added docs/design/capab1.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
117 changes: 117 additions & 0 deletions docs/design/managed_identity_capabilities_devex.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
# Microsoft.Identity.Web – Continuous Access Evaluation (CAE) for Managed Identity

## Why Continuous Access Evaluation?

Continuous Access Evaluation (CAE) lets Microsoft Entra ID revoke tokens or demand extra claims almost immediately when risk changes (user disabled, password reset, network change, policy update, etc.).

A workload opts-in by sending the client-capability **`cp1`** when acquiring tokens. Entra then includes an **`xms_cc`** claim in the token so downstream Microsoft services know the caller can handle claims challenges.

## What this spec adds to **Microsoft.Identity.Web**

* **Declarative opt-in** – one configuration knob (`ClientCapabilities: [ "cp1" ]`).
* **Transparent 401 recovery** – when a downstream Microsoft API responds with a 401+claims challenge, Id.Web automatically:
1. extracts the claims body;
2. bypasses its token cache;
3. requests a fresh token that satisfies the claims;
4. retries the HTTP call **once**.

The goal is **zero-touch** for most developers.

## Typical Flow (Managed Identity → Downstream API)

```text
1. Id.Web → MSI endpoint : GET /token?resource=...&xms_cc=cp1 ──▶
2. MSI → ESTS : request includes cp1 ──▶
3. ESTS → Id.Web : access_token (xms_cc claim present) ◀──
4. Id.Web → Downstream API : GET /resource ⟶ 200 OK │
5. Policy change occurs │
6. Id.Web → Downstream API : GET /resource ⟶ 401 + claims payload │
7. Id.Web handles challenge (steps 1-4 again, bypassing msal cache) ──▶
```

## Design Goals

| # | Goal | Success Metric |
|-----|--------------------------------------------------------------|----------------------------------------------------------|
| G1 | Transparent CAE retry with cache-bypass on 401 claims challenge. | Downstream API call recovers without developer code. |
| G2 | Declarative client capabilities via configuration. | Single place to add `cp1`; all MI calls include it. |

## Public API Impact

no changes to the public api.

## Configuration Example

```
{
"AzureAd": {
"ClientCapabilities": [ "cp1" ]
},

// Example downstream API definition (Contoso Storage API)
"ContosoStorage": {
"BaseUrl": "https://storage.contoso.com/",
"RelativePath": "data/records?api-version=1.0",
"RequestAppToken": true,
"Scopes": [ "https://storage.contoso.com/.default" ],
"AcquireTokenOptions": {
"ManagedIdentity": {
// optional – omit for system-assigned MI
"UserAssignedClientId": "<client-id>"
}
}
}
}
```

> **Note** : The same configuration block works in *appsettings.json* or can be supplied programmatically.


## Code Snippets

### Registering & Calling a Downstream API

```csharp
// 1 – set up the TokenAcquirerFactory (test-helper shown for brevity)
var factory = TokenAcquirerFactory.GetDefaultInstance();

// 2 – register the downstream API using section "ContosoStorage"
factory.Services.AddDownstreamApi("ContosoStorage",
factory.Configuration.GetSection("ContosoStorage"));

IServiceProvider sp = factory.Build();
IDownstreamApi api = sp.GetRequiredService<IDownstreamApi>();

// 3 – call the API (Id.Web handles CAE automatically)
HttpResponseMessage resp = await api.CallApiForAppAsync("ContosoStorage");
```

### Using **IAuthorizationHeaderProvider** (advanced)

`IAuthorizationHeaderProvider` is fully supported with Managed Identity. Claims challenges propagate the same way:

```csharp
var headerProvider = sp.GetRequiredService<IAuthorizationHeaderProvider>();
string header = await headerProvider.CreateAuthorizationHeaderForAppAsync(
scope: "https://storage.contoso.com/.default",
options: new AuthorizationHeaderProviderOptions
{
AcquireTokenOptions = new AcquireTokenOptions
{
ManagedIdentity = new ManagedIdentityOptions(), // system-assigned MI
Claims = claimsChallengeJson // when retrying after 401
}
});
```

## Telemetry

We rely on server side telemetry for the token revocation features.

Server dashboards add MI success‑rate with/without cp1.

## Options as seen in MSAL

![alt text](capab1.png)

### reference - [How to use Continuous Access Evaluation enabled APIs in your applications](https://learn.microsoft.com/en-us/entra/identity-platform/app-resilience-continuous-access-evaluation?tabs=dotnet)
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using Microsoft.Identity.Client;

namespace Microsoft.Identity.Web
{
/// <summary>
/// **TEST-ONLY.** Allows unit tests to supply a custom <see cref="IMsalHttpClientFactory"/>.
/// </summary>
internal interface IManagedIdentityTestHttpClientFactory
{
IMsalHttpClientFactory Create();
}
}
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
const Microsoft.Identity.Web.IDWebErrorMessage.ExceptionAcquiringTokenForConfidentialClient = "IDW10501: Exception acquiring token for a confidential client: " -> string!
const Microsoft.Identity.Web.IDWebErrorMessage.ExceptionAcquiringTokenForConfidentialClient = "IDW10501: Exception acquiring token for a confidential client: " -> string!
Microsoft.Identity.Web.IManagedIdentityTestHttpClientFactory
Microsoft.Identity.Web.IManagedIdentityTestHttpClientFactory.Create() -> Microsoft.Identity.Client.IMsalHttpClientFactory!
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
const Microsoft.Identity.Web.IDWebErrorMessage.ExceptionAcquiringTokenForConfidentialClient = "IDW10501: Exception acquiring token for a confidential client: " -> string!
const Microsoft.Identity.Web.IDWebErrorMessage.ExceptionAcquiringTokenForConfidentialClient = "IDW10501: Exception acquiring token for a confidential client: " -> string!
Microsoft.Identity.Web.IManagedIdentityTestHttpClientFactory
Microsoft.Identity.Web.IManagedIdentityTestHttpClientFactory.Create() -> Microsoft.Identity.Client.IMsalHttpClientFactory!
Original file line number Diff line number Diff line change
@@ -1,2 +1,4 @@
const Microsoft.Identity.Web.IDWebErrorMessage.ExceptionAcquiringTokenForConfidentialClient = "IDW10501: Exception acquiring token for a confidential client: " -> string!
Microsoft.Identity.Web.ClientInfoJsonContext
Microsoft.Identity.Web.ClientInfoJsonContext
Microsoft.Identity.Web.IManagedIdentityTestHttpClientFactory
Microsoft.Identity.Web.IManagedIdentityTestHttpClientFactory.Create() -> Microsoft.Identity.Client.IMsalHttpClientFactory!
Original file line number Diff line number Diff line change
@@ -1,2 +1,4 @@
const Microsoft.Identity.Web.IDWebErrorMessage.ExceptionAcquiringTokenForConfidentialClient = "IDW10501: Exception acquiring token for a confidential client: " -> string!
Microsoft.Identity.Web.ClientInfoJsonContext
Microsoft.Identity.Web.ClientInfoJsonContext
Microsoft.Identity.Web.IManagedIdentityTestHttpClientFactory
Microsoft.Identity.Web.IManagedIdentityTestHttpClientFactory.Create() -> Microsoft.Identity.Client.IMsalHttpClientFactory!
Original file line number Diff line number Diff line change
@@ -1,2 +1,4 @@
const Microsoft.Identity.Web.IDWebErrorMessage.ExceptionAcquiringTokenForConfidentialClient = "IDW10501: Exception acquiring token for a confidential client: " -> string!
Microsoft.Identity.Web.ClientInfoJsonContext
Microsoft.Identity.Web.ClientInfoJsonContext
Microsoft.Identity.Web.IManagedIdentityTestHttpClientFactory
Microsoft.Identity.Web.IManagedIdentityTestHttpClientFactory.Create() -> Microsoft.Identity.Client.IMsalHttpClientFactory!
Original file line number Diff line number Diff line change
@@ -1,2 +1,4 @@
const Microsoft.Identity.Web.IDWebErrorMessage.ExceptionAcquiringTokenForConfidentialClient = "IDW10501: Exception acquiring token for a confidential client: " -> string!
Microsoft.Identity.Web.ClientInfoJsonContext
Microsoft.Identity.Web.ClientInfoJsonContext
Microsoft.Identity.Web.IManagedIdentityTestHttpClientFactory
Microsoft.Identity.Web.IManagedIdentityTestHttpClientFactory.Create() -> Microsoft.Identity.Client.IMsalHttpClientFactory!
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
const Microsoft.Identity.Web.IDWebErrorMessage.ExceptionAcquiringTokenForConfidentialClient = "IDW10501: Exception acquiring token for a confidential client: " -> string!
const Microsoft.Identity.Web.IDWebErrorMessage.ExceptionAcquiringTokenForConfidentialClient = "IDW10501: Exception acquiring token for a confidential client: " -> string!
Microsoft.Identity.Web.IManagedIdentityTestHttpClientFactory
Microsoft.Identity.Web.IManagedIdentityTestHttpClientFactory.Create() -> Microsoft.Identity.Client.IMsalHttpClientFactory!
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
// Licensed under the MIT License.

using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Identity.Abstractions;
Expand All @@ -19,6 +21,7 @@ internal partial class TokenAcquisition
private readonly ConcurrentDictionary<string, IManagedIdentityApplication> _managedIdentityApplicationsByClientId = new();
private readonly SemaphoreSlim _managedIdSemaphore = new(1, 1);
private const string SystemAssignedManagedIdentityKey = "SYSTEM";
private readonly IManagedIdentityTestHttpClientFactory? _miHttpFactory;

/// <summary>
/// Gets a cached ManagedIdentityApplication object or builds a new one if not found.
Expand Down Expand Up @@ -62,6 +65,7 @@ internal async Task<IManagedIdentityApplication> GetOrBuildManagedIdentityApplic
// Build the application
application = BuildManagedIdentityApplication(
managedIdentityId,
mergedOptions.ClientCapabilities,
mergedOptions.ConfidentialClientApplicationOptions.EnablePiiLogging
);

Expand All @@ -80,17 +84,33 @@ internal async Task<IManagedIdentityApplication> GetOrBuildManagedIdentityApplic
/// Creates a managed identity client application.
/// </summary>
/// <param name="managedIdentityId">Indicates if system-assigned or user-assigned managed identity is used.</param>
/// <param name="capabilities">Indicates the capabilities of the managed identity application.</param>
/// <param name="enablePiiLogging">Indicates if logging that may contain personally identifiable information is enabled.</param>
/// <returns>A managed identity application.</returns>
private IManagedIdentityApplication BuildManagedIdentityApplication(ManagedIdentityId managedIdentityId, bool enablePiiLogging)
private IManagedIdentityApplication BuildManagedIdentityApplication(
ManagedIdentityId managedIdentityId,
IEnumerable<string>? capabilities,
bool enablePiiLogging)
{
return ManagedIdentityApplicationBuilder
ManagedIdentityApplicationBuilder miBuilder = ManagedIdentityApplicationBuilder
.Create(managedIdentityId)
.WithLogging(
Log,
ConvertMicrosoftExtensionsLogLevelToMsal(_logger),
enablePiiLogging: enablePiiLogging)
.Build();
enablePiiLogging: enablePiiLogging);

if (capabilities?.Any() == true)
{
miBuilder.WithClientCapabilities(capabilities);
}

if (_miHttpFactory != null)
{
miBuilder.WithHttpClientFactory(_miHttpFactory.Create());
}

return miBuilder.Build();

}

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,7 @@ public TokenAcquisition(
_credentialsLoader = credentialsLoader;
_certificatesObserver = serviceProvider.GetService<ICertificatesObserver>();
tokenAcquisitionExtensionOptionsMonitor = serviceProvider.GetService<IOptionsMonitor<TokenAcquisitionExtensionOptions>>();
_miHttpFactory = serviceProvider.GetService<IManagedIdentityTestHttpClientFactory>();
}

#if NET6_0_OR_GREATER
Expand Down Expand Up @@ -499,7 +500,15 @@ public async Task<AuthenticationResult> GetAuthenticationResultForAppAsync(
mergedOptions,
tokenAcquisitionOptions.ManagedIdentity
);
return await managedIdApp.AcquireTokenForManagedIdentity(scope).ExecuteAsync().ConfigureAwait(false);

var miBuilder = managedIdApp.AcquireTokenForManagedIdentity(scope);

if (!string.IsNullOrEmpty(tokenAcquisitionOptions.Claims))
{
miBuilder.WithClaims(tokenAcquisitionOptions.Claims);
}

return await miBuilder.ExecuteAsync().ConfigureAwait(false);
}
catch (Exception ex)
{
Expand Down
50 changes: 50 additions & 0 deletions tests/DevApps/daemon-app/daemon-app-msi/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Identity.Abstractions;
using Microsoft.Identity.Web;
using System.Net;
using System.Text.Json;

// ── 1. bootstrap factory (reads appsettings.json automatically) ─────────
var factory = TokenAcquirerFactory.GetDefaultInstance();

// optional console logging
factory.Services.AddLogging(b => b.AddConsole().SetMinimumLevel(LogLevel.Warning));

// ── 2. register the downstream API using the "AzureKeyVault" section ────
factory.Services.AddDownstreamApi("AzureKeyVault",
factory.Configuration.GetSection("AzureKeyVault"));
IServiceProvider sp = factory.Build();
IDownstreamApi api = sp.GetRequiredService<IDownstreamApi>();

// ── 3. call the vault (app-token path) ──────────────────────────────────
HttpResponseMessage response = await api.CallApiForAppAsync("AzureKeyVault");

if (response.StatusCode != HttpStatusCode.OK)
{
Console.WriteLine($"Vault returned {(int)response.StatusCode} {response.ReasonPhrase}");
return;
}

//Get the secret value from the response
using var doc = JsonDocument.Parse(await response.Content.ReadAsStringAsync());

// Check if the "value" property exists and is a string
if (doc.RootElement.TryGetProperty("value", out var valueElement) && valueElement.ValueKind == JsonValueKind.String)
{
// Retrieve the secret value but do not print it
string secret = valueElement.GetString()!;

// Optionally, you can check if the secret is not null or empty
if (!string.IsNullOrEmpty(secret))
{
Console.WriteLine("Secret retrieved successfully (non-null).");
}
else
{
Console.WriteLine("Secret value was empty.");
}
}
29 changes: 29 additions & 0 deletions tests/DevApps/daemon-app/daemon-app-msi/appsettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
{
// authentication settings (apply to the whole app)
"AzureAd": {
// Continuous Access Evaluation capability at app-level
"ClientCapabilities": [ "cp1" ]
},

// downstream API settings (per-resource)
"AzureKeyVault": {
"BaseUrl": "https://msidlabs.vault.azure.net/",
"RelativePath": "secrets/msidlab4?api-version=7.4",
"RequestAppToken": true,
"Scopes": [ "https://vault.azure.net/.default" ],
// per request settings
"AcquireTokenOptions": {
"ManagedIdentity": {
// user-assigned MI; omit for system-assigned
"UserAssignedClientId": "4b7a4b0b-ecb2-409e-879a-1e21a15ddaf6"
}
}
},

"Logging": {
"LogLevel": {
"Default": "Warning",
"Microsoft": "Information"
}
}
}
Loading
Loading