I'd like to extract body of a JWT as a JSON using Jose4j. Is this possible?
We need to support a custom validation that can be arbitrarily easy or very complex depending on the customer. We need the body in the form of a JSON, so that we can pass it as an argument for a customer-specific Javascript method.
Calling getRawJson()
on the JwtClaims
object obtained from JwtConsumer
will give you the JSON payload of the JWT, which sounds like what you're looking for.
The below snippet from https://bitbucket.org/b_c/jose4j/wiki/JWT%20Examples was modified slightly to show getRawJson()
being used.
// Use JwtConsumerBuilder to construct an appropriate JwtConsumer, which will
// be used to validate and process the JWT.
// The specific validation requirements for a JWT are context dependent, however,
// it typically advisable to require a (reasonable) expiration time, a trusted issuer, and
// and audience that identifies your system as the intended recipient.
// If the JWT is encrypted too, you need only provide a decryption key or
// decryption key resolver to the builder.
JwtConsumer jwtConsumer = new JwtConsumerBuilder()
.setRequireExpirationTime() // the JWT must have an expiration time
.setRequireSubject() // the JWT must have a subject claim
.setExpectedIssuer("Issuer") // whom the JWT needs to have been issued by
.setExpectedAudience("Audience") // to whom the JWT is intended for
.setVerificationKey(rsaJsonWebKey.getKey()) // verify the signature with the public key
.setJwsAlgorithmConstraints( // only allow the expected signature algorithm(s) in the given context
ConstraintType.PERMIT, AlgorithmIdentifiers.RSA_USING_SHA256) // which is only RS256 here
.build(); // create the JwtConsumer instance
try
{
// Validate the JWT and process it to the Claims
JwtClaims jwtClaims = jwtConsumer.processToClaims(jwt);
System.out.println("JWT validation succeeded! " + jwtClaims);
String jsonPayload = jwtClaims.getRawJson();
System.out.println("JWT's JSON payload: " + jsonPayload);
}
catch (InvalidJwtException e)
{
// InvalidJwtException will be thrown, if the JWT failed processing or validation in anyway.
// Hopefully with meaningful explanations(s) about what went wrong.
System.out.println("Invalid JWT! " + e);
}