jwtk/jjwt

Cannot parse JWT by new version of jjwt library

b3lowster opened this issue · 2 comments

I've updated jjwt to version 0.12.3. I use a keystore PKCS12 to sign jwt and validate it. But now I'm getting errror: JWS verification key must be either a SecretKey (for MAC algorithms) or a PublicKey (for Signature algorithms). Everything works fine on the version 0.9.1

private static Key getKey() throws Exception {
        KeyStore keystore = KeyStore.getInstance("PKCS12");
        keystore.load(GenerateValidateKey.class.getResourceAsStream("/test.p12"), "test".toCharArray());
        Enumeration aliases = keystore.aliases();
        String keyAlias = "";
        while (aliases.hasMoreElements()) {
            keyAlias = (String) aliases.nextElement();
        }
        return keystore.getKey(keyAlias, "test".toCharArray());
    }
Map<String, Object> claims = new HashMap<>();
            claims.put("aud", "test");
            claims.put("sub", "test");

String token = Jwts.builder().signWith(SignatureAlgorithm.RS256, getKey())
                    .setSubject("test")
                    .setExpiration(Date.from(expiration.atStartOfDay(ZoneId.systemDefault()).toInstant()))
                    .setIssuedAt(Date.from(now.atStartOfDay(ZoneId.systemDefault()).toInstant()))
                    .setClaims(claims)
                    .compact();
Claims claims = Jwts.parser()
                                .setSigningKey(getKey())
                                .requireAudience("test")
                                .build()
                                .parseClaimsJws(token)
                                .getBody()

@b3lowster use Jwts.parser().verifyWith instead. Also, a generic Key instance cannot be used to sign or verify RS256 signatures. A PrivateKey instance is required to sign, and a PublicKey instance is required to verify.

Closing due to inactivity or follow up from OP. Also note that, while versions before 0.12.0 allowed using the private key to verify, this is non-standard in almost all cryptographic contexts, so that's why the API has changed. PrivateKeys are used to sign, and PublicKeys are used to verify.

In the above OP code, there should probably be two helper methods: PrivateKey getSigningKey() and PublicKey getVerificationKey() instead of just Key getKey(). HTH!