lvermeulen / Keycloak.Net

C# client for Keycloak 6.x
MIT License
203 stars 120 forks source link

User attributes serialization issue (dictionary key capitalize issue) #38

Closed redsaprogrammer closed 3 years ago

redsaprogrammer commented 3 years ago

I'm trying to send user attributes during user creation

 var attributes = new Dictionary<string, IEnumerable<string>>
 {
      ["ID"] = new[] {myId}
 };

The problem is that it sends it using "id" key (not "ID"). I think the library creates it's own JsonSerializer with ContractResolver = (IContractResolver) new CamelCasePropertyNamesContractResolver() and there is no way to override it with my custom serializer:

new NewtonsoftJsonSerializer(new JsonSerializerSettings
{
      ContractResolver = new DefaultContractResolver
      {
            NamingStrategy = new CamelCaseNamingStrategy
            {
                  ProcessDictionaryKeys = false
            }
       }
});
kampilan commented 3 years ago

This is what you are looking for I think:

var client = new KeycloakClient( "https://auth.abc.com", "AAAAA", "BBBBB" );
client.SetSerializer(new TheSerialzer());

public class TheSerialzer : ISerializer
{

    private static JsonSerializerSettings Settings { get; } = new JsonSerializerSettings
    {
        ContractResolver = new DefaultContractResolver {NamingStrategy = new CamelCaseNamingStrategy {ProcessDictionaryKeys = false}}
    };

    public string Serialize(object obj)
    {

        var json = JsonConvert.SerializeObject(obj, Settings);
        return json;

    }

    public T Deserialize<T>(string s)
    {
        var obj = JsonConvert.DeserializeObject<T>(s, Settings);
        return obj;
    }

    public T Deserialize<T>(Stream stream)
    {

        using( var reader = new StreamReader(stream) )
        {
            var json = reader.ReadToEnd();
            var obj = JsonConvert.DeserializeObject<T>(json, Settings);
            return obj;
        }

    }

}