Added expectAudience convenience method.

This commit is contained in:
Micah Silverman 2015-09-12 03:32:56 -04:00
parent 056dc819e2
commit fd04a357cb
3 changed files with 80 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 audience claim.
*
* @param audience
* @return the parser for method chaining.
*/
JwtParser expectAudience(String audience);
/**
* Sets an expected value for the issuer claim.
*

View File

@ -80,6 +80,13 @@ public class DefaultJwtParser implements JwtParser {
return this;
}
@Override
public JwtParser expectAudience(String audience) {
expect(Claims.AUDIENCE, audience);
return this;
}
@Override
public JwtParser expect(String claimName, Object value) {
if (claimName != null && claimName.length() > 0 && value != null) {

View File

@ -981,4 +981,69 @@ class JwtParserTest {
)
}
}
@Test
void testParseExpectAudience_Success() {
def audience = 'A Most Awesome Audience'
byte[] key = randomKey()
String compact = Jwts.builder().signWith(SignatureAlgorithm.HS256, key).
setAudience(audience).
compact()
Jwt<Header,Claims> jwt = Jwts.parser().setSigningKey(key).
expectAudience(audience).
parseClaimsJws(compact)
assertEquals jwt.getBody().getAudience(), audience
}
@Test
void testParseExpectAudience_Incorrect_Fail() {
def goodAudience = 'A Most Awesome Audience'
def badAudience = 'A Most Bogus Audience'
byte[] key = randomKey()
String compact = Jwts.builder().signWith(SignatureAlgorithm.HS256, key).
setAudience(badAudience).
compact()
try {
Jwts.parser().setSigningKey(key).
expectAudience(goodAudience).
parseClaimsJws(compact)
fail()
} catch(IncorrectClaimException e) {
assertEquals(
String.format(INCORRECT_EXPECTED_CLAIM_MESSAGE_TEMPLATE, Claims.AUDIENCE, goodAudience, badAudience),
e.getMessage()
)
}
}
@Test
void testParseExpectAudience_Missing_Fail() {
def audience = 'A Most Awesome audience'
byte[] key = randomKey()
String compact = Jwts.builder().signWith(SignatureAlgorithm.HS256, key).
setId('id').
compact()
try {
Jwts.parser().setSigningKey(key).
expectAudience(audience).
parseClaimsJws(compact)
fail()
} catch(MissingClaimException e) {
assertEquals(
String.format(MISSING_EXPECTED_CLAIM_MESSAGE_TEMPLATE, Claims.AUDIENCE, audience),
e.getMessage()
)
}
}
}