Created
June 26, 2022 19:01
-
-
Save markrendle/a770e9bfa518a7afe915061cf5369f97 to your computer and use it in GitHub Desktop.
Typed ClaimsPrincipal sketch
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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