Skip to content

Instantly share code, notes, and snippets.

@haamond
Created July 18, 2023 09:30
Show Gist options
  • Save haamond/c971bccf729e742f47a1f278f3f842f8 to your computer and use it in GitHub Desktop.
Save haamond/c971bccf729e742f47a1f278f3f842f8 to your computer and use it in GitHub Desktop.
Claim's JsonConverter for System.Text.Json
using System.Security.Claims;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace System.Security.Claims.Serialization;
public class ClaimJsonConverter : JsonConverter<Claim>
{
// Supported properties:
private const string Issuer = "Issuer";
private const string OriginalIssuer = "OriginalIssuer";
private const string Type = "Type";
private const string Value = "Value";
private const string ValueType = "ValueType";
public static readonly ClaimJsonConverter Instance = new();
public override Claim Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
if (reader.TokenType != JsonTokenType.StartObject)
throw new JsonException("Expected start of data");
string? issuer = null;
string? originalIssuer = null;
string? type = null;
string? value = null;
string? valueType = null;
while (reader.Read())
{
if (reader.TokenType == JsonTokenType.EndObject)
{
if (type is null)
throw new JsonException($"Missing property: {Type}");
if (value is null)
throw new JsonException($"Missing property: {Value}");
return new Claim(type, value, valueType, issuer, originalIssuer);
}
if (reader.TokenType == JsonTokenType.PropertyName)
{
var propertyName = reader.GetString();
reader.Read();
switch (propertyName)
{
case Issuer:
issuer = reader.GetString();
break;
case OriginalIssuer:
originalIssuer = reader.GetString();
break;
case Type:
type = reader.GetString();
break;
case Value:
value = reader.GetString();
break;
case ValueType:
valueType = reader.GetString();
break;
default:
throw new JsonException($"Unexpected property: {propertyName}");
}
}
}
throw new JsonException("Unexpected end of data");
}
public override void Write(Utf8JsonWriter writer, Claim value, JsonSerializerOptions options)
{
writer.WriteStartObject();
writer.WriteString(Issuer, value.Issuer);
writer.WriteString(OriginalIssuer, value.OriginalIssuer);
writer.WriteString(Type, value.Type);
writer.WriteString(Value, value.Value);
writer.WriteString(ValueType, value.ValueType);
writer.WriteEndObject();
}
}
@haamond
Copy link
Author

haamond commented Jul 18, 2023

Using:

        const string json = @"{
            ""Type"": ""sub"",
            ""Value"": ""1234567890"",
            ""ValueType"": ""http://www.w3.org/2001/XMLSchema#string"",
            ""Issuer"": ""Issuer"",
            ""OriginalIssuer"": ""OriginalIssuer""
        }";

        var options = new JsonSerializerOptions();
        options.Converters.Add(ClaimJsonConverter.Instance);

        var claim = JsonSerializer.Deserialize<Claim>(json, options);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment