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.
This commit is contained in:
2026-02-02 16:27:45 +01:00
parent ada621ac46
commit 3923a3b403

View File

@@ -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);
}
/// <summary>
/// Retrieves the user's ID from the claims. Throws an exception if the ID is missing or invalid.
/// </summary>
@@ -32,8 +50,7 @@ namespace EnvelopeGenerator.API.Extensions
/// <exception cref="InvalidOperationException">Thrown if the user ID claim is missing or invalid.</exception>
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))
{