using System; using System.Security.Claims; using System.Security.Principal; namespace Umbraco.Core { public static class ClaimsIdentityExtensions { public static T GetUserId(this IIdentity identity) { var strId = identity.GetUserId(); var converted = strId.TryConvertTo(); return converted.ResultOr(default); } /// /// Returns the user id from the of either the claim type or "sub" /// /// /// /// The string value of the user id if found otherwise null /// public static string GetUserId(this IIdentity identity) { if (identity == null) throw new ArgumentNullException(nameof(identity)); string userId = null; if (identity is ClaimsIdentity claimsIdentity) { userId = claimsIdentity.FindFirstValue(ClaimTypes.NameIdentifier) ?? claimsIdentity.FindFirstValue("sub"); } return userId; } /// /// Returns the user name from the of either the claim type or "preferred_username" /// /// /// /// The string value of the user name if found otherwise null /// public static string GetUserName(this IIdentity identity) { if (identity == null) throw new ArgumentNullException(nameof(identity)); string username = null; if (identity is ClaimsIdentity claimsIdentity) { username = claimsIdentity.FindFirstValue(ClaimTypes.Name) ?? claimsIdentity.FindFirstValue("preferred_username"); } return username; } /// /// Returns the first claim value found in the for the given claimType /// /// /// /// /// The string value of the claim if found otherwise null /// public static string FindFirstValue(this ClaimsIdentity identity, string claimType) { if (identity == null) throw new ArgumentNullException(nameof(identity)); return identity.FindFirst(claimType)?.Value; } } }