Skip to content

Commit

Permalink
allow to require a custom class Claim
Browse files Browse the repository at this point in the history
  • Loading branch information
lbalmaceda committed Dec 14, 2016
1 parent bde493b commit 3842dc5
Show file tree
Hide file tree
Showing 5 changed files with 49 additions and 26 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -293,7 +293,7 @@ The Claim class is a wrapper for the Claim values. It allows you to get the Clai
#### Custom Class and Collections
To obtain a Claim as a Collection you'll need to provide the **Class Type** of the contents to convert from.

* **as(class)**: Returns the value parsed as **Class Type**.
* **as(class)**: Returns the value parsed as **Class Type**. For collections you should use the `asArray` and `asList` methods.
* **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.
* **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.

Expand Down
13 changes: 5 additions & 8 deletions lib/src/main/java/com/auth0/jwt/JWTVerifier.java
Original file line number Diff line number Diff line change
Expand Up @@ -168,20 +168,15 @@ public Verification withJWTId(String jwtId) {
/**
* Require a specific Claim value.
*
* @param name the Claim's name
* @param value the Claim's value. Must be an instance of Integer, Double, Boolean, Date or String class.
* @param name the Claim's name.
* @param value the Claim's value.
* @return this same Verification instance.
* @throws IllegalArgumentException if the name is null or the value class is not allowed.
* @throws IllegalArgumentException if the name is null.
*/
public Verification withClaim(String name, Object value) throws IllegalArgumentException {
final boolean validValue = value instanceof Integer || value instanceof Double ||
value instanceof Boolean || value instanceof Date || value instanceof String;
if (name == null) {
throw new IllegalArgumentException("The Custom Claim's name can't be null.");
}
if (!validValue) {
throw new IllegalArgumentException("The Custom Claim's value class must be an instance of Integer, Double, Boolean, Date or String.");
}

requireClaim(name, value);
return this;
Expand Down Expand Up @@ -301,6 +296,8 @@ private void assertValidClaim(Claim claim, String claimName, Object value) {
isValid = value.equals(claim.asDouble());
} else if (value instanceof Date) {
isValid = value.equals(claim.asDate());
} else {
isValid = Objects.deepEquals(value, claim.as(value.getClass()));
}

if (!isValid) {
Expand Down
5 changes: 3 additions & 2 deletions lib/src/main/java/com/auth0/jwt/impl/JsonNodeClaim.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Date;
Expand Down Expand Up @@ -93,8 +94,8 @@ public <T> List<T> asList(Class<T> tClazz) throws JWTDecodeException {
public <T> T as(Class<T> tClazz) throws JWTDecodeException {
ObjectMapper mapper = new ObjectMapper();
try {
return mapper.treeToValue(data, tClazz);
} catch (JsonProcessingException e) {
return mapper.treeAsTokens(data).readValueAs(tClazz);
} catch (IOException e) {
throw new JWTDecodeException("Couldn't map the Claim value to " + tClazz.getSimpleName(), e);
}
}
Expand Down
44 changes: 33 additions & 11 deletions lib/src/test/java/com/auth0/jwt/JWTVerifierTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,7 @@
import org.junit.Test;
import org.junit.rules.ExpectedException;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.*;

import static org.hamcrest.Matchers.*;
import static org.junit.Assert.assertThat;
Expand Down Expand Up @@ -132,14 +130,6 @@ public void shouldThrowOnNullCustomClaimName() throws Exception {
.withClaim(null, "value");
}

@Test
public void shouldThrowOnIllegalCustomClaimValueClass() throws Exception {
exception.expect(IllegalArgumentException.class);
exception.expectMessage("The Custom Claim's value class must be an instance of Integer, Double, Boolean, Date or String.");
JWTVerifier.init(Algorithm.HMAC256("secret"))
.withClaim("name", new Object());
}

@Test
public void shouldThrowOnInvalidCustomClaimValueOfTypeString() throws Exception {
exception.expect(InvalidClaimException.class);
Expand Down Expand Up @@ -263,6 +253,38 @@ public void shouldValidateCustomClaimOfTypeDate() throws Exception {
assertThat(jwt, is(notNullValue()));
}

@Test
public void shouldValidateCustomClaimOfCustomType() throws Exception {
String token = "eyJhbGciOiJIUzI1NiJ9.eyJ1c2VyIjp7Im5hbWUiOiJqb2huIiwiaWQiOjEyM319.j3e7IfnEchQEwgDs1icOyufhzAyNOYfX9fjJwV6uyZk";
DecodedJWT jwt = JWTVerifier.init(Algorithm.HMAC256("secret"))
.withClaim("user", new UserPojo("john", 123))
.build()
.verify(token);

assertThat(jwt, is(notNullValue()));
}

@Test
public void shouldValidateCustomClaimOfTypeArray() throws Exception {
String token = "eyJhbGciOiJIUzI1NiJ9.eyJuYW1lIjpbInRleHQiLDEyMyx0cnVlXX0.uSulPFzLSbgfG8Lpr0jq0JDMhDlGGeQrx09PHEymu1E";
DecodedJWT jwt = JWTVerifier.init(Algorithm.HMAC256("secret"))
.withClaim("name", new Object[]{"text", 123, true})
.build()
.verify(token);

assertThat(jwt, is(notNullValue()));
}

@Test
public void shouldValidateCustomClaimOfTypeList() throws Exception {
String token = "eyJhbGciOiJIUzI1NiJ9.eyJuYW1lIjpbInRleHQiLDEyMyx0cnVlXX0.uSulPFzLSbgfG8Lpr0jq0JDMhDlGGeQrx09PHEymu1E";
DecodedJWT jwt = JWTVerifier.init(Algorithm.HMAC256("secret"))
.withClaim("name", new ArrayList<>(Arrays.asList("text", 123, true)))
.build()
.verify(token);

assertThat(jwt, is(notNullValue()));
}

// Generic Delta
@SuppressWarnings("RedundantCast")
Expand Down
11 changes: 7 additions & 4 deletions lib/src/test/java/com/auth0/jwt/impl/JsonNodeClaimTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,10 @@
import org.junit.Test;
import org.junit.rules.ExpectedException;

import java.util.*;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.Map;

import static com.auth0.jwt.impl.JWTParser.getDefaultObjectMapper;
import static com.auth0.jwt.impl.JsonNodeClaim.claimFromNode;
Expand Down Expand Up @@ -230,9 +233,9 @@ public void shouldGetAsMapValue() throws Exception {
Claim claim = claimFromNode(value);

assertThat(claim, is(notNullValue()));
Map map = claim.as(Map.class);
assertThat(((HashMap<String, Object>) map.get("key")), IsMapContaining.hasEntry("name", "john"));
assertThat(((HashMap<String, Object>) map.get("key")), IsMapContaining.hasEntry("id", 123));
Map<String, Object> map = claim.as(Map.class);
assertThat(((Map<String, Object>) map.get("key")), IsMapContaining.hasEntry("name", "john"));
assertThat(((Map<String, Object>) map.get("key")), IsMapContaining.hasEntry("id", 123));
}

@Test
Expand Down

0 comments on commit 3842dc5

Please sign in to comment.