Skip to content

Commit

Permalink
Added expectAudience convenience method.
Browse files Browse the repository at this point in the history
  • Loading branch information
dogeared committed Sep 12, 2015
1 parent 056dc81 commit fd04a35
Show file tree
Hide file tree
Showing 3 changed files with 80 additions and 0 deletions.
8 changes: 8 additions & 0 deletions src/main/java/io/jsonwebtoken/JwtParser.java
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*
Expand Down
7 changes: 7 additions & 0 deletions src/main/java/io/jsonwebtoken/impl/DefaultJwtParser.java
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,13 @@ public JwtParser expectIssuer(String issuer) {
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) {
Expand Down
65 changes: 65 additions & 0 deletions src/test/groovy/io/jsonwebtoken/JwtParserTest.groovy
Original file line number Diff line number Diff line change
Expand Up @@ -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()
)
}
}

}

0 comments on commit fd04a35

Please sign in to comment.