Cannot Deserialize ClaimsPrincipal

3.6k Views Asked by At

Given I create a claims identity and subsequently a principal. Then I serialize the principal. Inspecting the json string I can confirm that the "Role" claim is there as well as the identity.

Deserializing it back results in an object with empty properties. The .Claims and .Identity is lost.

var identity = new ClaimsIdentity(new List<Claim>() { new Claim("Role", "Admin") });
var principal = new ClaimsPrincipal(identity);

string serialized = JsonConvert.SerializeObject(principal, new JsonSerializerSettings() { ReferenceLoopHandling = ReferenceLoopHandling.Ignore });
ClaimsPrincipal deserialized = JsonConvert.DeserializeObject<ClaimsPrincipal>(serialized); // The object has all properties empty

Question: How can I ensure the object is correctly deserialized?

1

There are 1 best solutions below

0
SNO On

Facing the same issue I guess the claimsPrinciple is a "protected" object that can't be "copied" that easy. Having a look into a Swagger-Generated code one solution could be creating new classes. Following a snippet from swagger-gen:

[System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "9.13.15.0 (Newtonsoft.Json v11.0.0.0)")]
    public partial class ClaimsPrincipal 
    {
        [Newtonsoft.Json.JsonProperty("Claims", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)]
        public System.Collections.Generic.ICollection<Claim> Claims { get; set; }

        [Newtonsoft.Json.JsonProperty("Identities", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)]
        public System.Collections.Generic.ICollection<ClaimsIdentity> Identities { get; set; }

        [Newtonsoft.Json.JsonProperty("Identity", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)]
        public IIdentity Identity { get; set; }

        public string ToJson() 
        {
            return Newtonsoft.Json.JsonConvert.SerializeObject(this);
        }

        public static ClaimsPrincipal FromJson(string data)
        {
            return Newtonsoft.Json.JsonConvert.DeserializeObject<ClaimsPrincipal>(data);
        }

    }