Added expectSubject convenience method.

This commit is contained in:
Micah Silverman 2015-09-12 03:40:20 -04:00
parent fd04a357cb
commit f3c8f10f32
3 changed files with 78 additions and 0 deletions

View File

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

View File

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

View File

@ -1046,4 +1046,67 @@ class JwtParserTest {
} }
} }
@Test
void testParseExpectSubject_Success() {
def subject = 'A Most Awesome Subject'
byte[] key = randomKey()
String compact = Jwts.builder().signWith(SignatureAlgorithm.HS256, key).
setSubject(subject).
compact()
Jwt<Header,Claims> jwt = Jwts.parser().setSigningKey(key).
expectSubject(subject).
parseClaimsJws(compact)
assertEquals jwt.getBody().getSubject(), subject
}
@Test
void testParseExpectSubject_Incorrect_Fail() {
def goodSubject = 'A Most Awesome Subject'
def badSubject = 'A Most Bogus Subject'
byte[] key = randomKey()
String compact = Jwts.builder().signWith(SignatureAlgorithm.HS256, key).
setSubject(badSubject).
compact()
try {
Jwts.parser().setSigningKey(key).
expectSubject(goodSubject).
parseClaimsJws(compact)
fail()
} catch(IncorrectClaimException e) {
assertEquals(
String.format(INCORRECT_EXPECTED_CLAIM_MESSAGE_TEMPLATE, Claims.SUBJECT, goodSubject, badSubject),
e.getMessage()
)
}
}
@Test
void testParseExpectSubject_Missing_Fail() {
def subject = 'A Most Awesome Subject'
byte[] key = randomKey()
String compact = Jwts.builder().signWith(SignatureAlgorithm.HS256, key).
setId('id').
compact()
try {
Jwts.parser().setSigningKey(key).
expectSubject(subject).
parseClaimsJws(compact)
fail()
} catch(MissingClaimException e) {
assertEquals(
String.format(MISSING_EXPECTED_CLAIM_MESSAGE_TEMPLATE, Claims.SUBJECT, subject),
e.getMessage()
)
}
}
} }