mirror of https://github.com/jwtk/jjwt.git
Added expectAudience convenience method.
This commit is contained in:
parent
056dc819e2
commit
fd04a357cb
|
@ -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.
|
||||
*
|
||||
|
|
|
@ -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) {
|
||||
|
|
|
@ -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()
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue