41 lines
1.1 KiB
C#
41 lines
1.1 KiB
C#
using System.Security.Claims;
|
|
|
|
namespace Hutopy.Web.Common;
|
|
|
|
public static class ClaimsPrincipalExtensions
|
|
{
|
|
public static Guid GetUserId(this ClaimsPrincipal claims)
|
|
{
|
|
return (Guid)claims.GetFirstValue<Guid>(ClaimTypes.NameIdentifier);
|
|
}
|
|
|
|
public static string GetFirstName(this ClaimsPrincipal claims)
|
|
{
|
|
return (string)claims.GetFirstValue<string>(ClaimTypes.GivenName);
|
|
}
|
|
|
|
public static string GetLastName(this ClaimsPrincipal claims)
|
|
{
|
|
return (string)claims.GetFirstValue<string>(ClaimTypes.Surname);
|
|
}
|
|
|
|
public static string GetEmail(this ClaimsPrincipal claims)
|
|
{
|
|
return (string)claims.GetFirstValue<string>(ClaimTypes.Email);
|
|
}
|
|
|
|
public static object GetFirstValue<TValue>(this ClaimsPrincipal claims, string key)
|
|
{
|
|
var claim = claims.FindFirst(key);
|
|
|
|
if (claim is null) throw new MissingClaimException(key);
|
|
|
|
if (typeof(TValue) == typeof(Guid))
|
|
{
|
|
return Guid.Parse(claim.Value);
|
|
}
|
|
|
|
return Convert.ChangeType(claim.Value, typeof(TValue));
|
|
}
|
|
}
|