How do I set the signingkey from a jwk to verify a jwt with jjwt

700 views Asked by At

To verify and parse the jwt token the code is

public static Claims decodeJWT(String jwt) {
    //This line will throw an exception if it is not a signed JWS (as expected)
    Claims claims = Jwts.parser()
        .setSigningKey(DatatypeConverter.parseBase64Binary(SECRET_KEY))
        .parseClaimsJws(jwt).getBody();
    return claims;
}

My jwk looks like

public class MyJwkDto {
    String kty;
    String crv;
    String kid;
    String x;
    String y;
}

as exaple

  {
    "kty": "EC",
    "crv": "P-256",
    "kid": "UD9Jr8TKPk3MI_RQg2LX3UFwaV4U3nhIzUO_pU78q4M",
    "x": "lKgBPjCtzRiYOC1Oyi_3qi6Ux7Wcxaem35nx9IgEqRY",
    "y": "fNghfAOzpsSudHo6tq1JB3FdKkdQnH_tLj2tajc8ZUM"
  }

But what do I use now for the SECRET_KEY?

1

There are 1 answers

0
Julian On

So what i did is:

First changed the lib from jjwt to nimbus-jose-jwt. After that I stored the jwks as .a JWKSet

public JWKSet getJwks(String token) {
    try {
        SignedJWT signedJWT = SignedJWT.parse(token);
        JWTClaimsSet payload = signedJWT.getJWTClaimsSet();
        return JWKSet.parse(payload.getJSONObjectClaim("jwks"));
    } catch (java.text.ParseException e) {
        throw new RuntimeException(e);
    }
}

After that the validation of a jwk worked as follows

public boolean verifyToken(String token, JWKSet jwkSet) {
    try {
        SignedJWT signedJWT = SignedJWT.parse(token);
        JWSHeader header = signedJWT.getHeader();
        String kid = header.toJSONObject().get("kid").toString();
        JWK jwk = jwkSet.getKeyByKeyId(kid);
        final ECKey ecPublicJWK = new ECKey.Builder(jwk.toECKey()).build();
        JWSVerifier verifier = new ECDSAVerifier(ecPublicJWK);
        return signedJWT.verify(verifier);
    } catch (java.text.ParseException e) {
        throw new RuntimeException(e);
    } catch (JOSEException e) {
        throw new RuntimeException(e);
    }
}

Thanks to @jps