Skip to content
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

Extended AspNetUserClaimLayoutRenderer to handle multi-values #975

Merged
merged 5 commits into from
Aug 4, 2023
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
61 changes: 47 additions & 14 deletions src/Shared/LayoutRenderers/AspNetUserClaimLayoutRenderer.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
#if ASP_NET_CORE || NET46_OR_GREATER

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Security.Claims;
using System.Security.Principal;
using System.Text;
using NLog.Common;
using NLog.Config;
Expand All @@ -14,26 +17,28 @@ namespace NLog.Web.LayoutRenderers
/// ASP.NET User ClaimType Value Lookup.
/// </summary>
/// <remarks>
/// <code>${aspnet-user-claim:ClaimType=Name}</code>
/// <code>${aspnet-user-claim:ClaimType=Name}</code> to render a single specific claim type
/// <code>${aspnet-user-claim}</code> to render all claim types
/// </remarks>
/// <seealso href="https://github.com/NLog/NLog/wiki/AspNet-User-Claim-Layout-Renderer">Documentation on NLog Wiki</seealso>
[LayoutRenderer("aspnet-user-claim")]
public class AspNetUserClaimLayoutRenderer : AspNetLayoutRendererBase
public class AspNetUserClaimLayoutRenderer : AspNetLayoutMultiValueRendererBase
{
/// <summary>
/// Key to lookup using <see cref="ClaimsIdentity.FindFirst(string)"/> with fallback to <see cref="ClaimsPrincipal.FindFirst(string)"/>
/// </summary>
/// <remarks>
/// When value is prefixed with "ClaimTypes." (Remember dot) then ít will lookup in well-known claim types from <see cref="ClaimTypes"/>. Ex. ClaimsTypes.Name
/// If this is null or empty then all claim types are rendered
/// </remarks>
[RequiredParameter]
[DefaultParameter]
public string ClaimType { get; set; }

/// <inheritdoc />
protected override void InitializeLayoutRenderer()
{
if (ClaimType?.Trim().StartsWith("ClaimTypes.", StringComparison.OrdinalIgnoreCase) == true || ClaimType?.Trim().StartsWith("ClaimType.", StringComparison.OrdinalIgnoreCase) == true)
if (ClaimType?.Trim().StartsWith("ClaimTypes.", StringComparison.OrdinalIgnoreCase) == true ||
ClaimType?.Trim().StartsWith("ClaimType.", StringComparison.OrdinalIgnoreCase) == true)
{
var fieldName = ClaimType.Substring(ClaimType.IndexOf('.') + 1).Trim();
var claimTypesField = typeof(ClaimTypes).GetField(fieldName, BindingFlags.Static | BindingFlags.Public);
Expand All @@ -51,29 +56,57 @@ protected override void DoAppend(StringBuilder builder, LogEventInfo logEvent)
{
try
{
var claimsPrincipel = HttpContextAccessor.HttpContext.User;
if (claimsPrincipel == null)
var claimsPrincipal = HttpContextAccessor.HttpContext.User;
if (claimsPrincipal == null)
{
InternalLogger.Debug("aspnet-user-claim - HttpContext User is null");
return;
}

var claimsIdentity = claimsPrincipel.Identity as ClaimsIdentity; // Prioritize primary identity
var claim = claimsIdentity?.FindFirst(ClaimType)
#if ASP_NET_CORE
?? claimsPrincipel.FindFirst(ClaimType)
#endif
;
if (claim != null)
if (string.IsNullOrEmpty(ClaimType))
{
SerializePairs(GetAllClaims(claimsPrincipal), builder, logEvent);
}
else
{
builder.Append(claim?.Value);
var claim = GetClaim(claimsPrincipal, ClaimType);
if (claim != null)
{
builder.Append(claim?.Value);
}
}
}
catch (ObjectDisposedException ex)
{
InternalLogger.Debug(ex, "aspnet-user-claim - HttpContext has been disposed");
}
}

#if NET46
private IEnumerable<KeyValuePair<string, string>> GetAllClaims(IPrincipal claimsPrincipal)
{
return GetAllClaims(claimsPrincipal as ClaimsPrincipal);
}
#endif
private IEnumerable<KeyValuePair<string, string>> GetAllClaims(ClaimsPrincipal claimsPrincipal)
{
return claimsPrincipal?.Claims?.Select(claim =>
new KeyValuePair<string, string>(claim.Type, claim.Value)) ??
new List<KeyValuePair<string, string>>();
}
#if NET46
private Claim GetClaim(IPrincipal claimsPrincipal, string claimType)
#else
private Claim GetClaim(ClaimsPrincipal claimsPrincipal, string claimType)
#endif
{
var claimsIdentity = claimsPrincipal.Identity as ClaimsIdentity; // Prioritize primary identity
return claimsIdentity?.FindFirst(claimType)
#if ASP_NET_CORE
?? claimsPrincipal.FindFirst(claimType)
#endif
;
}
}
}

Expand Down
30 changes: 30 additions & 0 deletions tests/Shared/LayoutRenderers/AspNetUserClaimLayoutRendererTests.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
#if ASP_NET_CORE || NET46_OR_GREATER

using System;
using System.Collections.Generic;
using System.Security.Claims;
using System.Security.Principal;
#if ASP_NET_CORE
using Microsoft.Extensions.Primitives;
Expand Down Expand Up @@ -66,6 +69,33 @@ public void UserClaimTypeNameRendersValue()
// Assert
Assert.Equal(expectedResult, result);
}

[Fact]
public void AllRendersAllValue()
{
// Arrange
var (renderer, httpContext) = CreateWithHttpContext();

var expectedResult = "http://schemas.xmlsoap.org/ws/2009/09/identity/claims/actor=ActorValue1,http://schemas.xmlsoap.org/ws/2009/09/identity/claims/actor=ActorValue2,http://schemas.xmlsoap.org/ws/2005/05/identity/claims/country=CountryValue";

var principal = Substitute.For<System.Security.Claims.ClaimsPrincipal>();

principal.Claims.Returns(new List<Claim>()
{
new System.Security.Claims.Claim(ClaimTypes.Actor, "ActorValue1"),
new System.Security.Claims.Claim(ClaimTypes.Actor, "ActorValue2"),
new System.Security.Claims.Claim(ClaimTypes.Country, "CountryValue")
}
);

httpContext.User.Returns(principal);

// Act
string result = renderer.Render(new LogEventInfo());

// Assert
Assert.Equal(expectedResult, result);
}
}
}

Expand Down