From 3923a3b403967d2e5d767da1386a50bba352aa9f Mon Sep 17 00:00:00 2001 From: TekH Date: Mon, 2 Feb 2026 16:27:45 +0100 Subject: [PATCH] Refactor claim retrieval with GetRequiredClaimOfSender Added a private extension method GetRequiredClaimOfSender to ClaimsPrincipal for retrieving the first available value from multiple claim types, throwing a detailed exception if none are found. Refactored GetId to use this method, improving code reuse and clarity when handling user claims. --- .../Extensions/SenderClaimExtensions.cs | 25 ++++++++++++++++--- 1 file changed, 21 insertions(+), 4 deletions(-) diff --git a/EnvelopeGenerator.API/Extensions/SenderClaimExtensions.cs b/EnvelopeGenerator.API/Extensions/SenderClaimExtensions.cs index 613d9157..262968ed 100644 --- a/EnvelopeGenerator.API/Extensions/SenderClaimExtensions.cs +++ b/EnvelopeGenerator.API/Extensions/SenderClaimExtensions.cs @@ -1,5 +1,4 @@ -using Microsoft.AspNetCore.Mvc; -using System.Security.Claims; +using System.Security.Claims; namespace EnvelopeGenerator.API.Extensions { @@ -24,6 +23,25 @@ namespace EnvelopeGenerator.API.Extensions throw new InvalidOperationException(message); } + private static string GetRequiredClaimOfSender(this ClaimsPrincipal user, params string[] claimTypes) + { + string? value = null; + + foreach (var claimType in claimTypes) + { + value = user.FindFirstValue(claimType); + if (value is not null) + return value; + } + + var identity = user.Identity; + var principalName = identity?.Name ?? "(anonymous)"; + var authType = identity?.AuthenticationType ?? "(none)"; + var availableClaims = string.Join(", ", user.Claims.Select(c => $"{c.Type}={c.Value}")); + var message = $"Required claim among [{string.Join(", ", claimTypes)}] is missing for user '{principalName}' (auth: {authType}). Available claims: [{availableClaims}]."; + throw new InvalidOperationException(message); + } + /// /// Retrieves the user's ID from the claims. Throws an exception if the ID is missing or invalid. /// @@ -32,8 +50,7 @@ namespace EnvelopeGenerator.API.Extensions /// Thrown if the user ID claim is missing or invalid. public static int GetId(this ClaimsPrincipal user) { - var idValue = user.FindFirstValue(ClaimTypes.NameIdentifier) ?? user.FindFirstValue("sub"); - idValue ??= user.GetRequiredClaimOfSender(ClaimTypes.NameIdentifier); + var idValue = user.GetRequiredClaimOfSender(ClaimTypes.NameIdentifier, "sub"); if (!int.TryParse(idValue, out var result)) {