Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add DefaultJwtParser functionality to parse JWSs with empty body. #540

Merged
merged 6 commits into from
Jun 8, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions api/src/main/java/io/jsonwebtoken/JwtParserBuilder.java
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,18 @@ public interface JwtParserBuilder {
*/
JwtParserBuilder require(String claimName, Object value);

/**
* Allow that the body / payload part of the JWT may be empty. Some API specifications require JWT authenticated
* POST-AS-GET requests with an empty octet string as body part.
* The default value is false. If a message contains an empty body without allowing it, parsing the JWS will lead
* to a {@link MalformedJwtException}.
*
* @param allowEmptyBody
* @return the parser builder for method chaining.
* @see MalformedJwtException
*/
JwtParserBuilder allowEmptyBody(boolean allowEmptyBody);
lhazlewood marked this conversation as resolved.
Show resolved Hide resolved

/**
* Sets the {@link Clock} that determines the timestamp to use when validating the parsed JWT.
* The parser uses a default Clock implementation that simply returns {@code new Date()} when called.
Expand Down
11 changes: 9 additions & 2 deletions impl/src/main/java/io/jsonwebtoken/impl/DefaultJwtParser.java
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,8 @@ public class DefaultJwtParser implements JwtParser {

private Claims expectedClaims = new DefaultClaims();

private boolean allowEmptyBody = false;
lhazlewood marked this conversation as resolved.
Show resolved Hide resolved

private Clock clock = DefaultClock.INSTANCE;

private long allowedClockSkewMillis = 0;
Expand All @@ -94,6 +96,7 @@ public DefaultJwtParser() { }
Clock clock,
long allowedClockSkewMillis,
Claims expectedClaims,
boolean allowEmptyBody,
Decoder<String, byte[]> base64UrlDecoder,
Deserializer<Map<String, ?>> deserializer,
CompressionCodecResolver compressionCodecResolver) {
Expand All @@ -103,6 +106,7 @@ public DefaultJwtParser() { }
this.clock = clock;
this.allowedClockSkewMillis = allowedClockSkewMillis;
this.expectedClaims = expectedClaims;
this.allowEmptyBody = allowEmptyBody;
this.base64UrlDecoder = base64UrlDecoder;
this.deserializer = deserializer;
this.compressionCodecResolver = compressionCodecResolver;
Expand Down Expand Up @@ -293,7 +297,7 @@ public Jwt parse(String jwt) throws ExpiredJwtException, MalformedJwtException,
base64UrlEncodedDigest = sb.toString();
}

if (base64UrlEncodedPayload == null) {
if (base64UrlEncodedPayload == null && !allowEmptyBody) {
throw new MalformedJwtException("JWT string '" + jwt + "' is missing a body/payload.");
}

Expand All @@ -317,6 +321,9 @@ public Jwt parse(String jwt) throws ExpiredJwtException, MalformedJwtException,
}

// =============== Body =================
if (base64UrlEncodedPayload == null) {
siebenfarben marked this conversation as resolved.
Show resolved Hide resolved
base64UrlEncodedPayload = ""; // If empty body is allowed, override the resulting null from parsing.
}
byte[] bytes = base64UrlDecoder.decode(base64UrlEncodedPayload);
if (compressionCodec != null) {
bytes = compressionCodec.decompress(bytes);
Expand All @@ -325,7 +332,7 @@ public Jwt parse(String jwt) throws ExpiredJwtException, MalformedJwtException,

Claims claims = null;

if (payload.charAt(0) == '{' && payload.charAt(payload.length() - 1) == '}') { //likely to be json, parse it:
if (!payload.isEmpty() && payload.charAt(0) == '{' && payload.charAt(payload.length() - 1) == '}') { //likely to be json, parse it:
Map<String, Object> claimsMap = (Map<String, Object>) readValue(payload);
claims = new DefaultClaims(claimsMap);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,8 @@ public class DefaultJwtParserBuilder implements JwtParserBuilder {

private Claims expectedClaims = new DefaultClaims();

private boolean allowEmptyBody = false;

private Clock clock = DefaultClock.INSTANCE;

private long allowedClockSkewMillis = 0;
Expand Down Expand Up @@ -122,6 +124,12 @@ public JwtParserBuilder require(String claimName, Object value) {
return this;
}

@Override
public JwtParserBuilder allowEmptyBody(boolean allowEmptyBody) {
this.allowEmptyBody = allowEmptyBody;
return this;
}

@Override
public JwtParserBuilder setClock(Clock clock) {
Assert.notNull(clock, "Clock instance cannot be null.");
Expand Down Expand Up @@ -187,6 +195,7 @@ public JwtParser build() {
clock,
allowedClockSkewMillis,
expectedClaims,
allowEmptyBody,
base64UrlDecoder,
deserializer,
compressionCodecResolver));
Expand Down
41 changes: 41 additions & 0 deletions impl/src/test/groovy/io/jsonwebtoken/JwtParserTest.groovy
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,47 @@ class JwtParserTest {
assertEquals jwt.body, payload
}

@Test
void testParseEmptyBodyWithAllowedEmptyBodyFalse() {

byte[] key = randomKey()
siebenfarben marked this conversation as resolved.
Show resolved Hide resolved

String base64Encodedkey = Encoders.BASE64.encode(key)

String payload = ''

//noinspection GrDeprecatedAPIUsage
siebenfarben marked this conversation as resolved.
Show resolved Hide resolved
String compact = Jwts.builder().setPayload(payload).signWith(SignatureAlgorithm.HS256, base64Encodedkey).compact()

assertTrue Jwts.parserBuilder().build().isSigned(compact)

try {
Jwts.parserBuilder().allowEmptyBody(false).setSigningKey(base64Encodedkey).build().parse(compact)
fail()
} catch (MalformedJwtException se) {
assertEquals se.getMessage(), "JWT string \'${compact}\' is missing a body/payload.".toString()
}
}

@Test
void testParseEmptyBodyWithAllowedEmptyBodyTrue() {

byte[] key = randomKey()

String base64Encodedkey = Encoders.BASE64.encode(key)

String payload = ''

//noinspection GrDeprecatedAPIUsage
String compact = Jwts.builder().setPayload(payload).signWith(SignatureAlgorithm.HS256, base64Encodedkey).compact()

assertTrue Jwts.parserBuilder().build().isSigned(compact)

Jwt<Header, String> jwt = Jwts.parserBuilder().allowEmptyBody(true).setSigningKey(base64Encodedkey).build().parse(compact)

assertEquals jwt.body, payload
}

@Test
void testParseWithExpiredJwt() {

Expand Down