org.apache.cxf.rs.security.jose.jwk.JwkUtils Java Examples

The following examples show how to use org.apache.cxf.rs.security.jose.jwk.JwkUtils. 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: JweUtils.java    From cxf with Apache License 2.0 6 votes vote down vote up
public static KeyEncryptionProvider getKeyEncryptionProvider(JsonWebKey jwk, KeyAlgorithm defaultAlgorithm) {
    KeyAlgorithm keyAlgo = jwk.getAlgorithm() == null ? defaultAlgorithm
        : KeyAlgorithm.getAlgorithm(jwk.getAlgorithm());
    KeyEncryptionProvider keyEncryptionProvider = null;
    KeyType keyType = jwk.getKeyType();
    if (KeyType.RSA == keyType) {
        keyEncryptionProvider = getPublicKeyEncryptionProvider(JwkUtils.toRSAPublicKey(jwk, true),
                                                             keyAlgo);
    } else if (KeyType.OCTET == keyType) {
        keyEncryptionProvider = getSecretKeyEncryptionAlgorithm(JwkUtils.toSecretKey(jwk, keyAlgo),
                                                                keyAlgo);
    } else if (keyAlgo == KeyAlgorithm.ECDH_ES_DIRECT) {
        return new EcdhDirectKeyEncryptionAlgorithm();
    } else {
        ContentAlgorithm ctAlgo = null;
        Message m = PhaseInterceptorChain.getCurrentMessage();
        if (m != null) {
            ctAlgo = getContentAlgo((String)m.get(JoseConstants.RSSEC_ENCRYPTION_CONTENT_ALGORITHM));
        }
        keyEncryptionProvider = new EcdhAesWrapKeyEncryptionAlgorithm(JwkUtils.toECPublicKey(jwk),
                                    jwk.getStringProperty(JsonWebKey.EC_CURVE),
                                    keyAlgo,
                                    ctAlgo == null ? ContentAlgorithm.A128GCM : ctAlgo);
    }
    return keyEncryptionProvider;
}
 
Example #2
Source File: JweUtils.java    From cxf with Apache License 2.0 6 votes vote down vote up
public static JweEncryptionProvider loadEncryptionProvider(Properties props, Message m, JweHeaders headers) {

        KeyEncryptionProvider keyEncryptionProvider = loadKeyEncryptionProvider(props, m, headers);
        ContentAlgorithm contentAlgo = getContentEncryptionAlgorithm(m, props, null, ContentAlgorithm.A128GCM);
        if (m != null) {
            m.put(JoseConstants.RSSEC_ENCRYPTION_CONTENT_ALGORITHM, contentAlgo.getJwaName());
        }
        ContentEncryptionProvider ctEncryptionProvider = null;
        if (KeyAlgorithm.DIRECT == keyEncryptionProvider.getAlgorithm()) {
            JsonWebKey jwk = JwkUtils.loadJsonWebKey(m, props, KeyOperation.ENCRYPT);
            if (jwk != null) {
                contentAlgo = getContentEncryptionAlgorithm(m, props,
                    jwk.getAlgorithm() != null ? ContentAlgorithm.getAlgorithm(jwk.getAlgorithm()) : null,
                    contentAlgo);
                ctEncryptionProvider = getContentEncryptionProvider(jwk, contentAlgo);
            }
        }
        String compression = props.getProperty(JoseConstants.RSSEC_ENCRYPTION_ZIP_ALGORITHM);
        return createJweEncryptionProvider(keyEncryptionProvider,
                                    ctEncryptionProvider,
                                    contentAlgo,
                                    compression,
                                    headers);
    }
 
Example #3
Source File: ApacheCXFConsumer.java    From cxf with Apache License 2.0 6 votes vote down vote up
private JweDecryptionProvider getJweDecryptionProvider(JsonWebKey key, KeyAlgorithm keyEncryptionAlgorithm,
    ContentAlgorithm contentEncryptionAlgorithm) {
    if (key.getAlgorithm() != null) {
        return JweUtils.createJweDecryptionProvider(key, contentEncryptionAlgorithm);
    }
    switch (key.getKeyType()) {
    case EC:
        return JweUtils.createJweDecryptionProvider(JwkUtils.toECPrivateKey(key), keyEncryptionAlgorithm,
            contentEncryptionAlgorithm);
    case RSA:
        return JweUtils.createJweDecryptionProvider(JwkUtils.toRSAPrivateKey(key), keyEncryptionAlgorithm,
            contentEncryptionAlgorithm);
    case OCTET:
        SecretKey secretKey = CryptoUtils.createSecretKeySpec(
            (String) key.getProperty(JsonWebKey.OCTET_KEY_VALUE), keyEncryptionAlgorithm.getJavaName());
        return JweUtils.createJweDecryptionProvider(secretKey, keyEncryptionAlgorithm,
            contentEncryptionAlgorithm);
    default:
        throw new IllegalArgumentException("JWK KeyType not supported: " + key.getKeyType());
    }
}
 
Example #4
Source File: EcdhHelper.java    From cxf with Apache License 2.0 6 votes vote down vote up
public byte[] getDerivedKey(JweHeaders headers) {
    KeyPair pair = CryptoUtils.generateECKeyPair(ecurve);
    ECPublicKey publicKey = (ECPublicKey)pair.getPublic();
    ECPrivateKey privateKey = (ECPrivateKey)pair.getPrivate();
    KeyAlgorithm keyAlgo = headers.getKeyEncryptionAlgorithm();
    ContentAlgorithm contentAlgo = ContentAlgorithm.valueOf(ctAlgo);
    String algorithm = (KeyAlgorithm.isDirect(keyAlgo)) ? contentAlgo.getJwaName() : keyAlgo.getJwaName();
    int keySizeBits = (KeyAlgorithm.isDirect(keyAlgo)) ? contentAlgo.getKeySizeBits() : keyAlgo.getKeySizeBits();

    if (apuBytes != null) {
        headers.setHeader("apu", Base64UrlUtility.encode(apuBytes));
    }
    if (apvBytes != null) {
        headers.setHeader("apv", Base64UrlUtility.encode(apvBytes));
    }
    headers.setJsonWebKey("epk", JwkUtils.fromECPublicKey(publicKey, ecurve));

    return JweUtils.getECDHKey(privateKey, peerPublicKey, apuBytes, apvBytes,
                               algorithm, keySizeBits);
}
 
Example #5
Source File: JweUtils.java    From cxf with Apache License 2.0 6 votes vote down vote up
public static KeyDecryptionProvider getKeyDecryptionProvider(JsonWebKey jwk, KeyAlgorithm defaultAlgorithm) {
    KeyAlgorithm keyAlgo = jwk.getAlgorithm() == null ? defaultAlgorithm
        : KeyAlgorithm.getAlgorithm(jwk.getAlgorithm());
    KeyDecryptionProvider keyDecryptionProvider = null;
    KeyType keyType = jwk.getKeyType();
    if (KeyType.RSA == keyType) {
        keyDecryptionProvider = getPrivateKeyDecryptionProvider(JwkUtils.toRSAPrivateKey(jwk),
                                                             keyAlgo);
    } else if (KeyType.OCTET == keyType) {
        keyDecryptionProvider = getSecretKeyDecryptionProvider(JwkUtils.toSecretKey(jwk),
                                        keyAlgo);
    } else {
        keyDecryptionProvider = getPrivateKeyDecryptionProvider(JwkUtils.toECPrivateKey(jwk),
                                                                 keyAlgo);
    }
    return keyDecryptionProvider;
}
 
Example #6
Source File: JwsUtils.java    From cxf with Apache License 2.0 6 votes vote down vote up
public static JsonWebKeys loadPublicVerificationKeys(Message m, Properties props, boolean stripPrivateParameters) {
    String storeType = props.getProperty(JoseConstants.RSSEC_KEY_STORE_TYPE);
    if ("jwk".equals(storeType)) {
        List<JsonWebKey> jsonWebKeys = JwkUtils.loadJsonWebKeys(m, props, KeyOperation.SIGN, null);
        if (jsonWebKeys == null || jsonWebKeys.isEmpty()) {
            throw new JoseException("Error loading keys");
        }
        return new JsonWebKeys(stripPrivateParameters ? JwkUtils.stripPrivateParameters(jsonWebKeys) : jsonWebKeys);
    }
    X509Certificate[] certs = null;
    if (PropertyUtils.isTrue(props.get(JoseConstants.RSSEC_SIGNATURE_INCLUDE_CERT))) {
        certs = KeyManagementUtils.loadX509CertificateOrChain(m, props);
    }
    PublicKey key = certs != null && certs.length > 0
        ? certs[0].getPublicKey() : KeyManagementUtils.loadPublicKey(m, props);
    JsonWebKey jwk = JwkUtils.fromPublicKey(key, props, JoseConstants.RSSEC_SIGNATURE_ALGORITHM);
    jwk.setPublicKeyUse(PublicKeyUse.SIGN);
    if (certs != null) {
        jwk.setX509Chain(KeyManagementUtils.encodeX509CertificateChain(certs));
    }
    return new JsonWebKeys(jwk);
}
 
Example #7
Source File: ApacheCXFProducer.java    From cxf with Apache License 2.0 6 votes vote down vote up
public void produceJWS(String keyType, String signatureAlgorithm, Serialization serialization, String plainText,
    String jwksJson) {
    JsonWebKeys keys = JwkUtils.readJwkSet(jwksJson);
    JsonWebKey key = getRequestedKeyType(keyType, keys).orElseThrow(IllegalArgumentException::new);

    // Sign
    JwsHeaders jwsHeaders = new JwsHeaders();
    jwsHeaders.setKeyId(key.getKeyId());
    jwsHeaders.setAlgorithm(signatureAlgorithm);
    switch (serialization) {
    case COMPACT:
        produceCompactJWS(plainText, key, jwsHeaders);
        break;
    case FLATTENED:
        produceJsonJWS(plainText, key, jwsHeaders, true);
        break;
    case JSON:
        produceJsonJWS(plainText, key, jwsHeaders, false);
        break;
    default:
        throw new IllegalArgumentException("Serialization not supported: " + serialization);
    }

}
 
Example #8
Source File: JwsUtils.java    From cxf with Apache License 2.0 6 votes vote down vote up
public static JwsSignatureProvider getSignatureProvider(JsonWebKey jwk,
                                                        SignatureAlgorithm defaultAlgorithm) {
    SignatureAlgorithm sigAlgo = jwk.getAlgorithm() == null ? defaultAlgorithm
        : SignatureAlgorithm.getAlgorithm(jwk.getAlgorithm());
    JwsSignatureProvider theSigProvider = null;
    KeyType keyType = jwk.getKeyType();
    if (KeyType.RSA == keyType) {
        theSigProvider = getPrivateKeySignatureProvider(JwkUtils.toRSAPrivateKey(jwk),
                                                        sigAlgo);
    } else if (KeyType.OCTET == keyType) {
        byte[] key = JoseUtils.decode((String)jwk.getProperty(JsonWebKey.OCTET_KEY_VALUE));
        theSigProvider = getHmacSignatureProvider(key, sigAlgo);
    } else if (KeyType.EC == jwk.getKeyType()) {
        theSigProvider = getPrivateKeySignatureProvider(JwkUtils.toECPrivateKey(jwk),
                                                        sigAlgo);
    }
    return theSigProvider;
}
 
Example #9
Source File: ApacheCXFProducer.java    From cxf with Apache License 2.0 6 votes vote down vote up
public void produceJWE(String keyType, String keyEncryptionAlgorithm, String contentEncryptionAlgorithm,
    Serialization serialization, String plainText, String jwksJson) {
    JsonWebKeys keys = JwkUtils.readJwkSet(jwksJson);
    JsonWebKey key = getRequestedKeyType(keyType, keys).orElseThrow(IllegalArgumentException::new);

    // Encrypt
    switch (serialization) {
    case COMPACT:
        JweHeaders headers = new JweHeaders();
        headers.setKeyId(key.getKeyId());
        headers.setKeyEncryptionAlgorithm(KeyAlgorithm.getAlgorithm(keyEncryptionAlgorithm));
        headers.setContentEncryptionAlgorithm(ContentAlgorithm.getAlgorithm(contentEncryptionAlgorithm));
        produceCompactJWE(plainText, key, headers);
        break;
    case FLATTENED:
        produceJsonJWE(keyEncryptionAlgorithm, contentEncryptionAlgorithm, plainText, key, true);
        break;
    case JSON:
        produceJsonJWE(keyEncryptionAlgorithm, contentEncryptionAlgorithm, plainText, key, false);
        break;
    default: 
        throw new IllegalArgumentException("Serialization not supported: " + serialization);
    }

}
 
Example #10
Source File: BookStore.java    From cxf with Apache License 2.0 6 votes vote down vote up
private String getRecipientText(JweJsonConsumer consumer, String recipientPropLoc, String recipientKid) { 
    Message message = JAXRSUtils.getCurrentMessage();
    
    
    Properties recipientProps = JweUtils.loadJweProperties(message, recipientPropLoc);
    JsonWebKey recipientKey = JwkUtils.loadJwkSet(message, recipientProps, null).getKey(recipientKid);
    
    ContentAlgorithm contentEncryptionAlgorithm = JweUtils.getContentEncryptionAlgorithm(recipientProps);
    
    JweDecryptionProvider jweRecipient = 
        JweUtils.createJweDecryptionProvider(recipientKey, contentEncryptionAlgorithm);
    
    JweDecryptionOutput jweRecipientOutput = 
        consumer.decryptWith(jweRecipient,
                             Collections.singletonMap("kid", recipientKid));
    return jweRecipientOutput.getContentText();
}
 
Example #11
Source File: EcdhAesWrapKeyDecryptionAlgorithm.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected byte[] getDecryptedContentEncryptionKeyFromHeaders(JweHeaders headers, ECPrivateKey privateKey) {
    KeyAlgorithm jwtAlgo = headers.getKeyEncryptionAlgorithm();
    JsonWebKey publicJwk = headers.getJsonWebKey("epk");
    String apuHeader = (String) headers.getHeader("apu");
    byte[] apuBytes = apuHeader == null ? null : JoseUtils.decode(apuHeader);
    String apvHeader = (String) headers.getHeader("apv");
    byte[] apvBytes = apvHeader == null ? null : JoseUtils.decode(apvHeader);
    return JweUtils.getECDHKey(privateKey, JwkUtils.toECPublicKey(publicJwk), apuBytes, apvBytes,
        jwtAlgo.getJwaName(), jwtAlgo.getKeySizeBits());
}
 
Example #12
Source File: JweUtils.java    From cxf with Apache License 2.0 5 votes vote down vote up
public static JweEncryption getEcDirectKeyJweEncryption(JsonWebKey key, ContentAlgorithm ctAlgo) {
    if (AlgorithmUtils.isEcdhEsDirect(key.getAlgorithm())) {
        String curve = key.getStringProperty(JsonWebKey.EC_CURVE);
        if (curve == null) {
            curve = JsonWebKey.EC_CURVE_P256;
        }
        ECPublicKey ecKey = JwkUtils.toECPublicKey(key);
        return new EcdhDirectKeyJweEncryption(ecKey, curve, ctAlgo);
    }
    throw new JweException(JweException.Error.INVALID_KEY_ALGORITHM);
}
 
Example #13
Source File: ApacheCXFConsumer.java    From cxf with Apache License 2.0 5 votes vote down vote up
public void consumeJWS(String signedData, String plainText, String jwks) {
    JsonWebKeys keys = JwkUtils.readJwkSet(jwks);
    if (signedData.startsWith("{")) {
        consumeJsonJWS(signedData, plainText, keys);
    } else {
        consumeCompactJWS(signedData, plainText, keys);
    }
}
 
Example #14
Source File: JweUtils.java    From cxf with Apache License 2.0 5 votes vote down vote up
public static JsonWebKeys loadPublicKeyEncryptionKeys(Message m, Properties props) {
    String storeType = props.getProperty(JoseConstants.RSSEC_KEY_STORE_TYPE);
    if ("jwk".equals(storeType)) {
        return JwkUtils.loadPublicJwkSet(m, props);
    }
    //TODO: consider loading all the public keys in the store
    PublicKey key = KeyManagementUtils.loadPublicKey(m, props);
    JsonWebKey jwk = JwkUtils.fromPublicKey(key, props, JoseConstants.RSSEC_ENCRYPTION_KEY_ALGORITHM);
    return new JsonWebKeys(jwk);
}
 
Example #15
Source File: JweUtils.java    From cxf with Apache License 2.0 5 votes vote down vote up
public static byte[] getECDHKey(JsonWebKey privateKey,
                                JsonWebKey peerPublicKey,
                                byte[] partyUInfo,
                                byte[] partyVInfo,
                                String algoName,
                                int algoKeyBitLen) {
    return getECDHKey(JwkUtils.toECPrivateKey(privateKey),
                      JwkUtils.toECPublicKey(peerPublicKey),
                      partyUInfo, partyVInfo, algoName, algoKeyBitLen);
}
 
Example #16
Source File: JweUtils.java    From cxf with Apache License 2.0 5 votes vote down vote up
public static ContentEncryptionProvider getEcdhDirectContentEncryptionProvider(JsonWebKey key, JweHeaders headers) {
    String curve = key.getStringProperty(JsonWebKey.EC_CURVE);
    if (curve == null) {
        curve = JsonWebKey.EC_CURVE_P256;
    }
    ECPublicKey ecKey = JwkUtils.toECPublicKey(key);
    return new EcdhAesGcmContentEncryptionAlgorithm(ecKey, curve, null, null, 
        headers.getContentEncryptionAlgorithm());
}
 
Example #17
Source File: JwsJoseCookBookTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testECDSASignature() throws Exception {

    try {
        Cipher.getInstance(AlgorithmUtils.ES_SHA_512_JAVA);
    } catch (Throwable t) {
        Security.addProvider(new BouncyCastleProvider());
    }
    try {
        JwsCompactProducer compactProducer = new JwsCompactProducer(PAYLOAD);
        compactProducer.getJwsHeaders().setSignatureAlgorithm(SignatureAlgorithm.ES512);
        compactProducer.getJwsHeaders().setKeyId(ECDSA_KID_VALUE);
        JsonMapObjectReaderWriter reader = new JsonMapObjectReaderWriter();
        assertEquals(reader.toJson(compactProducer.getJwsHeaders().asMap()),
                     ECDSA_SIGNATURE_PROTECTED_HEADER_JSON);
        assertEquals(compactProducer.getUnsignedEncodedJws(),
                ECSDA_SIGNATURE_PROTECTED_HEADER + "." + ENCODED_PAYLOAD);
        JsonWebKeys jwks = readKeySet("cookbookPrivateSet.txt");
        List<JsonWebKey> keys = jwks.getKeys();
        JsonWebKey ecKey = keys.get(0);
        compactProducer.signWith(new EcDsaJwsSignatureProvider(JwkUtils.toECPrivateKey(ecKey),
                                                               SignatureAlgorithm.ES512));
        assertEquals(compactProducer.getUnsignedEncodedJws(),
                     ECSDA_SIGNATURE_PROTECTED_HEADER + "." + ENCODED_PAYLOAD);
        assertEquals(132, Base64UrlUtility.decode(compactProducer.getEncodedSignature()).length);

        JwsCompactConsumer compactConsumer = new JwsCompactConsumer(compactProducer.getSignedEncodedJws());
        JsonWebKeys publicJwks = readKeySet("cookbookPublicSet.txt");
        List<JsonWebKey> publicKeys = publicJwks.getKeys();
        JsonWebKey ecPublicKey = publicKeys.get(0);
        assertTrue(compactConsumer.verifySignatureWith(ecPublicKey, SignatureAlgorithm.ES512));
    } finally {
        Security.removeProvider(BouncyCastleProvider.PROVIDER_NAME);
    }
}
 
Example #18
Source File: ApacheCXFConsumer.java    From cxf with Apache License 2.0 5 votes vote down vote up
public void consumeJWE(String encryptedData, String plainText, String jwks) {
    JsonWebKeys keys = JwkUtils.readJwkSet(jwks);
    if (encryptedData.startsWith("{")) {
        consumeJsonJWE(encryptedData, plainText, keys);
    } else {
        consumeCompactJWE(encryptedData, plainText, keys);
    }
}
 
Example #19
Source File: JweUtils.java    From cxf with Apache License 2.0 5 votes vote down vote up
public static JweDecryption getEcDirectKeyJweDecryption(JsonWebKey key, ContentAlgorithm ctAlgo) {
    if (AlgorithmUtils.isEcdhEsDirect(key.getAlgorithm())) {
        ECPrivateKey ecKey = JwkUtils.toECPrivateKey(key);
        return new EcdhDirectKeyJweDecryption(ecKey, ctAlgo);
    }
    throw new JweException(JweException.Error.INVALID_KEY_ALGORITHM);
}
 
Example #20
Source File: JweUtils.java    From cxf with Apache License 2.0 5 votes vote down vote up
public static SecretKey getContentDecryptionSecretKey(JsonWebKey jwk, String defaultAlgorithm) {
    String ctEncryptionAlgo = jwk.getAlgorithm() == null ? defaultAlgorithm : jwk.getAlgorithm();
    KeyType keyType = jwk.getKeyType();
    if (KeyType.OCTET == keyType && AlgorithmUtils.isAesGcm(ctEncryptionAlgo)) {
        return JwkUtils.toSecretKey(jwk);
    }
    return null;
}
 
Example #21
Source File: JweUtils.java    From cxf with Apache License 2.0 5 votes vote down vote up
public static ContentEncryptionProvider getContentEncryptionProvider(JsonWebKey jwk,
                                                                     ContentAlgorithm defaultAlgorithm) {
    ContentAlgorithm ctAlgo = jwk.getAlgorithm() == null ? defaultAlgorithm
        : getContentAlgo(jwk.getAlgorithm());
    KeyType keyType = jwk.getKeyType();
    if (KeyType.OCTET == keyType) {
        return getContentEncryptionProvider(JwkUtils.toSecretKey(jwk), ctAlgo);
    }
    return null;
}
 
Example #22
Source File: EcdhDirectKeyDecryptionAlgorithm.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected byte[] getDecryptedContentEncryptionKeyFromHeaders(JweHeaders headers, ECPrivateKey key) {
    ContentAlgorithm jwtAlgo = headers.getContentEncryptionAlgorithm();
    JsonWebKey publicJwk = headers.getJsonWebKey("epk");
    String apuHeader = (String) headers.getHeader("apu");
    byte[] apuBytes = apuHeader == null ? null : JoseUtils.decode(apuHeader);
    String apvHeader = (String) headers.getHeader("apv");
    byte[] apvBytes = apvHeader == null ? null : JoseUtils.decode(apvHeader);
    return JweUtils.getECDHKey(key, JwkUtils.toECPublicKey(publicJwk), apuBytes, apvBytes,
        jwtAlgo.getJwaName(), jwtAlgo.getKeySizeBits());
}
 
Example #23
Source File: JwsUtils.java    From cxf with Apache License 2.0 5 votes vote down vote up
public static JwsSignatureVerifier getSignatureVerifier(JsonWebKey jwk, SignatureAlgorithm defaultAlgorithm) {
    SignatureAlgorithm sigAlgo = jwk.getAlgorithm() == null ? defaultAlgorithm
        : SignatureAlgorithm.getAlgorithm(jwk.getAlgorithm());
    JwsSignatureVerifier theVerifier = null;
    KeyType keyType = jwk.getKeyType();
    if (KeyType.RSA == keyType) {
        theVerifier = getPublicKeySignatureVerifier(JwkUtils.toRSAPublicKey(jwk, true), sigAlgo);
    } else if (KeyType.OCTET == keyType) {
        byte[] key = JoseUtils.decode((String)jwk.getProperty(JsonWebKey.OCTET_KEY_VALUE));
        theVerifier = getHmacSignatureVerifier(key, sigAlgo);
    } else if (KeyType.EC == keyType) {
        theVerifier = getPublicKeySignatureVerifier(JwkUtils.toECPublicKey(jwk), sigAlgo);
    }
    return theVerifier;
}
 
Example #24
Source File: JsonWebKeysProvider.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
public void writeTo(JsonWebKeys t, Class<?> type, Type genericType, Annotation[] annotations,
                    MediaType mediaType, MultivaluedMap<String, Object> httpHeaders,
                    OutputStream entityStream) throws IOException, WebApplicationException {
    JwkUtils.jwkSetToJson(t, entityStream);

}
 
Example #25
Source File: KeySetRetriever.java    From deprecated-security-advanced-modules with Apache License 2.0 5 votes vote down vote up
public JsonWebKeys get() throws AuthenticatorUnavailableException {
	String uri = getJwksUri();

	try (CloseableHttpClient httpClient = createHttpClient(null)) {

		HttpGet httpGet = new HttpGet(uri);

		RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(getRequestTimeoutMs())
				.setConnectTimeout(getRequestTimeoutMs()).setSocketTimeout(getRequestTimeoutMs()).build();

		httpGet.setConfig(requestConfig);

		try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
			StatusLine statusLine = response.getStatusLine();

			if (statusLine.getStatusCode() < 200 || statusLine.getStatusCode() >= 300) {
				throw new AuthenticatorUnavailableException("Error while getting " + uri + ": " + statusLine);
			}

			HttpEntity httpEntity = response.getEntity();

			if (httpEntity == null) {
				throw new AuthenticatorUnavailableException(
						"Error while getting " + uri + ": Empty response entity");
			}

			JsonWebKeys keySet = JwkUtils.readJwkSet(httpEntity.getContent());

			return keySet;
		}
	} catch (IOException e) {
		throw new AuthenticatorUnavailableException("Error while getting " + uri + ": " + e, e);
	}

}
 
Example #26
Source File: DefaultJoseImpl.java    From thorntail with Apache License 2.0 5 votes vote down vote up
private JsonWebKey loadJsonWebKey(String kid) {
    JsonWebKeys jwkSet = JwkUtils.readJwkSet(config.inlinedKeystoreJwkSet());
    JsonWebKey jwkKey = jwkSet.getKey(kid);
    if (jwkKey == null) {
        throw new JoseException("JWK key is not available");
    }
    return jwkKey;
}
 
Example #27
Source File: JwkJoseCookBookTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
public JsonWebKey readKey(String key) throws Exception {
    return JwkUtils.readJwkKey(key);
}
 
Example #28
Source File: AbstractOIDCTest.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
private JsonWebKeys jsonWebKeys() throws IOException {
    return JwkUtils.readJwkSet(oidcEndpointBuilder("/jwk/keys").build());
}
 
Example #29
Source File: JwsJoseCookBookTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
public JsonWebKeys readKeySet(String fileName) throws Exception {
    InputStream is = JwsJoseCookBookTest.class.getResourceAsStream(fileName);
    String s = IOUtils.readStringFromStream(is);
    return JwkUtils.readJwkSet(s);
}
 
Example #30
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;
}