Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,19 @@
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.Module;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.databind.module.SimpleModule;
import io.jsonwebtoken.io.AbstractSerializer;
import io.jsonwebtoken.lang.Assert;

import java.io.OutputStream;
import java.lang.reflect.Array;
import java.util.Map;

/**
* Serializer using a Jackson {@link ObjectMapper}.
Expand Down Expand Up @@ -87,6 +92,40 @@ public JacksonSerializer(ObjectMapper objectMapper) {
protected void doSerialize(T t, OutputStream out) throws Exception {
Assert.notNull(out, "OutputStream cannot be null.");
ObjectWriter writer = this.objectMapper.writer().without(JsonGenerator.Feature.AUTO_CLOSE_TARGET);
writer.writeValue(out, t);
writer.writeValue(out, t instanceof Map ? toJsonNode((Map<?, ?>) t) : t);
}

/*
* Map values are declared as Object to Jackson, so type information declared on a value's base type is not
* included. Serializing each map value independently lets Jackson resolve any type information configured for its
* runtime type while retaining the existing behavior for values without type information.
*/
private JsonNode toJsonNode(Object value) {
if (value == null) {
return objectMapper.nullNode();
}
if (value instanceof Map) {
ObjectNode node = objectMapper.createObjectNode();
for (Map.Entry<?, ?> entry : ((Map<?, ?>) value).entrySet()) {
node.set(String.valueOf(entry.getKey()), toJsonNode(entry.getValue()));
}
return node;
}
if (value instanceof Iterable) {
ArrayNode node = objectMapper.createArrayNode();
for (Object element : (Iterable<?>) value) {
node.add(toJsonNode(element));
}
return node;
}
if (value.getClass().isArray() && !value.getClass().getComponentType().isPrimitive()) {
ArrayNode node = objectMapper.createArrayNode();
int length = Array.getLength(value);
for (int i = 0; i < length; i++) {
node.add(toJsonNode(Array.get(value, i)));
}
return node;
}
return objectMapper.valueToTree(value);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -118,4 +118,25 @@ class JacksonSerializerTest {
byte[] result = serialize([hello: '世界'])
assertArrayEquals expected, result
}

@Test
void testMapValues() {
byte[] result = serialize([bytes: Strings.utf8('hi'), chars: 'hi'.toCharArray()])
assertEquals '{"bytes":"aGk=","chars":"hi"}', Strings.utf8(result)
}

@Test
void testNestedMapValues() {
def value = [
nullValue: null,
map : [string: 'value'],
iterable : ['one', 'two'],
array : ['three', 'four'] as String[]
]

byte[] result = serialize(value)

assertEquals '{"nullValue":null,"map":{"string":"value"},"iterable":["one","two"],' +
'"array":["three","four"]}', Strings.utf8(result)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,16 @@
*/
package io.jsonwebtoken

import com.fasterxml.jackson.annotation.JsonTypeInfo
import com.fasterxml.jackson.databind.ObjectMapper
import io.jsonwebtoken.jackson.io.JacksonDeserializer
import io.jsonwebtoken.jackson.io.JacksonSerializer
import io.jsonwebtoken.io.Decoders
import org.junit.Test

import static org.junit.Assert.assertEquals
import static org.junit.Assert.assertNotNull
import static org.junit.Assert.assertTrue

class CustomObjectDeserializationTest {

Expand All @@ -35,6 +40,9 @@ class CustomObjectDeserializationTest {

String jwtString = Jwts.builder().claim("cust", customBean).compact()

String payload = new String(Decoders.BASE64URL.decode(jwtString.split('\\.')[1]), 'UTF-8')
assertEquals '{"cust":{"key1":"value1","key2":42}}', payload

// no custom deserialization, object is a map
Jwt<Header, Claims> jwt = Jwts.parser().unsecured().build().parseUnsecuredClaims(jwtString)
assertNotNull jwt
Expand All @@ -48,6 +56,67 @@ class CustomObjectDeserializationTest {
assertEquals customBean, result
}

/**
* Asserts https://github.com/jwtk/jjwt/issues/1065
*/
@Test
void testCustomObjectDeserializationWithJsonTypeInfo() {

ObjectMapper objectMapper = new ObjectMapper()
.addMixIn(Authority, AuthorityMixin)
SimpleAuthority authority = new SimpleAuthority('ROLE_ADMIN')

String jwtString = Jwts.builder()
.json(new JacksonSerializer(objectMapper))
.claim('authority', authority)
.compact()

String payload = new String(Decoders.BASE64URL.decode(jwtString.split('\\.')[1]), 'UTF-8')
assertTrue payload.contains('"@class":"io.jsonwebtoken.CustomObjectDeserializationTest$SimpleAuthority"')

Jwt<Header, Claims> jwt = Jwts.parser()
.unsecured()
.json(new JacksonDeserializer(objectMapper, [authority: Authority]))
.build()
.parseUnsecuredClaims(jwtString)
assertEquals authority, jwt.payload.get('authority')
}

interface Authority {
String getAuthority()
}

@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS)
static abstract class AuthorityMixin {
}

static class SimpleAuthority implements Authority {
private String authority

SimpleAuthority() {
}

SimpleAuthority(String authority) {
this.authority = authority
}

String getAuthority() {
return authority
}

void setAuthority(String authority) {
this.authority = authority
}

boolean equals(o) {
return o instanceof SimpleAuthority && authority == o.authority
}

int hashCode() {
return authority?.hashCode() ?: 0
}
}

static class CustomBean {
private String key1
private Integer key2
Expand Down
Loading