Cannot Deserialize ClaimsPrincipal
Asked Answered
O

1

6

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?

Oof answered 24/1, 2018 at 14:38 Comment(0)
O
0

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);
        }

    }
Odometer answered 13/2, 2019 at 6:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.