Newtonsoft.json: Serializing a .Net Core ClaimsIdentity with claims causes PlatformNotSupportedException

Created on 21 May 2018  路  4Comments  路  Source: JamesNK/Newtonsoft.Json

I am in the process of upgrading my application to use .Net Core 2 and .NetStandard. In several areas I am serializing a ClaimsIdentity for logging and transmission purposes.

Whenever I try to serialize a ClaimsIdentity that contains at least one claim, I get a PlatformNotSupportedException. I suspect this is due to the Binary Serialization changes introduced in .Net Core 2 (https://github.com/dotnet/corefx/issues/23415). This appears to have been addressed previously (https://github.com/JamesNK/Newtonsoft.Json/issues/1404) however I am still getting this error in 11.0.2.

Using a decompiler, the error occurs in the OnSerializingMethod method in ClaimsIdentity, and only occurs when the identity has 1 or more claims attached:

[OnSerializing]
private void OnSerializingMethod(StreamingContext context)
{
    if (this is ISerializable)
    {
        return;
    }

    _serializedNameType = _nameClaimType;
    _serializedRoleType = _roleClaimType;
    if (_instanceClaims != null && _instanceClaims.Count > 0)
    {
        throw new PlatformNotSupportedException(SR.PlatformNotSupported_Serialization); // BinaryFormatter would be needed
    }
}

Source/destination types

System.Security.Claims.ClaimsIdentity

Expected behavior

A fully serialized object with all claims intact.

Actual behavior

PlatformNotSupportedException: This instance contains state that cannot be serialized and deserialized on this platform.

Steps to reproduce

var identity = new ClaimsIdentity();
identity.AddClaim(new Claim("test", "test"));
var serializedIdentity = JsonConvert.SerializeObject(identity);

All 4 comments

That looks like the expected behavior of ClaimsIdentity. Raise it with the corefx team.

did we get a resolution for this?

Was this resolved?

This issue has not been resolved.
.net core 3.1

Was this page helpful?
0 / 5 - 0 ratings