Skip to content

Instantly share code, notes, and snippets.

@markrendle
Created June 26, 2022 19:01
Show Gist options
  • Save markrendle/a770e9bfa518a7afe915061cf5369f97 to your computer and use it in GitHub Desktop.
Save markrendle/a770e9bfa518a7afe915061cf5369f97 to your computer and use it in GitHub Desktop.
Typed ClaimsPrincipal sketch
using System.Security.Claims;
using Microsoft.AspNetCore.Http;
namespace TypedClaimsPrincipal;
public interface IClaimsPrincipalProperties<out T>
where T : IClaimsPrincipalProperties<T>
{
static abstract T Create(ClaimsPrincipal claimsPrincipal);
}
public class ClaimsPrincipal<T>
where T : class, IClaimsPrincipalProperties<T>, new()
{
private readonly ClaimsPrincipal _principal;
private T? _properties;
public ClaimsPrincipal(ClaimsPrincipal principal)
{
_principal = principal;
}
public T Properties => _properties ??= T.Create(_principal);
}
public class MyClaimsProperties : IClaimsPrincipalProperties<MyClaimsProperties>
{
private readonly ClaimsPrincipal _principal;
private Guid? _userId;
public MyClaimsProperties(ClaimsPrincipal claimsPrincipal)
{
_principal = claimsPrincipal;
}
public static MyClaimsProperties Create(ClaimsPrincipal claimsPrincipal)
{
return new MyClaimsProperties(claimsPrincipal);
}
public Guid UserId => _userId ??= Guid.Parse(_principal.FindFirstValue("UserId"));
}
public static class HttpContextExtension
{
public static ClaimsPrincipal<T> GetTypedUser<T>(this HttpContext context)
where T : class, IClaimsPrincipalProperties<T>, new()
{
var instance = context.Features.Get<ClaimsPrincipal<T>>();
if (instance is null)
{
instance = new ClaimsPrincipal<T>(context.User);
context.Features.Set(instance);
}
return instance;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment