diff --git a/src/main/java/io/jsonwebtoken/JwtParser.java b/src/main/java/io/jsonwebtoken/JwtParser.java index c74ec9e6..3e0cff47 100644 --- a/src/main/java/io/jsonwebtoken/JwtParser.java +++ b/src/main/java/io/jsonwebtoken/JwtParser.java @@ -27,6 +27,14 @@ public interface JwtParser { public static final char SEPARATOR_CHAR = '.'; + /** + * Sets an expected value for the jti claim. + * + * @param id + * @return the parser for method chaining. + */ + JwtParser expectId(String id); + /** * Sets an expected value for the subject claim. * diff --git a/src/main/java/io/jsonwebtoken/impl/DefaultJwtParser.java b/src/main/java/io/jsonwebtoken/impl/DefaultJwtParser.java index a251ca8e..30588e1f 100644 --- a/src/main/java/io/jsonwebtoken/impl/DefaultJwtParser.java +++ b/src/main/java/io/jsonwebtoken/impl/DefaultJwtParser.java @@ -94,6 +94,13 @@ public class DefaultJwtParser implements JwtParser { return this; } + @Override + public JwtParser expectId(String id) { + expect(Claims.ID, id); + + return this; + } + @Override public JwtParser expect(String claimName, Object value) { if (claimName != null && claimName.length() > 0 && value != null) { diff --git a/src/test/groovy/io/jsonwebtoken/JwtParserTest.groovy b/src/test/groovy/io/jsonwebtoken/JwtParserTest.groovy index c6116842..a5b74580 100644 --- a/src/test/groovy/io/jsonwebtoken/JwtParserTest.groovy +++ b/src/test/groovy/io/jsonwebtoken/JwtParserTest.groovy @@ -1109,4 +1109,68 @@ class JwtParserTest { ) } } + + @Test + void testParseExpectId_Success() { + def id = 'A Most Awesome id' + + byte[] key = randomKey() + + String compact = Jwts.builder().signWith(SignatureAlgorithm.HS256, key). + setId(id). + compact() + + Jwt jwt = Jwts.parser().setSigningKey(key). + expectId(id). + parseClaimsJws(compact) + + assertEquals jwt.getBody().getId(), id + } + + @Test + void testParseExpectId_Incorrect_Fail() { + def goodId = 'A Most Awesome Id' + def badId = 'A Most Bogus Id' + + byte[] key = randomKey() + + String compact = Jwts.builder().signWith(SignatureAlgorithm.HS256, key). + setId(badId). + compact() + + try { + Jwts.parser().setSigningKey(key). + expectId(goodId). + parseClaimsJws(compact) + fail() + } catch(IncorrectClaimException e) { + assertEquals( + String.format(INCORRECT_EXPECTED_CLAIM_MESSAGE_TEMPLATE, Claims.ID, goodId, badId), + e.getMessage() + ) + } + } + + @Test + void testParseExpectId_Missing_Fail() { + def id = 'A Most Awesome Id' + + byte[] key = randomKey() + + String compact = Jwts.builder().signWith(SignatureAlgorithm.HS256, key). + setIssuer('me'). + compact() + + try { + Jwts.parser().setSigningKey(key). + expectId(id). + parseClaimsJws(compact) + fail() + } catch(MissingClaimException e) { + assertEquals( + String.format(MISSING_EXPECTED_CLAIM_MESSAGE_TEMPLATE, Claims.ID, id), + e.getMessage() + ) + } + } }