Created
March 19, 2020 12:13
-
-
Save rikbosch/73e4e71bfd2a4bb1d533ae82f89aa1d5 to your computer and use it in GitHub Desktop.
Orleans ClaimsPrincipal Serializer
This file contains hidden or 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
[Serializable] | |
public class SerializableClaimsPrincipal | |
{ | |
public List<SerializableClaimsIdentity> Identities { get; set; } | |
} | |
[Serializable] | |
public class SerializableClaimsIdentity | |
{ | |
public string AuthenticationType { get; set; } | |
public string NameType { get; set; } | |
public string RoleType { get; set; } | |
public List<SerializableClaim> Claims { get; set; } | |
} | |
[Serializable] | |
public class SerializableClaim | |
{ | |
public SerializableClaim() | |
{ | |
ValueType = ClaimValueTypes.String; | |
} | |
public string Type { get; set; } | |
public string Value { get; set; } | |
public string ValueType { get; set; } | |
} | |
[Serializer(typeof(ClaimsPrincipal))] | |
internal class ClaimPrincipalSerializer | |
{ | |
[CopierMethod] | |
public static object DeepCopier(object original, ICopyContext context) => original; | |
[SerializerMethod] | |
public static void Serializer(object untypedInput, ISerializationContext context, Type expected) | |
{ | |
var source = (ClaimsPrincipal)untypedInput; | |
var principal = new SerializableClaimsPrincipal | |
{ | |
Identities = new List<SerializableClaimsIdentity>(source.Identities.Count()) | |
}; | |
foreach (var identity in source.Identities) | |
{ | |
var serializableClaimsIdentity = new SerializableClaimsIdentity | |
{ | |
AuthenticationType = identity.AuthenticationType, | |
NameType = identity.NameClaimType, | |
RoleType = identity.RoleClaimType, | |
Claims = new List<SerializableClaim>(identity.Claims.Count()) | |
}; | |
serializableClaimsIdentity.Claims.AddRange(identity.Claims.Select(claim => | |
new SerializableClaim {Type = claim.Type, Value = claim.Value})); | |
principal.Identities.Add(serializableClaimsIdentity); | |
} | |
SerializationManager.SerializeInner(principal, context); | |
} | |
[DeserializerMethod] | |
public static object Deserializer(Type expected, IDeserializationContext context) | |
{ | |
var source = SerializationManager.DeserializeInner<SerializableClaimsPrincipal>(context); | |
if (source == null) | |
{ | |
return null; | |
} | |
var identities = source.Identities.Select(identity => | |
new ClaimsIdentity( | |
identity.Claims.Select(claim => new Claim(claim.Type, claim.Value)), | |
identity.AuthenticationType, | |
identity.NameType, | |
identity.RoleType)); | |
var target = new ClaimsPrincipal(identities); | |
return target; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment