persistence/Persistence.API/Extensions.cs

27 lines
724 B
C#
Raw Normal View History

using System.ComponentModel;
using System.Security.Claims;
namespace Persistence.API;
public static class Extensions
{
public static T GetUserId<T>(this ClaimsPrincipal principal)
{
if (principal == null)
throw new ArgumentNullException(nameof(principal));
var loggedInUserId = principal.FindFirstValue(ClaimTypes.NameIdentifier);
if (String.IsNullOrEmpty(loggedInUserId))
throw new ArgumentNullException(nameof(loggedInUserId));
var result = TypeDescriptor.GetConverter(typeof(T)).ConvertFromInvariantString(loggedInUserId);
if (result is null)
throw new ArgumentNullException(nameof(result));
return (T)result;
}
}