Added expectIssuer convenience method.

This commit is contained in:
Micah Silverman 2015-09-12 03:08:03 -04:00
parent 0fab5504cd
commit 056dc819e2
3 changed files with 85 additions and 2 deletions

View File

@ -27,6 +27,14 @@ public interface JwtParser {
public static final char SEPARATOR_CHAR = '.';
/**
* Sets an expected value for the issuer claim.
*
* @param issuer
* @return the parser for method chaining.
*/
JwtParser expectIssuer(String issuer);
/**
* Sets an expected value for the issuedAt claim.
*

View File

@ -73,6 +73,13 @@ public class DefaultJwtParser implements JwtParser {
return this;
}
@Override
public JwtParser expectIssuer(String issuer) {
expect(Claims.ISSUER, issuer);
return this;
}
@Override
public JwtParser expect(String claimName, Object value) {
if (claimName != null && claimName.length() > 0 && value != null) {
@ -337,8 +344,12 @@ public class DefaultJwtParser implements JwtParser {
private void validateExpectedClaims(Header header, Claims claims) {
for (String expectedClaimName : expectedClaims.keySet()) {
Object expectedClaimValue = null;
Object actualClaimValue = null;
Object expectedClaimValue;
Object actualClaimValue;
// since issued at is a date, call the specific method
// other methods deal with strings and the more
// general method can be used
if (Claims.ISSUED_AT.equals(expectedClaimName)) {
expectedClaimValue = expectedClaims.getIssuedAt();
actualClaimValue = claims.getIssuedAt();

View File

@ -917,4 +917,68 @@ class JwtParserTest {
)
}
}
@Test
void testParseExpectIssuer_Success() {
def issuer = 'A Most Awesome Issuer'
byte[] key = randomKey()
String compact = Jwts.builder().signWith(SignatureAlgorithm.HS256, key).
setIssuer(issuer).
compact()
Jwt<Header,Claims> jwt = Jwts.parser().setSigningKey(key).
expectIssuer(issuer).
parseClaimsJws(compact)
assertEquals jwt.getBody().getIssuer(), issuer
}
@Test
void testParseExpectIssuer_Incorrect_Fail() {
def goodIssuer = 'A Most Awesome Issuer'
def badIssuer = 'A Most Bogus Issuer'
byte[] key = randomKey()
String compact = Jwts.builder().signWith(SignatureAlgorithm.HS256, key).
setIssuer(badIssuer).
compact()
try {
Jwts.parser().setSigningKey(key).
expectIssuer(goodIssuer).
parseClaimsJws(compact)
fail()
} catch(IncorrectClaimException e) {
assertEquals(
String.format(INCORRECT_EXPECTED_CLAIM_MESSAGE_TEMPLATE, Claims.ISSUER, goodIssuer, badIssuer),
e.getMessage()
)
}
}
@Test
void testParseExpectIssuer_Missing_Fail() {
def issuer = 'A Most Awesome Issuer'
byte[] key = randomKey()
String compact = Jwts.builder().signWith(SignatureAlgorithm.HS256, key).
setId('id').
compact()
try {
Jwts.parser().setSigningKey(key).
expectIssuer(issuer).
parseClaimsJws(compact)
fail()
} catch(MissingClaimException e) {
assertEquals(
String.format(MISSING_EXPECTED_CLAIM_MESSAGE_TEMPLATE, Claims.ISSUER, issuer),
e.getMessage()
)
}
}
}