com.auth0.jwt.exceptions.JWTDecodeException Java Examples

The following examples show how to use com.auth0.jwt.exceptions.JWTDecodeException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: JsonNodeClaim.java    From java-jwt with MIT License 6 votes vote down vote up
@Override
public <T> List<T> asList(Class<T> tClazz) throws JWTDecodeException {
    if (!data.isArray()) {
        return null;
    }

    List<T> list = new ArrayList<>();
    for (int i = 0; i < data.size(); i++) {
        try {
            list.add(objectReader.treeToValue(data.get(i), tClazz));
        } catch (JsonProcessingException e) {
            throw new JWTDecodeException("Couldn't map the Claim's array contents to " + tClazz.getSimpleName(), e);
        }
    }
    return list;
}
 
Example #2
Source File: JsonNodeClaim.java    From java-jwt with MIT License 6 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public <T> T[] asArray(Class<T> tClazz) throws JWTDecodeException {
    if (!data.isArray()) {
        return null;
    }

    T[] arr = (T[]) Array.newInstance(tClazz, data.size());
    for (int i = 0; i < data.size(); i++) {
        try {
            arr[i] = objectReader.treeToValue(data.get(i), tClazz);
        } catch (JsonProcessingException e) {
            throw new JWTDecodeException("Couldn't map the Claim's array contents to " + tClazz.getSimpleName(), e);
        }
    }
    return arr;
}
 
Example #3
Source File: PayloadDeserializer.java    From java-jwt with MIT License 6 votes vote down vote up
List<String> getStringOrArray(Map<String, JsonNode> tree, String claimName) throws JWTDecodeException {
    JsonNode node = tree.get(claimName);
    if (node == null || node.isNull() || !(node.isArray() || node.isTextual())) {
        return null;
    }
    if (node.isTextual() && !node.asText().isEmpty()) {
        return Collections.singletonList(node.asText());
    }

    List<String> list = new ArrayList<>(node.size());
    for (int i = 0; i < node.size(); i++) {
        try {
            list.add(objectReader.treeToValue(node.get(i), String.class));
        } catch (JsonProcessingException e) {
            throw new JWTDecodeException("Couldn't map the Claim's array contents to String", e);
        }
    }
    return list;
}
 
Example #4
Source File: JsonNodeClaimTest.java    From java-jwt with MIT License 6 votes vote down vote up
@Test
public void shouldThrowIfAnExtraordinaryExceptionHappensWhenParsingAsGenericMap() throws Exception {
    JsonNode value = mock(ObjectNode.class);
    when(value.getNodeType()).thenReturn(JsonNodeType.OBJECT);

    ObjectReader mockedMapper = mock(ObjectReader.class);

    JsonNodeClaim claim = (JsonNodeClaim) JsonNodeClaim.claimFromNode(value, mockedMapper);
    JsonNodeClaim spiedClaim = spy(claim);
    
    JsonParser mockedParser = mock(JsonParser.class);
    when(mockedMapper.treeAsTokens(value)).thenReturn(mockedParser);
    when(mockedParser.readValueAs(ArgumentMatchers.any(TypeReference.class))).thenThrow(IOException.class);

    exception.expect(JWTDecodeException.class);
    spiedClaim.asMap();
}
 
Example #5
Source File: LineAPIService.java    From line-login-starter with Apache License 2.0 6 votes vote down vote up
public IdToken idToken(String id_token) {
    try {
        DecodedJWT jwt = JWT.decode(id_token);
        return new IdToken(
                jwt.getClaim("iss").asString(),
                jwt.getClaim("sub").asString(),
                jwt.getClaim("aud").asString(),
                jwt.getClaim("ext").asLong(),
                jwt.getClaim("iat").asLong(),
                jwt.getClaim("nonce").asString(),
                jwt.getClaim("name").asString(),
                jwt.getClaim("picture").asString());
    } catch (JWTDecodeException e) {
        throw new RuntimeException(e);
    }
}
 
Example #6
Source File: JsonNodeClaimTest.java    From java-jwt with MIT License 5 votes vote down vote up
@Test
public void shouldThrowIfCustomClassMismatch() throws Exception {
    JsonNode value = mapper.valueToTree(new UserPojo("john", 123));
    Claim claim = claimFromNode(value);

    exception.expect(JWTDecodeException.class);
    claim.as(String.class);
}
 
Example #7
Source File: JWTParserTest.java    From java-jwt with MIT License 5 votes vote down vote up
@Test
public void shouldThrowOnInvalidPayload() throws Exception {
    String jsonPayload = "{{";
    exception.expect(JWTDecodeException.class);
    exception.expectMessage(String.format("The string '%s' doesn't have a valid JSON format.", jsonPayload));
    Payload payload = parser.parsePayload(jsonPayload);
    assertThat(payload, is(nullValue()));
}
 
Example #8
Source File: JWTParserTest.java    From java-jwt with MIT License 5 votes vote down vote up
@Test
public void shouldThrowOnInvalidHeader() throws Exception {
    String jsonHeader = "}}";
    exception.expect(JWTDecodeException.class);
    exception.expectMessage(String.format("The string '%s' doesn't have a valid JSON format.", jsonHeader));
    Header header = parser.parseHeader(jsonHeader);
    assertThat(header, is(nullValue()));
}
 
Example #9
Source File: HeaderDeserializerTest.java    From java-jwt with MIT License 5 votes vote down vote up
@Test
public void shouldThrowOnNullTree() throws Exception {
    exception.expect(JWTDecodeException.class);
    exception.expectMessage("Parsing the Header's JSON resulted on a Null map");

    JsonDeserializer deserializer = new HeaderDeserializer(objectReader);
    JsonParser parser = mock(JsonParser.class);
    ObjectCodec codec = mock(ObjectCodec.class);
    DeserializationContext context = mock(DeserializationContext.class);

    when(codec.readValue(eq(parser), any(TypeReference.class))).thenReturn(null);
    when(parser.getCodec()).thenReturn(codec);

    deserializer.deserialize(parser, context);
}
 
Example #10
Source File: JsonNodeClaimTest.java    From java-jwt with MIT License 5 votes vote down vote up
@Test
public void shouldThrowIfArrayClassMismatch() throws Exception {
    JsonNode value = mapper.valueToTree(new String[]{"keys", "values"});
    Claim claim = claimFromNode(value);

    exception.expect(JWTDecodeException.class);
    claim.asArray(UserPojo.class);
}
 
Example #11
Source File: JsonNodeClaimTest.java    From java-jwt with MIT License 5 votes vote down vote up
@Test
public void shouldThrowIfListClassMismatch() throws Exception {
    JsonNode value = mapper.valueToTree(new String[]{"keys", "values"});
    Claim claim = claimFromNode(value);

    exception.expect(JWTDecodeException.class);
    claim.asList(UserPojo.class);
}
 
Example #12
Source File: SignatureVerifier.java    From auth0-java with MIT License 5 votes vote down vote up
private DecodedJWT decodeToken(String token) throws IdTokenValidationException {
    try {
        return JWT.decode(token);
    } catch (JWTDecodeException e) {
        throw new IdTokenValidationException("ID token could not be decoded", e);
    }
}
 
Example #13
Source File: PayloadDeserializerTest.java    From java-jwt with MIT License 5 votes vote down vote up
@Test
public void shouldThrowWhenParsingArrayWithObjectValue() throws Exception {
    exception.expect(JWTDecodeException.class);
    exception.expectMessage("Couldn't map the Claim's array contents to String");

    ObjectMapper mapper = new ObjectMapper();
    JsonNode jsonNode = mapper.readTree("{\"some\" : \"random\", \"properties\" : \"inside\"}");
    Map<String, JsonNode> tree = new HashMap<>();
    List<JsonNode> subNodes = new ArrayList<>();
    subNodes.add(jsonNode);
    ArrayNode arrNode = new ArrayNode(JsonNodeFactory.instance, subNodes);
    tree.put("key", arrNode);

    deserializer.getStringOrArray(tree, "key");
}
 
Example #14
Source File: JwtUtil.java    From flash-waimai with MIT License 5 votes vote down vote up
public static Long getUserId(String token) {
    try {
        DecodedJWT jwt = JWT.decode(token);
        return jwt.getClaim("userId").asLong();
    } catch (JWTDecodeException e) {
        return null;
    }
}
 
Example #15
Source File: JwtUtil.java    From teaching with Apache License 2.0 5 votes vote down vote up
/**
 * 获得token中的信息无需secret解密也能获得
 *
 * @return token中包含的用户名
 */
public static String getUsername(String token) {
	try {
		DecodedJWT jwt = JWT.decode(token);
		return jwt.getClaim("username").asString();
	} catch (JWTDecodeException e) {
		return null;
	}
}
 
Example #16
Source File: JwtUtil.java    From SpringBoot-Home with Apache License 2.0 5 votes vote down vote up
/**
 * 根据token获取userId
 * @param token
 * @return
 */
public static String getUserId(String token) {
    try {
        String userId = JWT.decode(token).getAudience().get(0);
        return userId;
    } catch (JWTDecodeException e) {
        return null;
    }
}
 
Example #17
Source File: JwtUtil.java    From flash-waimai with MIT License 5 votes vote down vote up
/**
 * 获得token中的信息无需secret解密也能获得
 * @return token中包含的用户名
 */
public static String getUsername(String token) {
    try {
        DecodedJWT jwt = JWT.decode(token);
        return jwt.getClaim("username").asString();
    } catch (JWTDecodeException e) {
        return null;
    }
}
 
Example #18
Source File: PayloadDeserializerTest.java    From java-jwt with MIT License 5 votes vote down vote up
@Test
public void shouldThrowWhenParsingNonNumericNode() throws Exception {
    exception.expect(JWTDecodeException.class);
    exception.expectMessage("The claim 'key' contained a non-numeric date value.");

    Map<String, JsonNode> tree = new HashMap<>();
    TextNode node = new TextNode("123456789");
    tree.put("key", node);

    deserializer.getDateFromSeconds(tree, "key");
}
 
Example #19
Source File: SignatureVerifier.java    From auth0-java-mvc-common with MIT License 5 votes vote down vote up
private DecodedJWT decodeToken(String token) throws TokenValidationException {
    try {
        return JWT.decode(token);
    } catch (JWTDecodeException e) {
        throw new TokenValidationException("ID token could not be decoded", e);
    }
}
 
Example #20
Source File: PayloadDeserializerTest.java    From java-jwt with MIT License 5 votes vote down vote up
@Test
public void shouldThrowOnNullTree() throws Exception {
    exception.expect(JWTDecodeException.class);
    exception.expectMessage("Parsing the Payload's JSON resulted on a Null map");

    JsonParser parser = mock(JsonParser.class);
    ObjectCodec codec = mock(ObjectCodec.class);
    DeserializationContext context = mock(DeserializationContext.class);

    when(codec.readValue(eq(parser), any(TypeReference.class))).thenReturn(null);
    when(parser.getCodec()).thenReturn(codec);

    deserializer.deserialize(parser, context);
}
 
Example #21
Source File: TokenUtilsTest.java    From java-jwt with MIT License 5 votes vote down vote up
@Test
public void shouldThrowOnSplitTokenWithLessThan3Parts() throws Exception {
    exception.expect(JWTDecodeException.class);
    exception.expectMessage("The token was expected to have 3 parts, but got 2.");
    String token = "two.parts";
    TokenUtils.splitToken(token);
}
 
Example #22
Source File: JWTParser.java    From java-jwt with MIT License 5 votes vote down vote up
@Override
public Payload parsePayload(String json) throws JWTDecodeException {
    if (json == null) {
        throw decodeException();
    }

    try {
        return payloadReader.readValue(json);
    } catch (IOException e) {
        throw decodeException(json);
    }
}
 
Example #23
Source File: JWTParser.java    From java-jwt with MIT License 5 votes vote down vote up
@Override
public Header parseHeader(String json) throws JWTDecodeException {
    if (json == null) {
        throw decodeException();
    }

    try {
        return headerReader.readValue(json);
    } catch (IOException e) {
        throw decodeException(json);
    }
}
 
Example #24
Source File: TokenUtilsTest.java    From java-jwt with MIT License 5 votes vote down vote up
@Test
public void shouldThrowOnSplitTokenWithMoreThan3Parts() throws Exception {
    exception.expect(JWTDecodeException.class);
    exception.expectMessage("The token was expected to have 3 parts, but got 4.");
    String token = "this.has.four.parts";
    TokenUtils.splitToken(token);
}
 
Example #25
Source File: TokenUtils.java    From java-jwt with MIT License 5 votes vote down vote up
/**
 * Splits the given token on the "." chars into a String array with 3 parts.
 *
 * @param token the string to split.
 * @return the array representing the 3 parts of the token.
 * @throws JWTDecodeException if the Token doesn't have 3 parts.
 */
static String[] splitToken(String token) throws JWTDecodeException {
    String[] parts = token.split("\\.");
    if (parts.length == 2 && token.endsWith(".")) {
        //Tokens with alg='none' have empty String as Signature.
        parts = new String[]{parts[0], parts[1], ""};
    }
    if (parts.length != 3) {
        throw new JWTDecodeException(String.format("The token was expected to have 3 parts, but got %s.", parts.length));
    }
    return parts;
}
 
Example #26
Source File: HeaderDeserializer.java    From java-jwt with MIT License 5 votes vote down vote up
@Override
public BasicHeader deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
    Map<String, JsonNode> tree = p.getCodec().readValue(p, new TypeReference<Map<String, JsonNode>>() {
    });
    if (tree == null) {
        throw new JWTDecodeException("Parsing the Header's JSON resulted on a Null map");
    }

    String algorithm = getString(tree, PublicClaims.ALGORITHM);
    String type = getString(tree, PublicClaims.TYPE);
    String contentType = getString(tree, PublicClaims.CONTENT_TYPE);
    String keyId = getString(tree, PublicClaims.KEY_ID);
    return new BasicHeader(algorithm, type, contentType, keyId, tree, objectReader);
}
 
Example #27
Source File: PayloadDeserializer.java    From java-jwt with MIT License 5 votes vote down vote up
@Override
public Payload deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
    Map<String, JsonNode> tree = p.getCodec().readValue(p, new TypeReference<Map<String, JsonNode>>() {
    });
    if (tree == null) {
        throw new JWTDecodeException("Parsing the Payload's JSON resulted on a Null map");
    }

    String issuer = getString(tree, PublicClaims.ISSUER);
    String subject = getString(tree, PublicClaims.SUBJECT);
    List<String> audience = getStringOrArray(tree, PublicClaims.AUDIENCE);
    Date expiresAt = getDateFromSeconds(tree, PublicClaims.EXPIRES_AT);
    Date notBefore = getDateFromSeconds(tree, PublicClaims.NOT_BEFORE);
    Date issuedAt = getDateFromSeconds(tree, PublicClaims.ISSUED_AT);
    String jwtId = getString(tree, PublicClaims.JWT_ID);

    return new PayloadImpl(issuer, subject, audience, expiresAt, notBefore, issuedAt, jwtId, tree, objectReader);
}
 
Example #28
Source File: PayloadDeserializer.java    From java-jwt with MIT License 5 votes vote down vote up
Date getDateFromSeconds(Map<String, JsonNode> tree, String claimName) {
    JsonNode node = tree.get(claimName);
    if (node == null || node.isNull()) {
        return null;
    }
    if (!node.canConvertToLong()) {
        throw new JWTDecodeException(String.format("The claim '%s' contained a non-numeric date value.", claimName));
    }
    final long ms = node.asLong() * 1000;
    return new Date(ms);
}
 
Example #29
Source File: JsonNodeClaim.java    From java-jwt with MIT License 5 votes vote down vote up
@Override
public Map<String, Object> asMap() throws JWTDecodeException {
    if (!data.isObject()) {
        return null;
    }

    try {
        TypeReference<Map<String, Object>> mapType = new TypeReference<Map<String, Object>>() {
        };
        JsonParser thisParser = objectReader.treeAsTokens(data);
        return thisParser.readValueAs(mapType);
    } catch (IOException e) {
        throw new JWTDecodeException("Couldn't map the Claim value to Map", e);
    }
}
 
Example #30
Source File: JsonNodeClaim.java    From java-jwt with MIT License 5 votes vote down vote up
@Override
public <T> T as(Class<T> tClazz) throws JWTDecodeException {
    try {
        return objectReader.treeAsTokens(data).readValueAs(tClazz);
    } catch (IOException e) {
        throw new JWTDecodeException("Couldn't map the Claim value to " + tClazz.getSimpleName(), e);
    }
}