Skip to content

Commit bf0a030

Browse files
authored
Merge pull request auth0#152 from auth0/add-claim-as-map
Allow to get a Claim as Map
2 parents 3193e62 + 0a0e83a commit bf0a030

File tree

8 files changed

+153
-1
lines changed

8 files changed

+153
-1
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -338,6 +338,7 @@ The Claim class is a wrapper for the Claim values. It allows you to get the Clai
338338
To obtain a Claim as a Collection you'll need to provide the **Class Type** of the contents to convert from.
339339

340340
* **as(class)**: Returns the value parsed as **Class Type**. For collections you should use the `asArray` and `asList` methods.
341+
* **asMap()**: Returns the value parsed as **Map<String, Object>**.
341342
* **asArray(class)**: Returns the value parsed as an Array of elements of type **Class Type**, or null if the value isn't a JSON Array.
342343
* **asList(class)**: Returns the value parsed as a List of elements of type **Class Type**, or null if the value isn't a JSON Array.
343344

lib/src/main/java/com/auth0/jwt/JWTDecoder.java

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33
import com.auth0.jwt.exceptions.JWTDecodeException;
44
import com.auth0.jwt.impl.JWTParser;
55
import com.auth0.jwt.interfaces.Claim;
6-
import com.auth0.jwt.interfaces.DecodedJWT;
76
import com.auth0.jwt.interfaces.Header;
87
import com.auth0.jwt.interfaces.Payload;
98
import org.apache.commons.codec.binary.Base64;

lib/src/main/java/com/auth0/jwt/impl/JsonNodeClaim.java

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import com.auth0.jwt.exceptions.JWTDecodeException;
44
import com.auth0.jwt.interfaces.Claim;
55
import com.fasterxml.jackson.core.JsonProcessingException;
6+
import com.fasterxml.jackson.core.type.TypeReference;
67
import com.fasterxml.jackson.databind.JsonNode;
78
import com.fasterxml.jackson.databind.ObjectMapper;
89

@@ -90,6 +91,22 @@ public <T> List<T> asList(Class<T> tClazz) throws JWTDecodeException {
9091
return list;
9192
}
9293

94+
@Override
95+
public Map<String, Object> asMap() throws JWTDecodeException {
96+
if (!data.isObject()) {
97+
return null;
98+
}
99+
100+
ObjectMapper mapper = new ObjectMapper();
101+
try {
102+
TypeReference<Map<String, Object>> mapType = new TypeReference<Map<String, Object>>() {
103+
};
104+
return mapper.treeAsTokens(data).readValueAs(mapType);
105+
} catch (IOException e) {
106+
throw new JWTDecodeException("Couldn't map the Claim value to Map", e);
107+
}
108+
}
109+
93110
@Override
94111
public <T> T as(Class<T> tClazz) throws JWTDecodeException {
95112
ObjectMapper mapper = new ObjectMapper();

lib/src/main/java/com/auth0/jwt/impl/NullClaim.java

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55

66
import java.util.Date;
77
import java.util.List;
8+
import java.util.Map;
89

910
/**
1011
* The {@link NullClaim} class is a Claim implementation that returns null when any of it's methods it's called.
@@ -50,6 +51,11 @@ public <T> List<T> asList(Class<T> tClazz) throws JWTDecodeException {
5051
return null;
5152
}
5253

54+
@Override
55+
public Map<String, Object> asMap() throws JWTDecodeException {
56+
return null;
57+
}
58+
5359
@Override
5460
public <T> T as(Class<T> tClazz) throws JWTDecodeException {
5561
return null;

lib/src/main/java/com/auth0/jwt/interfaces/Claim.java

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
import java.util.Date;
66
import java.util.List;
7+
import java.util.Map;
78

89
/**
910
* The Claim class holds the value in a generic way so that it can be recovered in many representations.
@@ -75,6 +76,14 @@ public interface Claim {
7576
*/
7677
<T> List<T> asList(Class<T> tClazz) throws JWTDecodeException;
7778

79+
/**
80+
* Get this Claim as a generic Map of values.
81+
*
82+
* @return the value as instance of Map.
83+
* @throws JWTDecodeException if the value can't be converted to a Map.
84+
*/
85+
Map<String, Object> asMap() throws JWTDecodeException;
86+
7887
/**
7988
* Get this Claim as a custom type T.
8089
*

lib/src/test/java/com/auth0/jwt/JWTDecoderTest.java

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
import org.apache.commons.codec.binary.Base64;
88
import org.hamcrest.collection.IsCollectionWithSize;
99
import org.hamcrest.core.IsCollectionContaining;
10+
import org.junit.Assert;
1011
import org.junit.Rule;
1112
import org.junit.Test;
1213
import org.junit.rules.ExpectedException;
@@ -199,6 +200,66 @@ public void shouldNotGetNullClaimIfClaimIsEmptyObject() throws Exception {
199200
assertThat(jwt.getClaim("object").isNull(), is(false));
200201
}
201202

203+
@Test
204+
public void shouldGetCustomClaimOfTypeInteger() throws Exception {
205+
String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoxMjN9.XZAudnA7h3_Al5kJydzLjw6RzZC3Q6OvnLEYlhNW7HA";
206+
DecodedJWT jwt = JWT.decode(token);
207+
Assert.assertThat(jwt, is(notNullValue()));
208+
Assert.assertThat(jwt.getClaim("name").asInt(), is(123));
209+
}
210+
211+
@Test
212+
public void shouldGetCustomClaimOfTypeDouble() throws Exception {
213+
String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoyMy40NX0.7pyX2OmEGaU9q15T8bGFqRm-d3RVTYnqmZNZtxMKSlA";
214+
DecodedJWT jwt = JWT.decode(token);
215+
Assert.assertThat(jwt, is(notNullValue()));
216+
Assert.assertThat(jwt.getClaim("name").asDouble(), is(23.45));
217+
}
218+
219+
@Test
220+
public void shouldGetCustomClaimOfTypeBoolean() throws Exception {
221+
String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjp0cnVlfQ.FwQ8VfsZNRqBa9PXMinSIQplfLU4-rkCLfIlTLg_MV0";
222+
DecodedJWT jwt = JWT.decode(token);
223+
Assert.assertThat(jwt, is(notNullValue()));
224+
Assert.assertThat(jwt.getClaim("name").asBoolean(), is(true));
225+
}
226+
227+
@Test
228+
public void shouldGetCustomClaimOfTypeDate() throws Exception {
229+
String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoxNDc4ODkxNTIxfQ.mhioumeok8fghQEhTKF3QtQAksSvZ_9wIhJmgZLhJ6c";
230+
Date date = new Date(1478891521000L);
231+
DecodedJWT jwt = JWT.decode(token);
232+
Assert.assertThat(jwt, is(notNullValue()));
233+
Assert.assertThat(jwt.getClaim("name").asDate().getTime(), is(date.getTime()));
234+
}
235+
236+
@Test
237+
public void shouldGetCustomArrayClaimOfTypeString() throws Exception {
238+
String token = "eyJhbGciOiJIUzI1NiJ9.eyJuYW1lIjpbInRleHQiLCIxMjMiLCJ0cnVlIl19.lxM8EcmK1uSZRAPd0HUhXGZJdauRmZmLjoeqz4J9yAA";
239+
DecodedJWT jwt = JWT.decode(token);
240+
Assert.assertThat(jwt, is(notNullValue()));
241+
Assert.assertThat(jwt.getClaim("name").asArray(String.class), arrayContaining("text", "123", "true"));
242+
}
243+
244+
@Test
245+
public void shouldGetCustomArrayClaimOfTypeInteger() throws Exception {
246+
String token = "eyJhbGciOiJIUzI1NiJ9.eyJuYW1lIjpbMSwyLDNdfQ.UEuMKRQYrzKAiPpPLhIVawWkKWA1zj0_GderrWUIyFE";
247+
DecodedJWT jwt = JWT.decode(token);
248+
Assert.assertThat(jwt, is(notNullValue()));
249+
Assert.assertThat(jwt.getClaim("name").asArray(Integer.class), arrayContaining(1, 2, 3));
250+
}
251+
252+
@Test
253+
public void shouldGetCustomMapClaim() throws Exception {
254+
String token = "eyJhbGciOiJIUzI1NiJ9.eyJuYW1lIjp7InN0cmluZyI6InZhbHVlIiwibnVtYmVyIjoxLCJib29sZWFuIjp0cnVlfX0.-8aIaXd2-rp1lLuDEQmCeisCBX9X_zbqdPn2llGxNoc";
255+
DecodedJWT jwt = JWT.decode(token);
256+
Assert.assertThat(jwt, is(notNullValue()));
257+
Map<String, Object> map = jwt.getClaim("name").asMap();
258+
Assert.assertThat(map, hasEntry("string", (Object) "value"));
259+
Assert.assertThat(map, hasEntry("number", (Object) 1));
260+
Assert.assertThat(map, hasEntry("boolean", (Object) true));
261+
}
262+
202263
@Test
203264
public void shouldGetAvailableClaims() throws Exception {
204265
DecodedJWT jwt = JWTDecoder.decode("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOiIxMjM0NTY3ODkwIiwiaWF0IjoiMTIzNDU2Nzg5MCIsIm5iZiI6IjEyMzQ1Njc4OTAiLCJqdGkiOiJodHRwczovL2p3dC5pby8iLCJhdWQiOiJodHRwczovL2RvbWFpbi5hdXRoMC5jb20iLCJzdWIiOiJsb2dpbiIsImlzcyI6ImF1dGgwIiwiZXh0cmFDbGFpbSI6IkpvaG4gRG9lIn0.TX9Ct4feGp9YyeGK9Zl91tO0YBOrguJ4As9jeqgHdZQ");

lib/src/test/java/com/auth0/jwt/impl/JsonNodeClaimTest.java

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,13 +5,17 @@
55
import com.auth0.jwt.interfaces.Claim;
66
import com.fasterxml.jackson.databind.JsonNode;
77
import com.fasterxml.jackson.databind.ObjectMapper;
8+
import com.fasterxml.jackson.databind.node.JsonNodeType;
89
import com.fasterxml.jackson.databind.node.MissingNode;
910
import com.fasterxml.jackson.databind.node.NullNode;
11+
import com.fasterxml.jackson.databind.node.ObjectNode;
12+
import org.hamcrest.collection.IsMapContaining;
1013
import org.junit.Before;
1114
import org.junit.Rule;
1215
import org.junit.Test;
1316
import org.junit.rules.ExpectedException;
1417

18+
import java.io.IOException;
1519
import java.util.*;
1620

1721
import static com.auth0.jwt.impl.JWTParser.getDefaultObjectMapper;
@@ -20,6 +24,8 @@
2024
import static org.hamcrest.core.IsNull.notNullValue;
2125
import static org.hamcrest.core.IsNull.nullValue;
2226
import static org.junit.Assert.assertThat;
27+
import static org.mockito.Mockito.mock;
28+
import static org.mockito.Mockito.when;
2329

2430
public class JsonNodeClaimTest {
2531

@@ -203,6 +209,54 @@ public void shouldThrowIfListClassMismatch() throws Exception {
203209
claim.asList(UserPojo.class);
204210
}
205211

212+
@Test
213+
public void shouldGetNullMapIfNullValue() throws Exception {
214+
JsonNode value = mapper.valueToTree(null);
215+
Claim claim = claimFromNode(value);
216+
217+
assertThat(claim.asMap(), is(nullValue()));
218+
}
219+
220+
@Test
221+
public void shouldGetNullMapIfNonArrayValue() throws Exception {
222+
JsonNode value = mapper.valueToTree(1);
223+
Claim claim = claimFromNode(value);
224+
225+
assertThat(claim.asMap(), is(nullValue()));
226+
}
227+
228+
@Test
229+
public void shouldGetMapValue() throws Exception {
230+
Map<String, Object> map = new HashMap<>();
231+
map.put("text", "extraValue");
232+
map.put("number", 12);
233+
map.put("boolean", true);
234+
map.put("object", Collections.singletonMap("something", "else"));
235+
236+
JsonNode value = mapper.valueToTree(map);
237+
Claim claim = claimFromNode(value);
238+
239+
assertThat(claim, is(notNullValue()));
240+
Map<String, Object> backMap = claim.asMap();
241+
assertThat(backMap, is(notNullValue()));
242+
assertThat(backMap, hasEntry("text", (Object) "extraValue"));
243+
assertThat(backMap, hasEntry("number", (Object) 12));
244+
assertThat(backMap, hasEntry("boolean", (Object) true));
245+
assertThat(backMap, hasKey("object"));
246+
assertThat((Map<String, Object>) backMap.get("object"), IsMapContaining.hasEntry("something", (Object) "else"));
247+
}
248+
249+
@Test
250+
public void shouldThrowIfAnExtraordinaryExceptionHappensWhenParsingAsGenericMap() throws Exception {
251+
JsonNode value = mock(ObjectNode.class);
252+
when(value.getNodeType()).thenReturn(JsonNodeType.OBJECT);
253+
when(value.fields()).thenThrow(IOException.class);
254+
Claim claim = claimFromNode(value);
255+
256+
exception.expect(JWTDecodeException.class);
257+
claim.asMap();
258+
}
259+
206260
@Test
207261
public void shouldGetCustomClassValue() throws Exception {
208262
JsonNode value = mapper.valueToTree(new UserPojo("john", 123));

lib/src/test/java/com/auth0/jwt/impl/NullClaimTest.java

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,11 @@ public void shouldGetAsList() throws Exception {
5656
assertThat(claim.asList(Object.class), is(nullValue()));
5757
}
5858

59+
@Test
60+
public void shouldGetAsMap() throws Exception {
61+
assertThat(claim.asMap(), is(nullValue()));
62+
}
63+
5964
@Test
6065
public void shouldGetAsCustomClass() throws Exception {
6166
assertThat(claim.as(Object.class), is(nullValue()));

0 commit comments

Comments
 (0)