Java Code Examples for org.apache.cxf.rs.security.jose.jwt.JwtToken#getJwsHeaders()

The following examples show how to use org.apache.cxf.rs.security.jose.jwt.JwtToken#getJwsHeaders() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: JwsCompactReaderWriterTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testReadJwsWithJwkSignedByMac() throws Exception {
    JwsJwtCompactConsumer jws = new JwsJwtCompactConsumer(ENCODED_TOKEN_WITH_JSON_KEY_SIGNED_BY_MAC);
    assertTrue(jws.verifySignatureWith(new HmacJwsSignatureVerifier(ENCODED_MAC_KEY,
                                                                    SignatureAlgorithm.HS256)));
    JwtToken token = jws.getJwtToken();
    JwsHeaders headers = new JwsHeaders(token.getJwsHeaders());
    assertEquals(JoseType.JWT, headers.getType());
    assertEquals(SignatureAlgorithm.HS256, headers.getSignatureAlgorithm());

    JsonWebKey key = headers.getJsonWebKey();
    assertEquals(KeyType.OCTET, key.getKeyType());
    List<KeyOperation> keyOps = key.getKeyOperation();
    assertEquals(2, keyOps.size());
    assertEquals(KeyOperation.SIGN, keyOps.get(0));
    assertEquals(KeyOperation.VERIFY, keyOps.get(1));

    validateSpecClaim(token.getClaims());
}
 
Example 2
Source File: JwsCompactReaderWriterTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testJwsPsSha() throws Exception {
    Security.addProvider(new BouncyCastleProvider());
    try {
        JwsHeaders outHeaders = new JwsHeaders();
        outHeaders.setSignatureAlgorithm(SignatureAlgorithm.PS256);
        JwsCompactProducer producer = initSpecJwtTokenWriter(outHeaders);
        PrivateKey privateKey = CryptoUtils.getRSAPrivateKey(RSA_MODULUS_ENCODED, RSA_PRIVATE_EXPONENT_ENCODED);
        String signed = producer.signWith(
            new PrivateKeyJwsSignatureProvider(privateKey, SignatureAlgorithm.PS256));

        JwsJwtCompactConsumer jws = new JwsJwtCompactConsumer(signed);
        RSAPublicKey key = CryptoUtils.getRSAPublicKey(RSA_MODULUS_ENCODED, RSA_PUBLIC_EXPONENT_ENCODED);
        assertTrue(jws.verifySignatureWith(new PublicKeyJwsSignatureVerifier(key, SignatureAlgorithm.PS256)));
        JwtToken token = jws.getJwtToken();
        JwsHeaders inHeaders = new JwsHeaders(token.getJwsHeaders());
        assertEquals(SignatureAlgorithm.PS256,
                     inHeaders.getSignatureAlgorithm());
        validateSpecClaim(token.getClaims());
    } finally {
        Security.removeProvider(BouncyCastleProvider.PROVIDER_NAME);
    }
}
 
Example 3
Source File: JwsCompactReaderWriterTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testWriteReadJwsSignedByESPrivateKey() throws Exception {
    JwsHeaders headers = new JwsHeaders();
    headers.setSignatureAlgorithm(SignatureAlgorithm.ES256);
    JwsCompactProducer jws = initSpecJwtTokenWriter(headers);
    ECPrivateKey privateKey = CryptoUtils.getECPrivateKey(JsonWebKey.EC_CURVE_P256,
                                                          EC_PRIVATE_KEY_ENCODED);
    jws.signWith(new EcDsaJwsSignatureProvider(privateKey, SignatureAlgorithm.ES256));
    String signedJws = jws.getSignedEncodedJws();

    ECPublicKey publicKey = CryptoUtils.getECPublicKey(JsonWebKey.EC_CURVE_P256,
                                                       EC_X_POINT_ENCODED,
                                                       EC_Y_POINT_ENCODED);
    JwsJwtCompactConsumer jwsConsumer = new JwsJwtCompactConsumer(signedJws);
    assertTrue(jwsConsumer.verifySignatureWith(new EcDsaJwsSignatureVerifier(publicKey,
                                               SignatureAlgorithm.ES256)));
    JwtToken token = jwsConsumer.getJwtToken();
    JwsHeaders headersReceived = new JwsHeaders(token.getJwsHeaders());
    assertEquals(SignatureAlgorithm.ES256, headersReceived.getSignatureAlgorithm());
    validateSpecClaim(token.getClaims());
}
 
Example 4
Source File: AbstractOIDCTest.java    From cxf-fediz with Apache License 2.0 6 votes vote down vote up
private void validateIdToken(String idToken, String audience, String role) throws IOException {
    JwsJwtCompactConsumer jwtConsumer = new JwsJwtCompactConsumer(idToken);
    JwtToken jwt = jwtConsumer.getJwtToken();
    JwtClaims jwtClaims = jwt.getClaims();

    // Validate claims
    assertEquals("alice", jwtClaims.getClaim("preferred_username"));
    assertEquals("accounts.fediz.com", jwtClaims.getIssuer());
    assertEquals(audience, jwtClaims.getAudience());
    assertNotNull(jwtClaims.getIssuedAt());
    assertNotNull(jwtClaims.getExpiryTime());

    // Check role
    if (role != null) {
        List<String> roles = jwtClaims.getListStringProperty("roles");
        assertNotNull(roles);
        assertTrue(roles.contains(role));
    }

    JwsHeaders jwsHeaders = jwt.getJwsHeaders();
    assertTrue(jwtConsumer.verifySignatureWith(
        jsonWebKeys().getKey(jwsHeaders.getKeyId()), SignatureAlgorithm.valueOf(jwsHeaders.getAlgorithm())));
}
 
Example 5
Source File: JwsCompactReaderWriterTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testReadJwsSignedByMacSpecExample() throws Exception {
    JwsJwtCompactConsumer jws = new JwsJwtCompactConsumer(ENCODED_TOKEN_SIGNED_BY_MAC);
    assertTrue(jws.verifySignatureWith(new HmacJwsSignatureVerifier(ENCODED_MAC_KEY,
                                                                    SignatureAlgorithm.HS256)));
    JwtToken token = jws.getJwtToken();
    JwsHeaders headers = new JwsHeaders(token.getJwsHeaders());
    assertEquals(JoseType.JWT, headers.getType());
    assertEquals(SignatureAlgorithm.HS256, headers.getSignatureAlgorithm());
    validateSpecClaim(token.getClaims());
}
 
Example 6
Source File: JwsCompactReaderWriterTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testReadJwsSignedByPrivateKey() throws Exception {
    JwsJwtCompactConsumer jws = new JwsJwtCompactConsumer(ENCODED_TOKEN_SIGNED_BY_PRIVATE_KEY);
    RSAPublicKey key = CryptoUtils.getRSAPublicKey(RSA_MODULUS_ENCODED, RSA_PUBLIC_EXPONENT_ENCODED);
    assertTrue(jws.verifySignatureWith(new PublicKeyJwsSignatureVerifier(key, SignatureAlgorithm.RS256)));
    JwtToken token = jws.getJwtToken();
    JwsHeaders headers = new JwsHeaders(token.getJwsHeaders());
    assertEquals(SignatureAlgorithm.RS256, headers.getSignatureAlgorithm());
    validateSpecClaim(token.getClaims());
}
 
Example 7
Source File: JwsJwtCompactProducer.java    From cxf with Apache License 2.0 4 votes vote down vote up
protected JwsJwtCompactProducer(JwtToken token, JsonMapObjectReaderWriter w) {
    super(new JwsHeaders(token.getJwsHeaders()), w,
          JwtUtils.claimsToJson(token.getClaims(), w));
}
 
Example 8
Source File: OidcClaimsValidator.java    From cxf with Apache License 2.0 4 votes vote down vote up
@Override
protected JwsSignatureVerifier getInitializedSignatureVerifier(JwtToken jwt) {
    JsonWebKey key = null;
    if (supportSelfIssuedProvider && SELF_ISSUED_ISSUER.equals(jwt.getClaim("issuer"))) {
        String publicKeyJson = (String)jwt.getClaim("sub_jwk");
        if (publicKeyJson != null) {
            JsonWebKey publicKey = JwkUtils.readJwkKey(publicKeyJson);
            String thumbprint = JwkUtils.getThumbprint(publicKey);
            if (thumbprint.equals(jwt.getClaim("sub"))) {
                key = publicKey;
            }
        }
        if (key == null) {
            throw new SecurityException("Self-issued JWK key is invalid or not available");
        }
    } else {
        String keyId = jwt.getJwsHeaders().getKeyId();
        key = keyId != null ? keyMap.get(keyId) : null;
        if (key == null && jwkSetClient != null) {
            JsonWebKeys keys = jwkSetClient.get(JsonWebKeys.class);
            if (keyId != null) {
                key = keys.getKey(keyId);
            } else if (keys.getKeys().size() == 1) {
                key = keys.getKeys().get(0);
            }
            //jwkSetClient returns the most up-to-date keys
            keyMap.clear();
            keyMap.putAll(keys.getKeyIdMap());
        }
    }
    JwsSignatureVerifier theJwsVerifier = null;
    if (key != null) {
        theJwsVerifier = JwsUtils.getSignatureVerifier(key, jwt.getJwsHeaders().getSignatureAlgorithm());
    } else {
        theJwsVerifier = super.getInitializedSignatureVerifier(jwt.getJwsHeaders());
    }
    if (theJwsVerifier == null) {
        throw new SecurityException("JWS Verifier is not available");
    }

    return theJwsVerifier;
}
 
Example 9
Source File: TrustedIdpOIDCProtocolHandler.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
private boolean validateSignature(TrustedIdp trustedIdp, JwsJwtCompactConsumer jwtConsumer)
    throws CertificateException, WSSecurityException, ProcessingException, IOException {

    // Validate the Signature
    String sigAlgo = getProperty(trustedIdp, SIGNATURE_ALGORITHM);
    if (sigAlgo == null || sigAlgo.isEmpty()) {
        sigAlgo = "RS256";
    }

    JwtToken jwt = jwtConsumer.getJwtToken();
    String jwksUri = getProperty(trustedIdp, JWKS_URI);
    JsonWebKey verifyingKey = null;

    if (jwksUri != null && jwt.getJwsHeaders() != null
        && jwt.getJwsHeaders().containsHeader(JoseConstants.HEADER_KEY_ID)) {
        String kid = (String)jwt.getJwsHeaders().getHeader(JoseConstants.HEADER_KEY_ID);
        LOG.debug("Attemping to retrieve key id {} from uri {}", kid, jwksUri);
        List<Object> jsonKeyProviders = new ArrayList<>();
        jsonKeyProviders.add(new JsonWebKeysProvider());

        WebClient client =
            WebClient.create(jwksUri, jsonKeyProviders, "cxf-tls.xml");
        client.accept("application/json");

        ClientConfiguration config = WebClient.getConfig(client);
        if (LOG.isDebugEnabled()) {
            config.getOutInterceptors().add(new LoggingOutInterceptor());
            config.getInInterceptors().add(new LoggingInInterceptor());
        }

        Response response = client.get();
        JsonWebKeys jsonWebKeys = response.readEntity(JsonWebKeys.class);
        if (jsonWebKeys != null) {
            verifyingKey = jsonWebKeys.getKey(kid);
        }
    }

    if (verifyingKey != null) {
        return jwtConsumer.verifySignatureWith(verifyingKey, SignatureAlgorithm.getAlgorithm(sigAlgo));
    }

    X509Certificate validatingCert = CertsUtils.parseX509Certificate(trustedIdp.getCertificate());
    if (validatingCert != null) {
        return jwtConsumer.verifySignatureWith(validatingCert, SignatureAlgorithm.getAlgorithm(sigAlgo));
    }

    LOG.warn("No key supplied to verify the signature of the IdToken");
    return false;
}