org.apache.cxf.rs.security.jose.jws.JwsUtils Java Examples

The following examples show how to use org.apache.cxf.rs.security.jose.jws.JwsUtils. 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: OidcImplicitService.java    From cxf with Apache License 2.0 6 votes vote down vote up
protected String processIdToken(OAuthRedirectionState state, IdToken idToken) {
    OAuthJoseJwtProducer processor = idTokenHandler == null ? new OAuthJoseJwtProducer() : idTokenHandler;

    String code =
        (String)JAXRSUtils.getCurrentMessage().getExchange().get(OAuthConstants.AUTHORIZATION_CODE_VALUE);
    if (code != null) {
        // this service is invoked as part of the hybrid flow
        Properties props = JwsUtils.loadSignatureOutProperties(false);
        SignatureAlgorithm sigAlgo = null;
        if (processor.isSignWithClientSecret()) {
            sigAlgo = OAuthUtils.getClientSecretSignatureAlgorithm(props);
        } else {
            sigAlgo = JwsUtils.getSignatureAlgorithm(props, SignatureAlgorithm.RS256);
        }
        idToken.setAuthorizationCodeHash(OidcUtils.calculateAuthorizationCodeHash(code, sigAlgo));
    }

    idToken.setNonce(state.getNonce());
    return processor.processJwt(new JwtToken(idToken));
}
 
Example #2
Source File: ApacheCXFConsumer.java    From cxf with Apache License 2.0 6 votes vote down vote up
protected void consumeCompactJWS(String signedData, String plainText, JsonWebKeys keys) {

        // Validate Signature

        // 1. Read data to get key id (only need to do this if you don't know the key)
        JwsCompactConsumer jwsConsumer = new JwsCompactConsumer(signedData);
        String kid = jwsConsumer.getJwsHeaders().getKeyId();

        Assert.assertNotNull("Data does not contain kid header.", kid);

        // 2. Get key
        JsonWebKey key = keys.getKey(kid);
        Assert.assertNotNull("Data signed with unknown key", key);

        // 3. Verify
        SignatureAlgorithm signAlgo = jwsConsumer.getJwsHeaders().getSignatureAlgorithm();
        Assert.assertNotNull("Signed data does not define algorithm used", signAlgo);
        JwsSignatureVerifier signatureVerifier = JwsUtils.getSignatureVerifier(key, signAlgo);
        Assert.assertTrue("Signature validation failed", jwsConsumer.verifySignatureWith(signatureVerifier));

        // Validate plain text
        Assert.assertEquals(plainText, jwsConsumer.getDecodedJwsPayload());
    }
 
Example #3
Source File: ApacheCXFConsumer.java    From cxf with Apache License 2.0 6 votes vote down vote up
protected void consumeJsonJWS(String signedData, String plainText, JsonWebKeys keys) {

        // Validate signature

        // 1. Read data
        JwsJsonConsumer jwsConsumer = new JwsJsonConsumer(signedData);
        jwsConsumer.getSignatureEntries().forEach(signature -> {
            String kid = signature.getKeyId();
            Assert.assertNotNull("Signature does not contain kid.", kid);

            // 2. Get Key
            JsonWebKey key = keys.getKey(kid);
            Assert.assertNotNull("Data signed with unknown key", key);

            // 3. Verify
            SignatureAlgorithm signAlgo = signature.getUnionHeader().getSignatureAlgorithm();
            Assert.assertNotNull("Signed data does not define algorithm used", signAlgo);
            JwsSignatureVerifier signatureVerifier = JwsUtils.getSignatureVerifier(key, signAlgo);
            Assert.assertTrue("Signature validation failed", jwsConsumer.verifySignatureWith(signatureVerifier));

            // Validate plain text
            Assert.assertEquals(plainText, signature.getDecodedJwsPayload());
        });
    }
 
Example #4
Source File: JwsJoseCookBookTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testProtectingContentOnlySignature() throws Exception {
    JwsJsonProducer jsonProducer = new JwsJsonProducer(PAYLOAD);
    assertEquals(jsonProducer.getPlainPayload(), PAYLOAD);
    assertEquals(jsonProducer.getUnsignedEncodedPayload(), ENCODED_PAYLOAD);
    JwsHeaders unprotectedHeader = new JwsHeaders();
    unprotectedHeader.setSignatureAlgorithm(SignatureAlgorithm.HS256);
    unprotectedHeader.setKeyId(HMAC_KID_VALUE);
    JsonWebKeys jwks = readKeySet("cookbookSecretSet.txt");
    List<JsonWebKey> keys = jwks.getKeys();
    JsonWebKey key = keys.get(0);
    jsonProducer.signWith(JwsUtils.getSignatureProvider(key, SignatureAlgorithm.HS256),
            null, unprotectedHeader);
    assertEquals(jsonProducer.getJwsJsonSignedDocument(),
            PROTECTING_CONTENT_ONLY_JSON_GENERAL_SERIALIZATION);
    JwsJsonConsumer jsonConsumer =
            new JwsJsonConsumer(jsonProducer.getJwsJsonSignedDocument());
    assertTrue(jsonConsumer.verifySignatureWith(key, SignatureAlgorithm.HS256));

    jsonProducer = new JwsJsonProducer(PAYLOAD, true);
    jsonProducer.signWith(JwsUtils.getSignatureProvider(key, SignatureAlgorithm.HS256),
            null, unprotectedHeader);
    assertEquals(jsonProducer.getJwsJsonSignedDocument(),
            PROTECTING_CONTENT_ONLY_JSON_FLATTENED_SERIALIZATION);
    jsonConsumer = new JwsJsonConsumer(jsonProducer.getJwsJsonSignedDocument());
    assertTrue(jsonConsumer.verifySignatureWith(key, SignatureAlgorithm.HS256));
}
 
Example #5
Source File: JwsJoseCookBookTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testProtectingSpecificHeaderFieldsSignature() throws Exception {
    JwsJsonProducer jsonProducer = new JwsJsonProducer(PAYLOAD);
    assertEquals(jsonProducer.getPlainPayload(), PAYLOAD);
    assertEquals(jsonProducer.getUnsignedEncodedPayload(), ENCODED_PAYLOAD);
    JwsHeaders protectedHeader = new JwsHeaders();
    protectedHeader.setSignatureAlgorithm(SignatureAlgorithm.HS256);
    JwsHeaders unprotectedHeader = new JwsHeaders();
    unprotectedHeader.setKeyId(HMAC_KID_VALUE);
    JsonWebKeys jwks = readKeySet("cookbookSecretSet.txt");
    List<JsonWebKey> keys = jwks.getKeys();
    JsonWebKey key = keys.get(0);
    jsonProducer.signWith(JwsUtils.getSignatureProvider(key, SignatureAlgorithm.HS256),
            protectedHeader, unprotectedHeader);
    assertEquals(jsonProducer.getJwsJsonSignedDocument(),
            PROTECTING_SPECIFIC_HEADER_FIELDS_JSON_GENERAL_SERIALIZATION);
    JwsJsonConsumer jsonConsumer =
            new JwsJsonConsumer(jsonProducer.getJwsJsonSignedDocument());
    assertTrue(jsonConsumer.verifySignatureWith(key, SignatureAlgorithm.HS256));

    jsonProducer = new JwsJsonProducer(PAYLOAD, true);
    jsonProducer.signWith(JwsUtils.getSignatureProvider(key, SignatureAlgorithm.HS256),
            protectedHeader, unprotectedHeader);
    assertEquals(jsonProducer.getJwsJsonSignedDocument(),
            PROTECTING_SPECIFIC_HEADER_FIELDS_JSON_FLATTENED_SERIALIZATION);
    jsonConsumer = new JwsJsonConsumer(jsonProducer.getJwsJsonSignedDocument());
    assertTrue(jsonConsumer.verifySignatureWith(key, SignatureAlgorithm.HS256));
}
 
Example #6
Source File: JwsJoseCookBookTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testDetachedHMACSignature2() throws Exception {
    JsonWebKeys jwks = readKeySet("cookbookSecretSet.txt");
    List<JsonWebKey> keys = jwks.getKeys();
    JsonWebKey key = keys.get(0);
    
    JwsJsonProducer jsonProducer = new JwsJsonProducer(PAYLOAD, false, true);
    assertEquals(jsonProducer.getPlainPayload(), PAYLOAD);
    assertEquals(jsonProducer.getUnsignedEncodedPayload(), ENCODED_PAYLOAD);
    JwsHeaders protectedHeader = new JwsHeaders();
    protectedHeader.setSignatureAlgorithm(SignatureAlgorithm.HS256);
    protectedHeader.setKeyId(HMAC_KID_VALUE);
    
    String jwsJsonCompleteSequence = 
        jsonProducer.signWith(JwsUtils.getSignatureProvider(key, SignatureAlgorithm.HS256), protectedHeader);
    assertEquals(jwsJsonCompleteSequence, HMAC_DETACHED_JSON_GENERAL_SERIALIZATION);
    JwsJsonConsumer jsonConsumer =
            new JwsJsonConsumer(jsonProducer.getJwsJsonSignedDocument(), ENCODED_PAYLOAD);
    assertTrue(jsonConsumer.verifySignatureWith(key, SignatureAlgorithm.HS256));

    jsonProducer = new JwsJsonProducer(PAYLOAD, true, true);
    String jwsJsonFlattenedSequence = 
        jsonProducer.signWith(JwsUtils.getSignatureProvider(key, SignatureAlgorithm.HS256), protectedHeader);
    assertEquals(jwsJsonFlattenedSequence, HMAC_DETACHED_JSON_FLATTENED_SERIALIZATION);
    jsonConsumer = new JwsJsonConsumer(jwsJsonFlattenedSequence, ENCODED_PAYLOAD);
    assertTrue(jsonConsumer.verifySignatureWith(key, SignatureAlgorithm.HS256));
}
 
Example #7
Source File: JwsJoseCookBookTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("deprecation")
@Test
public void testDetachedHMACSignature() throws Exception {
    JwsCompactProducer compactProducer = new JwsCompactProducer(PAYLOAD, true);
    compactProducer.getJwsHeaders().setSignatureAlgorithm(SignatureAlgorithm.HS256);
    compactProducer.getJwsHeaders().setKeyId(HMAC_KID_VALUE);
    JsonMapObjectReaderWriter reader = new JsonMapObjectReaderWriter();
    assertEquals(reader.toJson(compactProducer.getJwsHeaders().asMap()), HMAC_SIGNATURE_PROTECTED_HEADER_JSON);
    assertEquals(compactProducer.getUnsignedEncodedJws(),
            HMAC_SIGNATURE_PROTECTED_HEADER + ".");
    JsonWebKeys jwks = readKeySet("cookbookSecretSet.txt");
    List<JsonWebKey> keys = jwks.getKeys();
    JsonWebKey key = keys.get(0);
    compactProducer.signWith(key);
    assertEquals(compactProducer.getSignedEncodedJws(), DETACHED_HMAC_JWS);
    JwsCompactConsumer compactConsumer =
            new JwsCompactConsumer(compactProducer.getSignedEncodedJws(), ENCODED_PAYLOAD);
    assertTrue(compactConsumer.verifySignatureWith(key, SignatureAlgorithm.HS256));

    JwsJsonProducer jsonProducer = new JwsJsonProducer(PAYLOAD);
    assertEquals(jsonProducer.getPlainPayload(), PAYLOAD);
    assertEquals(jsonProducer.getUnsignedEncodedPayload(), ENCODED_PAYLOAD);
    JwsHeaders protectedHeader = new JwsHeaders();
    protectedHeader.setSignatureAlgorithm(SignatureAlgorithm.HS256);
    protectedHeader.setKeyId(HMAC_KID_VALUE);
    jsonProducer.signWith(JwsUtils.getSignatureProvider(key, SignatureAlgorithm.HS256), protectedHeader);
    assertEquals(jsonProducer.getJwsJsonSignedDocument(true), HMAC_DETACHED_JSON_GENERAL_SERIALIZATION);
    JwsJsonConsumer jsonConsumer =
            new JwsJsonConsumer(jsonProducer.getJwsJsonSignedDocument(true), ENCODED_PAYLOAD);
    assertTrue(jsonConsumer.verifySignatureWith(key, SignatureAlgorithm.HS256));

    jsonProducer = new JwsJsonProducer(PAYLOAD, true);
    jsonProducer.signWith(JwsUtils.getSignatureProvider(key, SignatureAlgorithm.HS256), protectedHeader);
    assertEquals(jsonProducer.getJwsJsonSignedDocument(true), HMAC_DETACHED_JSON_FLATTENED_SERIALIZATION);
    jsonConsumer = new JwsJsonConsumer(jsonProducer.getJwsJsonSignedDocument(true), ENCODED_PAYLOAD);
    assertTrue(jsonConsumer.verifySignatureWith(key, SignatureAlgorithm.HS256));
}
 
Example #8
Source File: JwsJoseCookBookTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testHMACSignature() throws Exception {
    JwsCompactProducer compactProducer = new JwsCompactProducer(PAYLOAD);
    compactProducer.getJwsHeaders().setSignatureAlgorithm(SignatureAlgorithm.HS256);
    compactProducer.getJwsHeaders().setKeyId(HMAC_KID_VALUE);
    JsonMapObjectReaderWriter reader = new JsonMapObjectReaderWriter();
    assertEquals(reader.toJson(compactProducer.getJwsHeaders().asMap()), HMAC_SIGNATURE_PROTECTED_HEADER_JSON);
    assertEquals(compactProducer.getUnsignedEncodedJws(),
            HMAC_SIGNATURE_PROTECTED_HEADER + "." + ENCODED_PAYLOAD);
    JsonWebKeys jwks = readKeySet("cookbookSecretSet.txt");
    List<JsonWebKey> keys = jwks.getKeys();
    JsonWebKey key = keys.get(0);
    compactProducer.signWith(key);
    assertEquals(compactProducer.getSignedEncodedJws(),
            HMAC_SIGNATURE_PROTECTED_HEADER + "." + ENCODED_PAYLOAD + "." + HMAC_SIGNATURE_VALUE);
    JwsCompactConsumer compactConsumer = new JwsCompactConsumer(compactProducer.getSignedEncodedJws());
    assertTrue(compactConsumer.verifySignatureWith(key, SignatureAlgorithm.HS256));

    JwsJsonProducer jsonProducer = new JwsJsonProducer(PAYLOAD);
    assertEquals(jsonProducer.getPlainPayload(), PAYLOAD);
    assertEquals(jsonProducer.getUnsignedEncodedPayload(), ENCODED_PAYLOAD);
    JwsHeaders protectedHeader = new JwsHeaders();
    protectedHeader.setSignatureAlgorithm(SignatureAlgorithm.HS256);
    protectedHeader.setKeyId(HMAC_KID_VALUE);
    jsonProducer.signWith(JwsUtils.getSignatureProvider(key, SignatureAlgorithm.HS256), protectedHeader);
    assertEquals(jsonProducer.getJwsJsonSignedDocument(), HMAC_JSON_GENERAL_SERIALIZATION);
    JwsJsonConsumer jsonConsumer = new JwsJsonConsumer(jsonProducer.getJwsJsonSignedDocument());
    assertTrue(jsonConsumer.verifySignatureWith(key, SignatureAlgorithm.HS256));

    jsonProducer = new JwsJsonProducer(PAYLOAD, true);
    jsonProducer.signWith(JwsUtils.getSignatureProvider(key, SignatureAlgorithm.HS256), protectedHeader);
    assertEquals(jsonProducer.getJwsJsonSignedDocument(), HMAC_JSON_FLATTENED_SERIALIZATION);
    jsonConsumer = new JwsJsonConsumer(jsonProducer.getJwsJsonSignedDocument());
    assertTrue(jsonConsumer.verifySignatureWith(key, SignatureAlgorithm.HS256));
}
 
Example #9
Source File: JwsJoseCookBookTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testRSAv15Signature() throws Exception {
    JwsCompactProducer compactProducer = new JwsCompactProducer(PAYLOAD);
    compactProducer.getJwsHeaders().setSignatureAlgorithm(SignatureAlgorithm.RS256);
    compactProducer.getJwsHeaders().setKeyId(RSA_KID_VALUE);
    JsonMapObjectReaderWriter reader = new JsonMapObjectReaderWriter();
    assertEquals(reader.toJson(compactProducer.getJwsHeaders().asMap()), RSA_V1_5_SIGNATURE_PROTECTED_HEADER_JSON);
    assertEquals(compactProducer.getUnsignedEncodedJws(),
            RSA_V1_5_SIGNATURE_PROTECTED_HEADER + "." + ENCODED_PAYLOAD);
    JsonWebKeys jwks = readKeySet("cookbookPrivateSet.txt");
    List<JsonWebKey> keys = jwks.getKeys();
    JsonWebKey rsaKey = keys.get(1);
    compactProducer.signWith(rsaKey);
    assertEquals(compactProducer.getSignedEncodedJws(),
            RSA_V1_5_SIGNATURE_PROTECTED_HEADER + "." + ENCODED_PAYLOAD + "." + RSA_V1_5_SIGNATURE_VALUE);
    JwsCompactConsumer compactConsumer = new JwsCompactConsumer(compactProducer.getSignedEncodedJws());
    JsonWebKeys publicJwks = readKeySet("cookbookPublicSet.txt");
    List<JsonWebKey> publicKeys = publicJwks.getKeys();
    JsonWebKey rsaPublicKey = publicKeys.get(1);
    assertTrue(compactConsumer.verifySignatureWith(rsaPublicKey,
                                                   SignatureAlgorithm.RS256));

    JwsJsonProducer jsonProducer = new JwsJsonProducer(PAYLOAD);
    assertEquals(jsonProducer.getPlainPayload(), PAYLOAD);
    assertEquals(jsonProducer.getUnsignedEncodedPayload(), ENCODED_PAYLOAD);
    JwsHeaders protectedHeader = new JwsHeaders();
    protectedHeader.setSignatureAlgorithm(SignatureAlgorithm.RS256);
    protectedHeader.setKeyId(RSA_KID_VALUE);
    jsonProducer.signWith(JwsUtils.getSignatureProvider(rsaKey,
                                                        SignatureAlgorithm.RS256), protectedHeader);
    assertEquals(jsonProducer.getJwsJsonSignedDocument(), RSA_V1_5_JSON_GENERAL_SERIALIZATION);
    JwsJsonConsumer jsonConsumer = new JwsJsonConsumer(jsonProducer.getJwsJsonSignedDocument());
    assertTrue(jsonConsumer.verifySignatureWith(rsaPublicKey, SignatureAlgorithm.RS256));

    jsonProducer = new JwsJsonProducer(PAYLOAD, true);
    jsonProducer.signWith(JwsUtils.getSignatureProvider(rsaKey, SignatureAlgorithm.RS256), protectedHeader);
    assertEquals(jsonProducer.getJwsJsonSignedDocument(), RSA_V1_5_JSON_FLATTENED_SERIALIZATION);
    jsonConsumer = new JwsJsonConsumer(jsonProducer.getJwsJsonSignedDocument());
    assertTrue(jsonConsumer.verifySignatureWith(rsaPublicKey, SignatureAlgorithm.RS256));
}
 
Example #10
Source File: OidcConfigurationService.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
protected void prepareConfigurationData(Map<String, Object> cfg, String baseUri) {
    super.prepareConfigurationData(cfg, baseUri);
    // UriInfo Endpoint
    if (!isUserInfoEndpointNotAvailable()) {
        String theUserInfoEndpointAddress =
            calculateEndpointAddress(userInfoEndpointAddress, baseUri, "/users/userinfo");
        cfg.put("userinfo_endpoint", theUserInfoEndpointAddress);
    }

    Properties sigProps = JwsUtils.loadSignatureOutProperties(false);
    if (sigProps != null && sigProps.containsKey(JoseConstants.RSSEC_SIGNATURE_ALGORITHM)) {
        cfg.put("id_token_signing_alg_values_supported",
                Collections.singletonList(sigProps.get(JoseConstants.RSSEC_SIGNATURE_ALGORITHM)));
    }
    
    // RP Initiated Logout Endpoint
    if (!isEndSessionEndpointNotAvailable()) {
        String theEndSessionEndpointAddress =
            calculateEndpointAddress(endSessionEndpointAddress, baseUri, "/idp/logout");
        cfg.put("end_session_endpoint", theEndSessionEndpointAddress);
    }
    
    if (isBackChannelLogoutSupported()) {
        cfg.put("backchannel_logout_supported", Boolean.TRUE);
    }
    
    //Subject types: pairwise is not supported yet
    cfg.put("subject_types_supported", Collections.singletonList("public"));
    
    List<String> theResponseTypes = responseTypes == null ? DEFAULT_RESPONSE_TYPES : responseTypes;
    cfg.put("response_types_supported", theResponseTypes);
}
 
Example #11
Source File: AbstractJwsMultipartSignatureFilter.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected List<Object> getAttachmentParts(Object rootEntity) {
    List<Object> parts = null;
    
    if (rootEntity instanceof MultipartBody) {
        parts = CastUtils.cast(((MultipartBody)rootEntity).getAllAttachments());
    } else {
        parts = new ArrayList<>();
        if (rootEntity instanceof List) {
            List<Object> entityList = CastUtils.cast((List<?>)rootEntity);
            parts.addAll(entityList);
        } else {
            parts.add(rootEntity);
        }
    }
    
    JwsHeaders headers = new JwsHeaders();
    headers.setPayloadEncodingStatus(false);
    JwsSignatureProvider theSigProvider = sigProvider != null ? sigProvider
        : JwsUtils.loadSignatureProvider(headers, true);
    JwsSignature jwsSignature = theSigProvider.createJwsSignature(headers);
    
    String base64UrlEncodedHeaders = Base64UrlUtility.encode(writer.toJson(headers));
    byte[] headerBytesWithDot = StringUtils.toBytesASCII(base64UrlEncodedHeaders + ".");
    jwsSignature.update(headerBytesWithDot, 0, headerBytesWithDot.length);
    AttachmentUtils.addMultipartOutFilter(new JwsMultipartSignatureOutFilter(jwsSignature));
    
    
    JwsDetachedSignature jws = new JwsDetachedSignature(headers, 
                                                        base64UrlEncodedHeaders,
                                                        jwsSignature,
                                                        useJwsJsonSignatureFormat);
    
    Attachment jwsPart = new Attachment("signature", JoseConstants.MEDIA_TYPE_JOSE, jws);
    parts.add(jwsPart);
    return parts;
}
 
Example #12
Source File: AbstractJoseConsumer.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected JwsSignatureVerifier getInitializedSignatureVerifier(JwsHeaders jwsHeaders) {
    if (jwsVerifier != null) {
        return jwsVerifier;
    }

    return JwsUtils.loadSignatureVerifier(jwsHeaders, false);
}
 
Example #13
Source File: AbstractJoseProducer.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected JwsSignatureProvider getInitializedSignatureProvider(JwsHeaders jwsHeaders) {
    if (sigProvider != null) {
        return sigProvider;
    }

    return JwsUtils.loadSignatureProvider(jwsHeaders, false);
}
 
Example #14
Source File: AbstractJwsJsonWriterProvider.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected List<JwsSignatureProvider> getInitializedSigProviders(
    List<String> propLocs, List<JwsHeaders> protectedHeaders) {
    if (sigProviders != null) {
        return sigProviders;
    }
    Message m = JAXRSUtils.getCurrentMessage();
    List<JwsSignatureProvider> theSigProviders = new LinkedList<>();
    for (int i = 0; i < propLocs.size(); i++) {
        Properties props = JwsUtils.loadJwsProperties(m, propLocs.get(i));
        theSigProviders.add(JwsUtils.loadSignatureProvider(props, protectedHeaders.get(i)));
    }
    return theSigProviders;
}
 
Example #15
Source File: AbstractJwsWriterProvider.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected JwsSignatureProvider getInitializedSigProvider(JwsHeaders headers) {
    setRequestContextProperty(headers);
    if (sigProvider != null) {
        return sigProvider;
    }
    return JwsUtils.loadSignatureProvider(headers, true);
}
 
Example #16
Source File: AbstractJwsReaderProvider.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected JwsSignatureVerifier getInitializedSigVerifier(JwsHeaders headers) {
    JoseUtils.traceHeaders(headers);
    if (sigVerifier != null) {
        return sigVerifier;
    }
    return JwsUtils.loadSignatureVerifier(headers, true);
}
 
Example #17
Source File: JwtVerifier.java    From deprecated-security-advanced-modules with Apache License 2.0 5 votes vote down vote up
private JwsSignatureVerifier getInitializedSignatureVerifier(JsonWebKey key, JwtToken jwt)
		throws BadCredentialsException, JwtException {

    validateSignatureAlgorithm(key, jwt);
       JwsSignatureVerifier result = JwsUtils.getSignatureVerifier(key, jwt.getJwsHeaders().getSignatureAlgorithm());
	if (result == null) {
		throw new BadCredentialsException("Cannot verify JWT");
	} else {
		return result;
	}
}
 
Example #18
Source File: OAuthServerJoseJwtConsumer.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected JwsSignatureVerifier getInitializedSignatureVerifier(Client c) {
    JwsSignatureVerifier theSignatureVerifier = null;
    if (verifyWithClientCertificates && c != null && !c.getApplicationCertificates().isEmpty()) {
        X509Certificate cert =
            (X509Certificate)CryptoUtils.decodeCertificate(c.getApplicationCertificates().get(0));
        theSignatureVerifier = JwsUtils.getPublicKeySignatureVerifier(cert.getPublicKey(),
                                                                      SignatureAlgorithm.RS256);
    }
    if (theSignatureVerifier == null && c != null && c.getClientSecret() != null) {
        theSignatureVerifier = super.getInitializedSignatureVerifier(c.getClientSecret());
    }
    return theSignatureVerifier;
}
 
Example #19
Source File: JoseSessionTokenProvider.java    From cxf with Apache License 2.0 5 votes vote down vote up
private String protectStateString(String stateString) {
    JwsSignatureProvider jws = getInitializedSigProvider();
    JweEncryptionProvider jwe = getInitializedEncryptionProvider();
    if (jws == null && jwe == null) {
        throw new OAuthServiceException("Session token can not be created");
    }
    if (jws != null) {
        stateString = JwsUtils.sign(jws, stateString, null);
    }
    if (jwe != null) {
        stateString = jwe.encrypt(StringUtils.toBytesUTF8(stateString), null);
    }
    return stateString;
}
 
Example #20
Source File: AuthTokenProcessorHandler.java    From deprecated-security-advanced-modules with Apache License 2.0 5 votes vote down vote up
AuthTokenProcessorHandler(Settings settings, Settings jwtSettings, Saml2SettingsProvider saml2SettingsProvider)
        throws Exception {
    this.saml2SettingsProvider = saml2SettingsProvider;

    this.jwtRolesKey = jwtSettings.get("roles_key", "roles");
    this.jwtSubjectKey = jwtSettings.get("subject_key", "sub");

    this.samlRolesKey = settings.get("roles_key");
    this.samlSubjectKey = settings.get("subject_key");
    this.samlRolesSeparator = settings.get("roles_seperator");
    this.kibanaRootUrl = settings.get("kibana_url");

    if (samlRolesKey == null || samlRolesKey.length() == 0) {
        log.warn("roles_key is not configured, will only extract subject from SAML");
        samlRolesKey = null;
    }

    if (samlSubjectKey == null || samlSubjectKey.length() == 0) {
        // If subjectKey == null, get subject from the NameID element.
        // Thus, this is a valid configuration.
        samlSubjectKey = null;
    }

    if (samlRolesSeparator == null || samlRolesSeparator.length() == 0) {
        samlRolesSeparator = null;
    }

    this.initJwtExpirySettings(settings);
    this.signingKey = this.createJwkFromSettings(settings, jwtSettings);

    this.jwtProducer = new JoseJwtProducer();
    this.jwtProducer.setSignatureProvider(JwsUtils.getSignatureProvider(this.signingKey));

}
 
Example #21
Source File: JoseSessionTokenProvider.java    From cxf with Apache License 2.0 5 votes vote down vote up
private String decryptStateString(String sessionToken) {
    JweDecryptionProvider jwe = getInitializedDecryptionProvider();
    String stateString = jwe.decrypt(sessionToken).getContentText();
    JwsSignatureVerifier jws = getInitializedSigVerifier();
    if (jws != null) {
        stateString = JwsUtils.verify(jws, stateString).getDecodedJwsPayload();
    }
    return stateString;
}
 
Example #22
Source File: JwtRequestCodeFilter.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected JwsSignatureVerifier getInitializedSigVerifier(Client c) {
    if (verifyWithClientCertificates) {
        X509Certificate cert =
            (X509Certificate)CryptoUtils.decodeCertificate(c.getApplicationCertificates().get(0));
        return JwsUtils.getPublicKeySignatureVerifier(cert, SignatureAlgorithm.RS256);
    }
    return super.getInitializedSignatureVerifier(c.getClientSecret());
}
 
Example #23
Source File: DefaultJoseImpl.java    From thorntail with Apache License 2.0 5 votes vote down vote up
private JwsSignatureVerifier getJwsSignatureVerifier(Properties props, JwsHeaders headers) {
    if (config.acceptSignatureAlias()) {
        props.setProperty(JoseConstants.RSSEC_KEY_STORE_ALIAS, headers.getKeyId());
    }

    if (isInlinedJwkSetAvailable()) {
        return JwsUtils.getSignatureVerifier(loadJsonWebKey(verificationKeyAlias()));
    } else {
        return JwsUtils.loadSignatureVerifier(props, headers);
    }
}
 
Example #24
Source File: DefaultJoseImpl.java    From thorntail with Apache License 2.0 5 votes vote down vote up
private JwsSignatureProvider getSignatureProvider(Properties props, JwsHeaders headers) {
    if (isInlinedJwkSetAvailable()) {
        return JwsUtils.getSignatureProvider(loadJsonWebKey(signatureKeyAlias()));
    } else {
        return JwsUtils.loadSignatureProvider(props, headers);
    }
}
 
Example #25
Source File: TestJwts.java    From deprecated-security-advanced-modules with Apache License 2.0 5 votes vote down vote up
static String createSignedWithPeculiarEscaping(JwtToken baseJwt, JsonWebKey jwk) {
	JwsSignatureProvider signatureProvider = JwsUtils.getSignatureProvider(jwk);
	JwsHeaders jwsHeaders = new JwsHeaders();
	JwtToken signedToken = new JwtToken(jwsHeaders, baseJwt.getClaims());

	// Depends on CXF not escaping the input string. This may fail for other frameworks or versions.
	jwsHeaders.setKeyId(jwk.getKeyId().replace("/", "\\/"));

	return new JoseJwtProducer().processJwt(signedToken, null, signatureProvider);
}
 
Example #26
Source File: JoseClientCodeStateManager.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected JwsSignatureProvider getInitializedSigProvider(JweEncryptionProvider theEncryptionProvider) {
    if (sigProvider != null) {
        return sigProvider;
    }
    JwsSignatureProvider theSigProvider = JwsUtils.loadSignatureProvider(false);
    if (theSigProvider == null && theEncryptionProvider != null) {
        theSigProvider = new NoneJwsSignatureProvider();
    }
    return theSigProvider;
}
 
Example #27
Source File: TestJwts.java    From deprecated-security-advanced-modules with Apache License 2.0 4 votes vote down vote up
static String createSignedWithoutKeyId(JwtToken baseJwt, JsonWebKey jwk) {
	JwsHeaders jwsHeaders = new JwsHeaders();
	JwtToken signedToken = new JwtToken(jwsHeaders, baseJwt.getClaims());

	return new JoseJwtProducer().processJwt(signedToken, null, JwsUtils.getSignatureProvider(jwk));
}
 
Example #28
Source File: JwsJoseCookBookTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@Test
public void testMultipleSignatures() throws Exception {
    try {
        Cipher.getInstance(AlgorithmUtils.ES_SHA_512_JAVA);
    } catch (Throwable t) {
        Security.addProvider(new BouncyCastleProvider());
    }
    try {
        JwsJsonProducer jsonProducer = new JwsJsonProducer(PAYLOAD);
        assertEquals(jsonProducer.getPlainPayload(), PAYLOAD);
        assertEquals(jsonProducer.getUnsignedEncodedPayload(), ENCODED_PAYLOAD);
        JwsHeaders firstSignerProtectedHeader = new JwsHeaders();
        firstSignerProtectedHeader.setSignatureAlgorithm(SignatureAlgorithm.RS256);
        JwsHeaders firstSignerUnprotectedHeader = new JwsHeaders();
        firstSignerUnprotectedHeader.setKeyId(RSA_KID_VALUE);
        JsonWebKeys jwks = readKeySet("cookbookPrivateSet.txt");
        List<JsonWebKey> keys = jwks.getKeys();
        JsonWebKey rsaKey = keys.get(1);
        jsonProducer.signWith(JwsUtils.getSignatureProvider(rsaKey, SignatureAlgorithm.RS256),
                firstSignerProtectedHeader, firstSignerUnprotectedHeader);
        assertEquals(jsonProducer.getSignatureEntries().get(0).toJson(),
                FIRST_SIGNATURE_ENTRY_MULTIPLE_SIGNATURES);

        JwsHeaders secondSignerUnprotectedHeader = new JwsHeaders();
        secondSignerUnprotectedHeader.setSignatureAlgorithm(SignatureAlgorithm.ES512);
        secondSignerUnprotectedHeader.setKeyId(ECDSA_KID_VALUE);
        JsonWebKey ecKey = keys.get(0);
        jsonProducer.signWith(JwsUtils.getSignatureProvider(ecKey, SignatureAlgorithm.ES512),
                null, secondSignerUnprotectedHeader);
        assertEquals(new JsonMapObjectReaderWriter().toJson(
            jsonProducer.getSignatureEntries().get(1).getUnprotectedHeader()),
                SECOND_SIGNATURE_UNPROTECTED_HEADER_MULTIPLE_SIGNATURES);
        assertEquals(jsonProducer.getSignatureEntries().get(1).toJson().length(),
                SECOND_SIGNATURE_ENTRY_MULTIPLE_SIGNATURES.length());

        JwsHeaders thirdSignerProtectedHeader = new JwsHeaders();
        thirdSignerProtectedHeader.setSignatureAlgorithm(SignatureAlgorithm.HS256);
        thirdSignerProtectedHeader.setKeyId(HMAC_KID_VALUE);
        JsonWebKeys secretJwks = readKeySet("cookbookSecretSet.txt");
        List<JsonWebKey> secretKeys = secretJwks.getKeys();
        JsonWebKey hmacKey = secretKeys.get(0);
        jsonProducer.signWith(JwsUtils.getSignatureProvider(hmacKey, SignatureAlgorithm.HS256),
                thirdSignerProtectedHeader);
        assertEquals(jsonProducer.getSignatureEntries().get(2).toJson(),
                THIRD_SIGNATURE_ENTRY_MULTIPLE_SIGNATURES);
        assertEquals(jsonProducer.getJwsJsonSignedDocument().length(),
                MULTIPLE_SIGNATURES_JSON_GENERAL_SERIALIZATION.length());
        JwsJsonConsumer jsonConsumer =
                new JwsJsonConsumer(jsonProducer.getJwsJsonSignedDocument());
        JsonWebKeys publicJwks = readKeySet("cookbookPublicSet.txt");
        List<JsonWebKey> publicKeys = publicJwks.getKeys();
        JsonWebKey rsaPublicKey = publicKeys.get(1);
        JsonWebKey ecPublicKey = publicKeys.get(0);
        assertTrue(jsonConsumer.verifySignatureWith(rsaPublicKey, SignatureAlgorithm.RS256));
        assertTrue(jsonConsumer.verifySignatureWith(ecPublicKey, SignatureAlgorithm.ES512));
        assertTrue(jsonConsumer.verifySignatureWith(hmacKey, SignatureAlgorithm.HS256));
    } finally {
        Security.removeProvider(BouncyCastleProvider.PROVIDER_NAME);
    }
}
 
Example #29
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 #30
Source File: IdTokenResponseFilter.java    From cxf with Apache License 2.0 4 votes vote down vote up
private void setAtHashAndNonce(IdToken idToken, ServerAccessToken st) {
    String rType = st.getResponseType();
    boolean atHashRequired = idToken.getAccessTokenHash() == null
        && (rType == null || !rType.equals(OidcUtils.ID_TOKEN_RESPONSE_TYPE));
    boolean cHashRequired = idToken.getAuthorizationCodeHash() == null
        && rType != null
        && (rType.equals(OidcUtils.CODE_ID_TOKEN_AT_RESPONSE_TYPE)
            || rType.equals(OidcUtils.CODE_ID_TOKEN_RESPONSE_TYPE));

    Message m = JAXRSUtils.getCurrentMessage();
    if (atHashRequired || cHashRequired) {
        Properties props = JwsUtils.loadSignatureOutProperties(false);
        final SignatureAlgorithm sigAlgo;
        if (super.isSignWithClientSecret()) {
            sigAlgo = OAuthUtils.getClientSecretSignatureAlgorithm(props);
        } else {
            sigAlgo = JwsUtils.getSignatureAlgorithm(props, SignatureAlgorithm.RS256);
        }
        if (sigAlgo != SignatureAlgorithm.NONE) {
            if (atHashRequired) {
                String tokenKey = st.getEncodedToken() != null ? st.getEncodedToken() : st.getTokenKey();
                String atHash = OidcUtils.calculateAccessTokenHash(tokenKey, sigAlgo);
                idToken.setAccessTokenHash(atHash);
            }
            if (cHashRequired) {
                // c_hash can be returned from either Authorization or Token endpoints
                String code;
                if (st.getGrantCode() != null) {
                    // This is a token endpoint, the code has been exchanged for a token
                    code = st.getGrantCode();
                } else {
                    // Authorization endpoint: hybrid flow, implicit part
                    code = (String)m.getExchange().get(OAuthConstants.AUTHORIZATION_CODE_VALUE);
                }
                if (code != null) {
                    idToken.setAuthorizationCodeHash(OidcUtils.calculateAuthorizationCodeHash(code, sigAlgo));
                }
            }
        }
    }

    if (m != null && m.getExchange().containsKey(OAuthConstants.NONCE)) {
        idToken.setNonce((String)m.getExchange().get(OAuthConstants.NONCE));
    } else if (st.getNonce() != null) {
        idToken.setNonce(st.getNonce());
    }

}