Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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 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;
}
}
}
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
84 changes: 62 additions & 22 deletions tests/E2E Tests/AgentApplications/AgentUserIdentityTestscs.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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();

Expand Down Expand Up @@ -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)));
Expand All @@ -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
Expand Down Expand Up @@ -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 =>
Expand All @@ -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
Expand Down Expand Up @@ -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"],
Expand All @@ -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();

Expand Down Expand Up @@ -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))));
Expand Down
16 changes: 16 additions & 0 deletions tests/E2E Tests/AgentApplications/AutonomousAgentTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,15 @@
// Licensed under the MIT License.
#if !FROM_GITHUB_ACTION

using System.IdentityModel.Tokens.Jwt;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Graph;
using Microsoft.Identity.Abstractions;
using Microsoft.Identity.Web;
using Microsoft.Identity.Web.TokenCacheProviders.Distributed;
using Microsoft.Identity.Web.TokenCacheProviders.InMemory;
using Microsoft.IdentityModel.Tokens;

namespace AgentApplicationsTests
{
Expand Down Expand Up @@ -46,6 +48,20 @@ public async Task AutonomousAgentGetsAppTokenForAgentIdentityToCallGraphAsync()
//// Request user tokens in autonomous agents.
string authorizationHeaderWithAppToken = await authorizationHeaderProvider.CreateAuthorizationHeaderForAppAsync("https://graph.microsoft.com/.default", options);

// Extract token from authorization header and validate claims using extension methods
string token = authorizationHeaderWithAppToken.Substring("Bearer ".Length);
var handler = new JwtSecurityTokenHandler();
var jwtToken = handler.ReadJwtToken(token);
var claimsIdentity = new CaseSensitiveClaimsIdentity(jwtToken.Claims);

// Verify the token does not represent an agent user identity using the extension method
Assert.False(claimsIdentity.IsAgentUserIdentity());

// Verify we can retrieve the parent agent blueprint if present
string? parentBlueprint = claimsIdentity.GetParentAgentBlueprint();
string agentApplication = configuration["AzureAd:ClientId"]!;
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 apps = await graphServiceClient.Applications.GetAsync(r => r.Options.WithAuthenticationOptions(options =>
Expand Down
Loading
Loading