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)) {