uruk-project / Jwt

JSON Web Token implementation for .Net & .Net Core
MIT License
81 stars 13 forks source link

add custom claims with object value #498

Closed althunibat closed 3 years ago

althunibat commented 3 years ago

i couldn't find a way to add custom claims to JwsDescriptor which accepts claim value as object, where it get automatically json serialized when jwt is written.

e.g.

descriptor.AddClaim("https://hasura.io/jwt/claims", new HasuraClaim { UserId = user.Id, DefaultRole = "user", Roles = new[] { "user" } });

ycrumeyrolle commented 3 years ago

Hi, there is not way to serialize a custom object for the moment. You can this achieve by using a JwtObject and a JwtArray:

            var descriptor = new JwsDescriptor();
            descriptor.AddClaim("https//hasura.io/jwt/claims", new JwtObject
            {
                { "user_id", 123 },
                { "default_role", "user" },
                { "roles", new JwtArray { "user"} }
            });

This is "by design" for avoiding two issues: 1/ Casing issue : how should be cased the custom property names? With the JwtObject, you specify the casing. 2/ Type mismatch : custom objects contains custom value types and there is always debates on its representation in JSON. The JwtObject only support native JSON types (String, Number, Boolean & Null) and the DateTime because there is convention for the mapping (epoch time).

ycrumeyrolle commented 3 years ago

For convenience it should be interessant to allow

                { "roles", new[] { "user"} }

for hiding the JwtArray in case of string array.

ycrumeyrolle commented 3 years ago

Fixed in version 2.0.0-beta.1

https://github.com/uruk-project/Jwt/blob/1c98645df6fbd76d5ad3ac4b1075563db519bed4/samples/JwsCreationSample/Program.cs#L62-L84

If required, the JSON serialization behavior can be controled with the JsonSerializationBehavior.SerializerOptions property, for example by adding a JsonConverter<HasuraClaim> to JsonSerializationBehavior.SerializerOptions.Converters