-
Notifications
You must be signed in to change notification settings - Fork 241
Add agent identity extension methods for ClaimsPrincipal and ClaimsIdentity #3515
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
jmprieur
merged 11 commits into
master
from
copilot/fix-2b1c96f6-8d41-4b94-900e-30503306567e
Oct 8, 2025
Merged
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
f7a1478
Initial plan
Copilot 0c236f4
Add agent identity extension methods and tests
Copilot 3303c3b
Move AgentIdentityExtensions to Microsoft.Identity.Web.AgentIdentitie…
Copilot 071555b
Refactor: Extract constant and rename method for clarity
Copilot 722ac3b
Add token validation using ClaimsIdentity extension methods in E2E tests
Copilot b194f0b
Assert parent blueprint equals agent application in E2E tests
Copilot b63b756
Merge branch 'master' into copilot/fix-2b1c96f6-8d41-4b94-900e-305033…
jmprieur 1fbb882
Using a real AUI
jmprieur 3cb27b6
Merge branch 'master' into copilot/fix-2b1c96f6-8d41-4b94-900e-305033…
jmprieur 4e9866f
Update src/Microsoft.Identity.Web.AgentIdentities/AgentIdentityExtens…
jmprieur 1907c2d
Merge branch 'master' into copilot/fix-2b1c96f6-8d41-4b94-900e-305033…
jmprieur File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
128 changes: 128 additions & 0 deletions
128
src/Microsoft.Identity.Web.AgentIdentities/AgentIdentityExtensions.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,128 @@ | ||
| // Copyright (c) Microsoft Corporation. All rights reserved. | ||
| // Licensed under the MIT License. | ||
|
|
||
| using System; | ||
| using System.Globalization; | ||
| using System.Security.Claims; | ||
|
|
||
| namespace Microsoft.Identity.Web | ||
| { | ||
| /// <summary> | ||
| /// Extensions to read agent identity-related claims. | ||
| /// </summary> | ||
| public static class AgentIdentityExtensions | ||
| { | ||
| /// <summary> | ||
| /// Claim type for the parent agent blueprint. | ||
| /// </summary> | ||
| private const string XmsParAppAzp = "xms_par_app_azp"; | ||
|
|
||
| /// <summary> | ||
| /// Claim type for subject facets (space-separated integers). | ||
| /// </summary> | ||
| private const string XmsSubFct = "xms_sub_fct"; | ||
|
|
||
| /// <summary> | ||
| /// Subject facet value for agent identity user. | ||
| /// </summary> | ||
| private const int AgentIdUser = 13; | ||
|
|
||
| /// <summary> | ||
| /// Retrieves the parent agent blueprint (xms_par_app_azp) value from a ClaimsPrincipal, if present. | ||
| /// </summary> | ||
| /// <param name="claimsPrincipal">The claims principal.</param> | ||
| /// <returns>The value of the xms_par_app_azp claim if it exists; otherwise, null.</returns> | ||
| public static string? GetParentAgentBlueprint(this ClaimsPrincipal claimsPrincipal) | ||
| { | ||
| if (claimsPrincipal is null) | ||
| { | ||
| throw new ArgumentNullException(nameof(claimsPrincipal)); | ||
| } | ||
|
|
||
| return claimsPrincipal.FindFirst(XmsParAppAzp)?.Value; | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Retrieves the parent agent blueprint (xms_par_app_azp) value from a ClaimsIdentity, if present. | ||
| /// </summary> | ||
| /// <param name="identity">The claims identity.</param> | ||
| /// <returns>The value of the xms_par_app_azp claim if it exists; otherwise, null.</returns> | ||
| public static string? GetParentAgentBlueprint(this ClaimsIdentity identity) | ||
| { | ||
| if (identity is null) | ||
| { | ||
| throw new ArgumentNullException(nameof(identity)); | ||
| } | ||
|
|
||
| return identity.FindFirst(XmsParAppAzp)?.Value; | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Determines whether the ClaimsPrincipal represents an agent user identity. | ||
| /// True if the xms_sub_fct claim exists, is a space-separated string of integers, | ||
| /// and that collection contains the agent identity user facet. | ||
| /// </summary> | ||
| /// <param name="claimsPrincipal">The claims principal.</param> | ||
| /// <returns>True if xms_sub_fct contains the agent identity user facet and all tokens are integers; otherwise false.</returns> | ||
| public static bool IsAgentUserIdentity(this ClaimsPrincipal claimsPrincipal) | ||
| { | ||
| if (claimsPrincipal is null) | ||
| { | ||
| throw new ArgumentNullException(nameof(claimsPrincipal)); | ||
| } | ||
|
|
||
| var value = claimsPrincipal.FindFirst(XmsSubFct)?.Value; | ||
| return ContainsSubjectFacet(value, AgentIdUser); | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Determines whether the ClaimsIdentity represents an agent user identity. | ||
| /// True if the xms_sub_fct claim exists, is a space-separated string of integers, | ||
| /// and that collection contains the agent identity user facet. | ||
| /// </summary> | ||
| /// <param name="identity">The claims identity.</param> | ||
| /// <returns>True if xms_sub_fct contains the agent identity user facet and all tokens are integers; otherwise false.</returns> | ||
| public static bool IsAgentUserIdentity(this ClaimsIdentity identity) | ||
| { | ||
| if (identity is null) | ||
| { | ||
| throw new ArgumentNullException(nameof(identity)); | ||
| } | ||
|
|
||
| var value = identity.FindFirst(XmsSubFct)?.Value; | ||
| return ContainsSubjectFacet(value, AgentIdUser); | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Parses a claim string representing a space-separated collection of integers and checks for a target subject facet. | ||
| /// Returns true only if all tokens are valid integers and one equals the target facet. | ||
| /// </summary> | ||
| private static bool ContainsSubjectFacet(string? raw, int targetFacet) | ||
| { | ||
| if (string.IsNullOrWhiteSpace(raw)) | ||
| { | ||
| return false; | ||
| } | ||
|
|
||
| // After the null check, raw is guaranteed to be non-null | ||
| var tokens = raw!.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries); // split on whitespace | ||
| bool found = false; | ||
|
|
||
| foreach (var token in tokens) | ||
| { | ||
| if (!int.TryParse(token, NumberStyles.Integer, CultureInfo.InvariantCulture, out int n)) | ||
| { | ||
| // If any token is non-integer, the claim is not a valid collection of integers. | ||
| return false; | ||
| } | ||
|
|
||
| if (n == targetFacet) | ||
| { | ||
| found = true; | ||
| } | ||
| } | ||
|
|
||
| return found; | ||
| } | ||
| } | ||
| } |
5 changes: 5 additions & 0 deletions
5
src/Microsoft.Identity.Web.AgentIdentities/PublicAPI/PublicAPI.Unshipped.txt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,2 +1,7 @@ | ||
| #nullable enable | ||
| Microsoft.Identity.Web.AgentIdentityExtensions | ||
| static Microsoft.Identity.Web.AgentIdentityExtension.WithAgentUserIdentity(this Microsoft.Identity.Abstractions.AuthorizationHeaderProviderOptions! options, string! agentApplicationId, System.Guid userId) -> Microsoft.Identity.Abstractions.AuthorizationHeaderProviderOptions! | ||
| static Microsoft.Identity.Web.AgentIdentityExtensions.GetParentAgentBlueprint(this System.Security.Claims.ClaimsPrincipal! claimsPrincipal) -> string? | ||
| static Microsoft.Identity.Web.AgentIdentityExtensions.GetParentAgentBlueprint(this System.Security.Claims.ClaimsIdentity! identity) -> string? | ||
| static Microsoft.Identity.Web.AgentIdentityExtensions.IsAgentUserIdentity(this System.Security.Claims.ClaimsPrincipal! claimsPrincipal) -> bool | ||
| static Microsoft.Identity.Web.AgentIdentityExtensions.IsAgentUserIdentity(this System.Security.Claims.ClaimsIdentity! identity) -> bool |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -4,25 +4,29 @@ | |
| #if !FROM_GITHUB_ACTION | ||
|
|
||
| using System; | ||
| using System.IdentityModel.Tokens.Jwt; | ||
| using System.Linq; | ||
| using System.Security.Claims; | ||
| using System.Security.Cryptography.X509Certificates; | ||
| using Microsoft.Extensions.DependencyInjection; | ||
| using Microsoft.Graph; | ||
| using Microsoft.Identity.Abstractions; | ||
| using Microsoft.Identity.Web; | ||
| using Microsoft.IdentityModel.Tokens; | ||
|
|
||
| namespace AgentApplicationsTests | ||
| { | ||
| public class AgentUserIdentityTests | ||
| { | ||
| string instance = "https://login.microsoftonline.com/"; | ||
| string tenantId = "31a58c3b-ae9c-4448-9e8f-e9e143e800df"; // Replace with your tenant ID | ||
| string agentApplication = "c4b2d4d9-9257-4c1a-a5c0-0a4907c83411"; // Replace with the actual agent application client ID | ||
| string agentIdentity = "44250d7d-2362-4fba-9ba0-49c19ae270e0"; // Replace with the actual agent identity | ||
| string userUpn = "[email protected]"; // Replace with the actual user upn. | ||
|
|
||
| [Fact] | ||
| public async Task AgentUserIdentityGetsTokenForGraphAsync() | ||
| { | ||
| string instance = "https://login.microsoftonline.com/"; | ||
| string tenantId = "31a58c3b-ae9c-4448-9e8f-e9e143e800df"; // Replace with your tenant ID | ||
| string agentApplication = "d15884b6-a447-4dd5-a5a5-a668c49f6300"; // Replace with the actual agent application client ID | ||
| string agentIdentity = "d84da24a-2ea2-42b8-b5ab-8637ec208024"; // Replace with the actual agent identity | ||
| string userUpn = "[email protected]"; // Replace with the actual user upn. | ||
|
|
||
| IServiceCollection services = new ServiceCollection(); | ||
|
|
||
|
|
@@ -52,6 +56,19 @@ public async Task AgentUserIdentityGetsTokenForGraphAsync() | |
| options); | ||
| Assert.NotNull(authorizationHeaderWithUserToken); | ||
|
|
||
| // Extract token from authorization header and validate claims using extension methods | ||
| string token = authorizationHeaderWithUserToken.Substring("Bearer ".Length); | ||
| var handler = new JwtSecurityTokenHandler(); | ||
| var jwtToken = handler.ReadJwtToken(token); | ||
| var claimsIdentity = new CaseSensitiveClaimsIdentity(jwtToken.Claims); | ||
|
|
||
| // Verify the token represents an agent user identity using the extension method | ||
| Assert.True(claimsIdentity.IsAgentUserIdentity()); | ||
|
|
||
| // Verify we can retrieve the parent agent blueprint if present | ||
| string? parentBlueprint = claimsIdentity.GetParentAgentBlueprint(); | ||
| Assert.Equal(agentApplication, parentBlueprint); | ||
|
|
||
| // If you want to call Microsoft Graph, just inject and use the Microsoft Graph SDK with the agent identity. | ||
| GraphServiceClient graphServiceClient = serviceProvider.GetRequiredService<GraphServiceClient>(); | ||
| var me = await graphServiceClient.Me.GetAsync(r => r.Options.WithAuthenticationOptions(options => options.WithAgentUserIdentity(agentIdentity, userUpn))); | ||
|
|
@@ -68,12 +85,6 @@ public async Task AgentUserIdentityGetsTokenForGraphAsync() | |
| [Fact] | ||
| public async Task AgentUserIdentityGetsTokenForGraphWithTenantOverrideAsync() | ||
| { | ||
| string instance = "https://login.microsoftonline.com/"; | ||
| string tenantId = "31a58c3b-ae9c-4448-9e8f-e9e143e800df"; // Replace with your tenant ID | ||
| string agentApplication = "d15884b6-a447-4dd5-a5a5-a668c49f6300"; // Replace with the actual agent application client ID | ||
| string agentIdentity = "d84da24a-2ea2-42b8-b5ab-8637ec208024"; // Replace with the actual agent identity | ||
| string userUpn = "[email protected]"; // Replace with the actual user upn. | ||
|
|
||
| IServiceCollection services = new ServiceCollection(); | ||
|
|
||
| // Configure the information about the agent application | ||
|
|
@@ -103,6 +114,19 @@ public async Task AgentUserIdentityGetsTokenForGraphWithTenantOverrideAsync() | |
| options); | ||
| Assert.NotNull(authorizationHeaderWithUserToken); | ||
|
|
||
| // Extract token from authorization header and validate claims using extension methods | ||
| string token = authorizationHeaderWithUserToken.Substring("Bearer ".Length); | ||
| var handler = new JwtSecurityTokenHandler(); | ||
| var jwtToken = handler.ReadJwtToken(token); | ||
| var claimsIdentity = new CaseSensitiveClaimsIdentity(jwtToken.Claims); | ||
|
|
||
| // Verify the token represents an agent user identity using the extension method | ||
| Assert.True(claimsIdentity.IsAgentUserIdentity()); | ||
|
|
||
| // Verify we can retrieve the parent agent blueprint if present | ||
| string? parentBlueprint = claimsIdentity.GetParentAgentBlueprint(); | ||
| Assert.Equal(agentApplication, parentBlueprint); | ||
|
|
||
| // If you want to call Microsoft Graph, just inject and use the Microsoft Graph SDK with the agent identity. | ||
| GraphServiceClient graphServiceClient = serviceProvider.GetRequiredService<GraphServiceClient>(); | ||
| var me = await graphServiceClient.Me.GetAsync(r => r.Options.WithAuthenticationOptions(options => | ||
|
|
@@ -124,12 +148,6 @@ public async Task AgentUserIdentityGetsTokenForGraphWithTenantOverrideAsync() | |
| [Fact] | ||
| public async Task AgentUserIdentityGetsTokenForGraphWithCacheAsync() | ||
| { | ||
| string instance = "https://login.microsoftonline.com/"; | ||
| string tenantId = "31a58c3b-ae9c-4448-9e8f-e9e143e800df"; // Replace with your tenant ID | ||
| string agentApplication = "d15884b6-a447-4dd5-a5a5-a668c49f6300"; // Replace with the actual agent application client ID | ||
| string agentIdentity = "d84da24a-2ea2-42b8-b5ab-8637ec208024"; // Replace with the actual agent identity | ||
| string userUpn = "[email protected]"; // Replace with the actual user upn. | ||
|
|
||
| IServiceCollection services = new ServiceCollection(); | ||
|
|
||
| // Configure the information about the agent application | ||
|
|
@@ -162,6 +180,19 @@ public async Task AgentUserIdentityGetsTokenForGraphWithCacheAsync() | |
| Assert.True(user.HasClaim(c => c.Type == "uid")); | ||
| Assert.True(user.HasClaim(c => c.Type == "utid")); | ||
|
|
||
| // Extract token from authorization header and validate claims using extension methods | ||
| string token = authorizationHeaderWithUserToken.Substring("Bearer ".Length); | ||
| var handler = new JwtSecurityTokenHandler(); | ||
| var jwtToken = handler.ReadJwtToken(token); | ||
| var claimsIdentity = new CaseSensitiveClaimsIdentity(jwtToken.Claims); | ||
|
|
||
| // Verify the token represents an agent user identity using the extension method | ||
| Assert.True(claimsIdentity.IsAgentUserIdentity()); | ||
|
|
||
| // Verify we can retrieve the parent agent blueprint if present | ||
| string? parentBlueprint = claimsIdentity.GetParentAgentBlueprint(); | ||
| Assert.Equal(agentApplication, parentBlueprint); | ||
|
|
||
| // Use the cached user | ||
| authorizationHeaderWithUserToken = await authorizationHeaderProvider.CreateAuthorizationHeaderForUserAsync( | ||
| scopes: ["https://graph.microsoft.com/.default"], | ||
|
|
@@ -180,11 +211,7 @@ public async Task AgentUserIdentityGetsTokenForGraphWithCacheAsync() | |
| [Fact] | ||
| public async Task AgentUserIdentityGetsTokenForGraphByUserIdAsync() | ||
| { | ||
| string instance = "https://login.microsoftonline.com/"; | ||
| string tenantId = "31a58c3b-ae9c-4448-9e8f-e9e143e800df"; // Replace with your tenant ID | ||
| string agentApplication = "d15884b6-a447-4dd5-a5a5-a668c49f6300"; // Replace with the actual agent application client ID | ||
| string agentIdentity = "d84da24a-2ea2-42b8-b5ab-8637ec208024"; // Replace with the actual agent identity | ||
| string userOid = "51c1aa1c-f6d0-4a92-936c-cadb27b717f2"; // Replace with the actual user OID. | ||
| string userOid = "04ea4dcd-f314-476f-be31-a13707cdd11e"; // Replace with the actual user OID. | ||
|
|
||
| IServiceCollection services = new ServiceCollection(); | ||
|
|
||
|
|
@@ -214,6 +241,19 @@ public async Task AgentUserIdentityGetsTokenForGraphByUserIdAsync() | |
| options); | ||
| Assert.NotNull(authorizationHeaderWithUserToken); | ||
|
|
||
| // Extract token from authorization header and validate claims using extension methods | ||
| string token = authorizationHeaderWithUserToken.Substring("Bearer ".Length); | ||
| var handler = new JwtSecurityTokenHandler(); | ||
| var jwtToken = handler.ReadJwtToken(token); | ||
| var claimsIdentity = new CaseSensitiveClaimsIdentity(jwtToken.Claims); | ||
|
|
||
| // Verify the token represents an agent user identity using the extension method | ||
| Assert.True(claimsIdentity.IsAgentUserIdentity()); | ||
|
|
||
| // Verify we can retrieve the parent agent blueprint if present | ||
| string? parentBlueprint = claimsIdentity.GetParentAgentBlueprint(); | ||
| Assert.Equal(agentApplication, parentBlueprint); | ||
|
|
||
| // If you want to call Microsoft Graph, just inject and use the Microsoft Graph SDK with the agent identity. | ||
| GraphServiceClient graphServiceClient = serviceProvider.GetRequiredService<GraphServiceClient>(); | ||
| var me = await graphServiceClient.Me.GetAsync(r => r.Options.WithAuthenticationOptions(options => options.WithAgentUserIdentity(agentIdentity, Guid.Parse(userOid)))); | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.