Created
July 18, 2023 09:30
-
-
Save haamond/c971bccf729e742f47a1f278f3f842f8 to your computer and use it in GitHub Desktop.
Claim's JsonConverter for System.Text.Json
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
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(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Using: