Skip to content
Merged
Show file tree
Hide file tree
Changes from 5 commits
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
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 function codes (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;
}
}
}
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
55 changes: 55 additions & 0 deletions tests/E2E Tests/AgentApplications/AgentUserIdentityTestscs.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,15 @@
#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
{
Expand Down Expand Up @@ -52,6 +55,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();
// Note: parentBlueprint may be null if the claim is not present in this token

// 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)));
Expand Down Expand Up @@ -103,6 +119,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();
// Note: parentBlueprint may be null if the claim is not present in this token

// 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 =>
Expand Down Expand Up @@ -162,6 +191,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();
// Note: parentBlueprint may be null if the claim is not present in this token

// Use the cached user
authorizationHeaderWithUserToken = await authorizationHeaderProvider.CreateAuthorizationHeaderForUserAsync(
scopes: ["https://graph.microsoft.com/.default"],
Expand Down Expand Up @@ -214,6 +256,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();
// Note: parentBlueprint may be null if the claim is not present in this token

// 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))));
Expand Down
139 changes: 139 additions & 0 deletions tests/Microsoft.Identity.Web.Test/AgentIdentityExtensionsTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using System.Security.Claims;
using Microsoft.Identity.Web.Test.Common;
using Microsoft.IdentityModel.Tokens;
using Xunit;

namespace Microsoft.Identity.Web.Test
{
public class AgentIdentityExtensionsTests
{
private const string ParentAgentBlueprintClaim = "xms_par_app_azp";
private const string ParentAgentBlueprintValue = "agent-blueprint-123";

private const string SubjectFunctionClaim = "xms_sub_fct";

[Fact]
public void GetParentAgentBlueprint_FromClaimsPrincipal_WithClaim_ReturnsValue()
{
var principal = new ClaimsPrincipal(
new CaseSensitiveClaimsIdentity(new[]
{
new Claim(ParentAgentBlueprintClaim, ParentAgentBlueprintValue),
}));

Assert.Equal(ParentAgentBlueprintValue, principal.GetParentAgentBlueprint());
}

[Fact]
public void GetParentAgentBlueprint_FromClaimsPrincipal_NoClaim_ReturnsNull()
{
var principal = new ClaimsPrincipal();
Assert.Null(principal.GetParentAgentBlueprint());
}

[Fact]
public void GetParentAgentBlueprint_FromClaimsIdentity_WithClaim_ReturnsValue()
{
var identity = new CaseSensitiveClaimsIdentity(new[]
{
new Claim(ParentAgentBlueprintClaim, ParentAgentBlueprintValue),
});

Assert.Equal(ParentAgentBlueprintValue, identity.GetParentAgentBlueprint());
}

[Fact]
public void GetParentAgentBlueprint_FromClaimsIdentity_NoClaim_ReturnsNull()
{
var identity = new CaseSensitiveClaimsIdentity();
Assert.Null(identity.GetParentAgentBlueprint());
}

[Fact]
public void IsAgentUserIdentity_Principal_SpaceSeparated_Contains13_ReturnsTrue()
{
var principal = new ClaimsPrincipal(
new CaseSensitiveClaimsIdentity(new[]
{
new Claim(SubjectFunctionClaim, "1 2 13 15"),
}));

Assert.True(principal.IsAgentUserIdentity());
}

[Fact]
public void IsAgentUserIdentity_Principal_SpaceSeparated_No13_ReturnsFalse()
{
var principal = new ClaimsPrincipal(
new CaseSensitiveClaimsIdentity(new[]
{
new Claim(SubjectFunctionClaim, "1 2 3 4"),
}));

Assert.False(principal.IsAgentUserIdentity());
}

[Fact]
public void IsAgentUserIdentity_Principal_ExtraWhitespace_Contains13_ReturnsTrue()
{
var principal = new ClaimsPrincipal(
new CaseSensitiveClaimsIdentity(new[]
{
new Claim(SubjectFunctionClaim, " 9 13 21 "),
}));

Assert.True(principal.IsAgentUserIdentity());
}

[Fact]
public void IsAgentUserIdentity_Principal_InvalidToken_ReturnsFalse()
{
var principal = new ClaimsPrincipal(
new CaseSensitiveClaimsIdentity(new[]
{
new Claim(SubjectFunctionClaim, "12 a 13"),
}));

Assert.False(principal.IsAgentUserIdentity());
}

[Fact]
public void IsAgentUserIdentity_Principal_NoClaim_ReturnsFalse()
{
var principal = new ClaimsPrincipal();
Assert.False(principal.IsAgentUserIdentity());
}

[Fact]
public void IsAgentUserIdentity_Identity_SpaceSeparated_Contains13_ReturnsTrue()
{
var identity = new CaseSensitiveClaimsIdentity(new[]
{
new Claim(SubjectFunctionClaim, "7 8 13 21"),
});

Assert.True(identity.IsAgentUserIdentity());
}

[Fact]
public void IsAgentUserIdentity_Identity_EmptyString_ReturnsFalse()
{
var identity = new CaseSensitiveClaimsIdentity(new[]
{
new Claim(SubjectFunctionClaim, " "),
});

Assert.False(identity.IsAgentUserIdentity());
}

[Fact]
public void IsAgentUserIdentity_Identity_NoClaim_ReturnsFalse()
{
var identity = new CaseSensitiveClaimsIdentity();
Assert.False(identity.IsAgentUserIdentity());
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
</PropertyGroup>

<ItemGroup>
<ProjectReference Include="..\..\src\Microsoft.Identity.Web.AgentIdentities\Microsoft.Identity.Web.AgentIdentities.csproj" />
<ProjectReference Include="..\..\src\Microsoft.Identity.Web.DownstreamApi\Microsoft.Identity.Web.DownstreamApi.csproj" />
<ProjectReference Condition="'$(TargetFramework)' == 'net8.0' Or '$(TargetFramework)' == 'net9.0'" Include="..\..\src\Microsoft.Identity.Web.MicrosoftGraph\Microsoft.Identity.Web.MicrosoftGraph.csproj" />
<ProjectReference Include="..\..\src\Microsoft.Identity.Web\Microsoft.Identity.Web.csproj" />
Expand Down