Skip to content

Commit

Permalink
Avoid allocation in TryGetAuthenticatedUser.
Browse files Browse the repository at this point in the history
As we reported in dotnet/runtime#107861 it turns out that retrieving ClaimsPrincipal.Identity causes an unnecessary allocation. This works around that.
  • Loading branch information
idg10 committed Sep 16, 2024
1 parent 945f301 commit c874c9f
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 1 deletion.
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
// <copyright file="ClaimsExtensions.cs" company="Endjin Limited">
// Copyright (c) Endjin Limited. All rights reserved.
// </copyright>

using System.Security.Claims;
using System.Security.Principal;

namespace Corvus.YarpPipelines;

/// <summary>
/// Low-allocation utilities for working with claims.
/// </summary>
internal static class ClaimsExtensions
{
/// <summary>
/// A non-allocating version of <see cref="ClaimsPrincipal.Identity"/>.
/// </summary>
/// <param name="claimsPrincipal">
/// The principal from which to extract the primary identity.
/// </param>
/// <returns>The primary identity.</returns>
/// <remarks>
/// <see cref="ClaimsPrincipal.Identity"/> allocates an enumerator, because
/// it executes a foreach over the identities. In most cases, these identities
/// are in an IList, making zero-allocation enumeration possible, and since
/// the .NET runtime implementation doesn't do that (at least, not in .NET 8.0)
/// we have to do it ourselves. (See https://github.com/dotnet/runtime/issues/107861)
/// </remarks>
public static IIdentity? GetPrimaryIdentity(this ClaimsPrincipal claimsPrincipal)
{
if (claimsPrincipal.Identities is IList<ClaimsIdentity> identities)
{
for (int i = 0; i < identities.Count; i++)
{
if (identities[i] is not null)
{
return identities[i];
}
}
}

return claimsPrincipal.Identity;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,8 @@ public static void SetUser(this YarpRequestPipelineState state, ClaimsPrincipal
public static bool TryGetAuthenticatedUser(this YarpRequestPipelineState state, [NotNullWhen(true)] out ClaimsPrincipal? user)
{
user = state.RequestTransformContext.HttpContext.User;
return user is not null && user.Identity?.IsAuthenticated == true;

return user is not null && user.GetPrimaryIdentity()?.IsAuthenticated == true;
}

/// <summary>
Expand Down

0 comments on commit c874c9f

Please sign in to comment.