Added expectId convenience method.

This commit is contained in:
Micah Silverman 2015-09-12 03:51:00 -04:00
parent f3c8f10f32
commit f2e620e36b
3 changed files with 79 additions and 0 deletions

View File

@ -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.
*

View File

@ -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) {

View File

@ -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<Header,Claims> 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()
)
}
}
}