javajwtjose4j

Verifying JWS with detached payload using jose4j fails


I'm having issues verifying a JWS with detached payload. I've basically copied all steps in the example provided on the jose4j documentation but for some reason verification still returns false while it should succeed.

Here's the code I'm using, using latest version of jose4j.

// signature is the complete JWS in the form: "JOSE Header".."JWS Signature"
// payload is the unencoded JSON string that makes up the request body
public boolean verifySignature(String signature, String payload) {

        JsonWebSignature jws = new JsonWebSignature();
        jws.setKnownCriticalHeaders(critHeaders); //critical headers from documentation
        //Algorithm as provided in documentation
        jws.setAlgorithmConstraints(new AlgorithmConstraints(AlgorithmConstraints.ConstraintType.PERMIT, 
                                                            AlgorithmIdentifiers.ECDSA_USING_P256_CURVE_AND_SHA256));
        jws.setPayload(payload);
        try {
            jws.setCompactSerialization(signature);
            String keyId = jws.getKeyIdHeaderValue();
            String keyType = jws.getKeyType();
            String keyAlg = jws.getAlgorithmHeaderValue();
            //Retrieve key from cached jwks
            JsonWebKey usedKey = jwks.findJsonWebKey(keyId, keyType, "sig", keyAlg);
            jws.setKey(usedKey.getKey());
            return jws.verifySignature();
        } catch  (JoseException e) {
            //log
            return false;
        }       
    }

Solution

  • Brian Campbell looked into this over on the jose4j Bitbucket, and this is his solution

    adding a jws.setEncodedPayload(null); right after jws.setCompactSerialization(signature); will make it work.

    Apparently there is some inconsistency in my use case between the encoded/unencoded payload