org.opensaml.xmlsec.signature.Signature Java Examples

The following examples show how to use org.opensaml.xmlsec.signature.Signature. 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: SamlMessageUtil.java    From armeria with Apache License 2.0 6 votes vote down vote up
static void validateSignature(Credential validationCredential, SignableSAMLObject signableObj) {
    requireNonNull(validationCredential, "validationCredential");
    requireNonNull(signableObj, "signableObj");

    // Skip signature validation if the object is not signed.
    if (!signableObj.isSigned()) {
        return;
    }

    final Signature signature = signableObj.getSignature();
    if (signature == null) {
        throw new InvalidSamlRequestException("failed to validate a signature because no signature exists");
    }

    try {
        signatureProfileValidator.validate(signature);
        SignatureValidator.validate(signature, validationCredential);
    } catch (SignatureException e) {
        throw new InvalidSamlRequestException("failed to validate a signature", e);
    }
}
 
Example #2
Source File: SamlClientTest.java    From saml-client with MIT License 6 votes vote down vote up
/**
 * Decode and validate saml logout response with valid signature.
 *
 * @throws Throwable the throwable
 */
@Test
public void decodeAndValidateSamlLogoutResponseWithValidSignature() throws Throwable {
  /*
   * To avoid annoying code test, the IDP and the SP have the same public key
   */
  //Retrieve the saml client
  SamlClient client = getKeyCloakClient(true);
  //Retrieve the new encoded logout response
  String encodedLogoutResponse = client.getSamlLogoutResponse(StatusCode.SUCCESS);
  //Decode the encoded logout response to check it is signed
  String decodedResponse = decode(encodedLogoutResponse);
  assertTrue(decodedResponse.contains(Signature.DEFAULT_ELEMENT_LOCAL_NAME));
  //Decode and valid the logout response
  SamlLogoutResponse logoutResponse =
      decodeAndValidateSamlLogoutResponse(encodedLogoutResponse, "POST");
  assertTrue(logoutResponse.isValid());
}
 
Example #3
Source File: ValidatorUtils.java    From saml-client with MIT License 6 votes vote down vote up
/**
 * Validate boolean.
 *
 * @param signature   the signature
 * @param credentials the credentials
 * @return the boolean
 */
private static boolean validate(Signature signature, List<Credential> credentials) {
  if (signature == null) {
    return false;
  }

  // It's fine if any of the credentials match the signature
  return credentials
      .stream()
      .anyMatch(
          credential -> {
            try {
              SignatureValidator.validate(signature, credential);
              return true;
            } catch (SignatureException ex) {
              return false;
            }
          });
}
 
Example #4
Source File: MockMetadataAggregatorServer.java    From verify-service-provider with MIT License 6 votes vote down vote up
private String buildTestCountryEntityDescriptor(String countryEntityId) throws Exception {
    KeyDescriptor signingKeyDescriptor = KeyDescriptorBuilder.aKeyDescriptor()
        .withX509ForSigning(STUB_COUNTRY_PUBLIC_PRIMARY_CERT)
        .build();

    IDPSSODescriptor idpSsoDescriptor = IdpSsoDescriptorBuilder.anIdpSsoDescriptor()
        .withoutDefaultSigningKey()
        .addKeyDescriptor(signingKeyDescriptor)
        .build();

    Signature signature = SignatureBuilder.aSignature()
        .withSigningCredential(new TestCredentialFactory(METADATA_SIGNING_A_PUBLIC_CERT, METADATA_SIGNING_A_PRIVATE_KEY).getSigningCredential())
        .withX509Data(METADATA_SIGNING_A_PUBLIC_CERT)
        .build();

    EntityDescriptor entityDescriptor = EntityDescriptorBuilder.anEntityDescriptor()
        .withEntityId(countryEntityId)
        .withIdpSsoDescriptor(idpSsoDescriptor)
        .setAddDefaultSpServiceDescriptor(false)
        .withValidUntil(DateTime.now().plusWeeks(2))
        .withSignature(signature)
        .build();

    String s = new MetadataFactory().singleEntityMetadata(entityDescriptor);
    return s;
}
 
Example #5
Source File: AuthnRequestFactory.java    From verify-service-provider with MIT License 5 votes vote down vote up
private Signature createSignature() {
    IdaKeyStore keyStore = new IdaKeyStore(signingKeyPair, Collections.emptyList());
    IdaKeyStoreCredentialRetriever keyStoreCredentialRetriever = new IdaKeyStoreCredentialRetriever(keyStore);
    SignatureRSASHA256 signatureAlgorithm = new SignatureRSASHA256();
    DigestSHA256 digestAlgorithm = new DigestSHA256();
    SignatureFactory signatureFactory = new SignatureFactory(keyStoreCredentialRetriever, signatureAlgorithm, digestAlgorithm);
    return signatureFactory.createSignature();
}
 
Example #6
Source File: AuthnRequestParser.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
private void validateSeparateSignature(Idp idp, String sigAlg, String signature, String relayState,
                                       String samlRequest, String realm) throws Exception {
    // Check signature
    X509Certificate validatingCert = getValidatingCertificate(idp, realm);

    // Process the received SigAlg parameter - fall back to RSA SHA1
    String processedSigAlg = null;
    if (sigAlg != null && SIG_ALGS.contains(sigAlg)) {
        processedSigAlg = sigAlg;
    } else {
        LOG.debug("Supplied SigAlg parameter is either null or not known, so falling back to use RSA-SHA1");
        processedSigAlg = SSOConstants.RSA_SHA1;
    }

    java.security.Signature sig =
        java.security.Signature.getInstance(JCEMapper.translateURItoJCEID(processedSigAlg));
    sig.initVerify(validatingCert);

    // Recreate request to sign
    String requestToSign =
            SSOConstants.SAML_REQUEST + "=" + URLEncoder.encode(samlRequest, StandardCharsets.UTF_8.name())
            + "&" + SSOConstants.RELAY_STATE + "=" + URLEncoder.encode(relayState, StandardCharsets.UTF_8.name())
            + "&" + SSOConstants.SIG_ALG + "=" + URLEncoder.encode(processedSigAlg, StandardCharsets.UTF_8.name());

    sig.update(requestToSign.getBytes(StandardCharsets.UTF_8));

    if (!sig.verify(Base64.getDecoder().decode(signature))) {
        LOG.debug("Signature validation failed");
        throw new ProcessingException(TYPE.BAD_REQUEST);
    }
}
 
Example #7
Source File: IdpTest.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
private static void signAuthnRequest(SignableSAMLObject signableObject) throws Exception {
    Crypto crypto = CryptoFactory.getInstance("stsKeystoreA.properties");

    CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS);
    cryptoType.setAlias("realma");
    X509Certificate[] issuerCerts = crypto.getX509Certificates(cryptoType);

    String sigAlgo = SSOConstants.RSA_SHA1;

    // Get the private key
    PrivateKey privateKey = crypto.getPrivateKey("realma", "realma");

    // Create the signature
    Signature signature = OpenSAMLUtil.buildSignature();
    signature.setCanonicalizationAlgorithm(SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);
    signature.setSignatureAlgorithm(sigAlgo);

    BasicX509Credential signingCredential = new BasicX509Credential(issuerCerts[0], privateKey);

    signature.setSigningCredential(signingCredential);

    X509KeyInfoGeneratorFactory kiFactory = new X509KeyInfoGeneratorFactory();
    kiFactory.setEmitEntityCertificate(true);

    try {
        KeyInfo keyInfo = kiFactory.newInstance().generate(signingCredential);
        signature.setKeyInfo(keyInfo);
    } catch (org.opensaml.security.SecurityException ex) {
        throw new Exception(
                "Error generating KeyInfo from signing credential", ex);
    }

    signableObject.setSignature(signature);
    signableObject.releaseDOM();
    signableObject.releaseChildrenDOM(true);

}
 
Example #8
Source File: ValidatorUtils.java    From saml-client with MIT License 5 votes vote down vote up
/**
 * Validate assertion signature.
 *
 * @param response    the response
 * @param credentials the credentials
 * @throws SamlException the saml exception
 */
private static void validateAssertionSignature(Response response, List<Credential> credentials)
    throws SamlException {
  Signature assertionSignature = response.getAssertions().get(0).getSignature();

  if (response.getSignature() == null && assertionSignature == null) {
    throw new SamlException("No signature is present in either response or assertion");
  }

  if (assertionSignature != null && !validate(assertionSignature, credentials)) {
    throw new SamlException("The assertion signature is invalid");
  }
}
 
Example #9
Source File: SamlClient.java    From saml-client with MIT License 5 votes vote down vote up
/** Sign a SamlObject with default settings.
 * Note that this method is a no-op if spCredential is unset.
 * @param samlObject The object to sign
 *
 * @throws SamlException if {@link SignatureSupport#signObject(SignableXMLObject, SignatureSigningParameters) signObject} fails
 * */
private void signSAMLObject(SignableSAMLObject samlObject) throws SamlException {
  if (spCredential != null) {
    try {
      // Describe how we're going to sign the request
      SignatureBuilder signer = new SignatureBuilder();
      Signature signature = signer.buildObject(Signature.DEFAULT_ELEMENT_NAME);
      signature.setCanonicalizationAlgorithm(SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);
      signature.setSignatureAlgorithm(SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA256);
      signature.setKeyInfo(
          new X509KeyInfoGeneratorFactory().newInstance().generate(spCredential));
      signature.setSigningCredential(spCredential);
      samlObject.setSignature(signature);

      // Actually sign the request
      SignatureSigningParameters signingParameters = new SignatureSigningParameters();
      signingParameters.setSigningCredential(spCredential);
      signingParameters.setSignatureCanonicalizationAlgorithm(
          SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);
      signingParameters.setSignatureAlgorithm(SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA256);
      signingParameters.setKeyInfoGenerator(new X509KeyInfoGeneratorFactory().newInstance());
      SignatureSupport.signObject(samlObject, signingParameters);
    } catch (SecurityException | MarshallingException | SignatureException e) {
      throw new SamlException("Failed to sign request", e);
    }
  }
}
 
Example #10
Source File: VerifyAssertionTranslatorTest.java    From verify-service-provider with MIT License 5 votes vote down vote up
private static AssertionBuilder aMatchingDatasetAssertionWithSignature(List<Attribute> attributes, Signature signature, String requestId) {
    return anAssertion()
            .withId("mds-assertion")
            .withIssuer(anIssuer().withIssuerId(STUB_IDP_ONE).build())
            .withSubject(anAssertionSubject(requestId))
            .withSignature(signature)
            .addAttributeStatement(anAttributeStatement().addAllAttributes(attributes).build())
            .withConditions(aConditions().build());
}
 
Example #11
Source File: AssertionHelper.java    From verify-service-provider with MIT License 5 votes vote down vote up
public static Signature aHubSignature() {
    return aSignature()
            .withSigningCredential(
                    new TestCredentialFactory(
                            HUB_TEST_PUBLIC_SIGNING_CERT,
                            HUB_TEST_PRIVATE_SIGNING_KEY
                    ).getSigningCredential()
            ).build();
}
 
Example #12
Source File: AssertionHelper.java    From verify-service-provider with MIT License 5 votes vote down vote up
public static Signature anIdpSignature() {
    return aSignature()
            .withSigningCredential(
                    new TestCredentialFactory(
                            STUB_IDP_PUBLIC_PRIMARY_CERT,
                            STUB_IDP_PUBLIC_PRIMARY_PRIVATE_KEY
                    ).getSigningCredential()
            ).build();
}
 
Example #13
Source File: AssertionHelper.java    From verify-service-provider with MIT License 5 votes vote down vote up
public static Signature anEidasSignature() {
    return aSignature()
            .withSigningCredential(
                    new TestCredentialFactory(
                            STUB_COUNTRY_PUBLIC_PRIMARY_CERT,
                            STUB_COUNTRY_PUBLIC_PRIMARY_PRIVATE_KEY
                    ).getSigningCredential()
            ).build();
}
 
Example #14
Source File: AssertionHelper.java    From verify-service-provider with MIT License 5 votes vote down vote up
public static EncryptedAssertion anEidasEncryptedAssertion(String requestId,
                                                           String issuerId,
                                                           Signature assertionSignature,
                                                           AttributeStatement attributeStatement,
                                                           boolean shouldSign,
                                                           String encryptionAlgorithm)
{
    AssertionBuilder assertionBuilder = anAssertion()
            .withSubject(
                    aSubject().withSubjectConfirmation(
                            aSubjectConfirmation().withSubjectConfirmationData(
                                    aSubjectConfirmationData()
                                            .withInResponseTo(requestId)
                                            .build())
                                    .build())
                            .build())
            .withIssuer(
                    anIssuer()
                            .withIssuerId(issuerId)
                            .build())
            .addAttributeStatement(attributeStatement)
            .addAuthnStatement(anEidasAuthnStatement().build())
            .withConditions(aConditionsForEidas());

    if (shouldSign) {
        assertionBuilder.withSignature(assertionSignature);
    } else {
        assertionBuilder.withoutSigning();
        assertionBuilder.withSignature(null);
    }

    return assertionBuilder.buildWithEncrypterCredential(
            new TestCredentialFactory(
                    TEST_RP_PUBLIC_ENCRYPTION_CERT,
                    TEST_RP_PRIVATE_ENCRYPTION_KEY
            ).getEncryptingCredential(),
            encryptionAlgorithm
    );
}
 
Example #15
Source File: AssertionHelper.java    From verify-service-provider with MIT License 5 votes vote down vote up
public static EncryptedAssertion anEidasEncryptedAssertion(String requestId,
                                                           String issuerId,
                                                           Signature assertionSignature,
                                                           AttributeStatement attributeStatement) {
    return anEidasEncryptedAssertion(
            requestId,
            issuerId,
            assertionSignature,
            attributeStatement,
            true,
            EncryptionConstants.ALGO_ID_BLOCKCIPHER_AES128
    );
}
 
Example #16
Source File: AssertionHelper.java    From verify-service-provider with MIT License 5 votes vote down vote up
public static EncryptedAssertion anUnsignedEidasEncryptedAssertion(String requestId,
                                                                   String issuerId,
                                                                   Signature assertionSignature) {
    return anEidasEncryptedAssertion(
            requestId,
            issuerId,
            assertionSignature,
            anEidasAttributeStatement().build(),
            false,
            EncryptionConstants.ALGO_ID_BLOCKCIPHER_AES128_GCM
    );
}
 
Example #17
Source File: MockSamlIdpServer.java    From deprecated-security-advanced-modules with Apache License 2.0 5 votes vote down vote up
private String createSamlAuthResponse(AuthnRequest authnRequest) {
    try {
        Response response = createSamlElement(Response.class);
        response.setID(nextId());

        if (authnRequest != null) {
            response.setInResponseTo(authnRequest.getID());
        }

        response.setVersion(SAMLVersion.VERSION_20);
        response.setStatus(createStatus(StatusCode.SUCCESS));
        response.setIssueInstant(new DateTime());

        Assertion assertion = createSamlElement(Assertion.class);
        response.getAssertions().add(assertion);

        assertion.setID(nextId());
        assertion.setIssueInstant(new DateTime());
        assertion.setIssuer(createIssuer());

        AuthnStatement authnStatement = createSamlElement(AuthnStatement.class);
        assertion.getAuthnStatements().add(authnStatement);

        authnStatement.setAuthnInstant(new DateTime());
        authnStatement.setSessionIndex(nextId());
        authnStatement.setAuthnContext(createAuthnCotext());

        Subject subject = createSamlElement(Subject.class);
        assertion.setSubject(subject);

        subject.setNameID(createNameID(NameIDType.UNSPECIFIED, authenticateUser));

        if (authnRequest != null) {
            subject.getSubjectConfirmations()
                    .add(createSubjectConfirmation("urn:oasis:names:tc:SAML:2.0:cm:bearer",
                            new DateTime().plusMinutes(1), authnRequest.getID(),
                            authnRequest.getAssertionConsumerServiceURL()));
        } else {
            subject.getSubjectConfirmations().add(createSubjectConfirmation("urn:oasis:names:tc:SAML:2.0:cm:bearer",
                    new DateTime().plusMinutes(1), null, defaultAssertionConsumerService));
        }

        Conditions conditions = createSamlElement(Conditions.class);
        assertion.setConditions(conditions);

        conditions.setNotBefore(new DateTime());
        conditions.setNotOnOrAfter(new DateTime().plusMinutes(1));

        if (authenticateUserRoles != null) {
            AttributeStatement attributeStatement = createSamlElement(AttributeStatement.class);
            assertion.getAttributeStatements().add(attributeStatement);

            Attribute attribute = createSamlElement(Attribute.class);
            attributeStatement.getAttributes().add(attribute);

            attribute.setName("roles");
            attribute.setNameFormat("urn:oasis:names:tc:SAML:2.0:attrname-format:basic");

            for (String role : authenticateUserRoles) {
                attribute.getAttributeValues().add(createXSAny(AttributeValue.DEFAULT_ELEMENT_NAME, role));
            }
        }

        if (signResponses) {
            Signature signature = createSamlElement(Signature.class);
            assertion.setSignature(signature);

            signature.setSigningCredential(this.signingCredential);
            signature.setSignatureAlgorithm(SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA1);
            signature.setCanonicalizationAlgorithm(SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);

            XMLObjectProviderRegistrySupport.getMarshallerFactory().getMarshaller(assertion).marshall(assertion);

            Signer.signObject(signature);
        }

        String marshalledXml = marshallSamlXml(response);

        return Base64Support.encode(marshalledXml.getBytes("UTF-8"), Base64Support.UNCHUNKED);

    } catch (MarshallingException | SignatureException | UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
}
 
Example #18
Source File: HubMetadataFeatureTest.java    From verify-service-provider with MIT License 5 votes vote down vote up
@Test
public void shouldFailHealthcheckWhenHubMetadataIsSignedWithMD5() {
    String id = UUID.randomUUID().toString();
    Signature signature = SignatureBuilder.aSignature()
        .withDigestAlgorithm(id, new DigestMD5())
        .withX509Data(TestCertificateStrings.METADATA_SIGNING_A_PUBLIC_CERT)
        .withSigningCredential(new TestCredentialFactory(TestCertificateStrings.METADATA_SIGNING_A_PUBLIC_CERT,
                TestCertificateStrings.METADATA_SIGNING_A_PRIVATE_KEY).getSigningCredential()).build();
    String metadata = new MetadataFactory().metadata(new EntitiesDescriptorFactory().signedEntitiesDescriptor(id, signature));

    wireMockServer.stubFor(
            get(urlEqualTo("/SAML2/metadata"))
                    .willReturn(
                            aResponse()
                                    .withStatus(200)
                                    .withBody(metadata)
                    )
    );

    applicationTestSupport.before();
    Client client = new JerseyClientBuilder(applicationTestSupport.getEnvironment()).build("test client");

    Response response = client
        .target(URI.create(format(HEALTHCHECK_URL, applicationTestSupport.getLocalPort())))
        .request()
        .buildGet()
        .invoke();

    String expectedResult = format("\"%s\":{\"healthy\":false", getHubMetadataUrl());

    wireMockServer.verify(getRequestedFor(urlEqualTo("/SAML2/metadata")));

    assertThat(response.getStatus()).isEqualTo(INTERNAL_SERVER_ERROR.getStatusCode());
    assertThat(response.readEntity(String.class)).contains(expectedResult);
}
 
Example #19
Source File: SAMLProtocolResponseValidator.java    From cxf with Apache License 2.0 4 votes vote down vote up
/**
 * Validate an internal Assertion
 */
private void validateAssertion(
    SamlAssertionWrapper assertion,
    Crypto sigCrypto,
    CallbackHandler callbackHandler,
    Document doc,
    boolean signedResponse
) throws WSSecurityException {
    Credential credential = new Credential();
    credential.setSamlAssertion(assertion);

    RequestData requestData = new RequestData();
    requestData.setSigVerCrypto(sigCrypto);
    WSSConfig wssConfig = WSSConfig.getNewInstance();
    requestData.setWssConfig(wssConfig);
    requestData.setCallbackHandler(callbackHandler);

    if (assertion.isSigned()) {
        if (assertion.getSaml1() != null) {
            assertion.getSaml1().getDOM().setIdAttributeNS(null, "AssertionID", true);
        } else {
            assertion.getSaml2().getDOM().setIdAttributeNS(null, "ID", true);
        }

        // Verify the signature
        try {
            Signature sig = assertion.getSignature();
            WSDocInfo docInfo = new WSDocInfo(sig.getDOM().getOwnerDocument());
            requestData.setWsDocInfo(docInfo);

            SAMLKeyInfo samlKeyInfo = null;

            KeyInfo keyInfo = sig.getKeyInfo();
            if (keyInfo != null) {
                samlKeyInfo = SAMLUtil.getCredentialFromKeyInfo(
                    keyInfo.getDOM(), new WSSSAMLKeyInfoProcessor(requestData), sigCrypto
                );
            } else if (!keyInfoMustBeAvailable) {
                samlKeyInfo = createKeyInfoFromDefaultAlias(sigCrypto);
            }

            if (samlKeyInfo == null) {
                LOG.warning("No KeyInfo supplied in the SAMLResponse assertion signature");
                throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
            }

            assertion.verifySignature(samlKeyInfo);

            assertion.parseSubject(
                new WSSSAMLKeyInfoProcessor(requestData),
                requestData.getSigVerCrypto(),
                requestData.getCallbackHandler()
            );
        } catch (WSSecurityException e) {
            LOG.log(Level.FINE, "Assertion failed signature validation", e);
            throw e;
        }
    }

    // Validate the Assertion & verify trust in the signature
    try {
        SamlSSOAssertionValidator assertionValidator = new SamlSSOAssertionValidator(signedResponse);
        assertionValidator.validate(credential, requestData);
    } catch (WSSecurityException ex) {
        LOG.log(Level.FINE, "Assertion validation failed: " + ex.getMessage(), ex);
        throw ex;
    }
}
 
Example #20
Source File: AuthnRequestParser.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
/**
 * Validate the AuthnRequest or LogoutRequest signature
 */
private void validateRequestSignature(
    Signature signature,
    Crypto sigCrypto
) throws WSSecurityException {
    RequestData requestData = new RequestData();
    requestData.setSigVerCrypto(sigCrypto);
    WSSConfig wssConfig = WSSConfig.getNewInstance();
    requestData.setWssConfig(wssConfig);
    // requestData.setCallbackHandler(callbackHandler);

    SAMLKeyInfo samlKeyInfo = null;

    KeyInfo keyInfo = signature.getKeyInfo();
    if (keyInfo != null) {
        try {
            Document doc = signature.getDOM().getOwnerDocument();
            requestData.setWsDocInfo(new WSDocInfo(doc));
            samlKeyInfo =
                SAMLUtil.getCredentialFromKeyInfo(
                    keyInfo.getDOM(), new WSSSAMLKeyInfoProcessor(requestData), sigCrypto
                );
        } catch (WSSecurityException ex) {
            LOG.debug("Error in getting KeyInfo from SAML AuthnRequest: {}", ex.getMessage(), ex);
            throw ex;
        }
    }

    if (samlKeyInfo == null) {
        LOG.debug("No KeyInfo supplied in the AuthnRequest signature");
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
    }

    // Validate Signature against profiles
    validateSignatureAgainstProfiles(signature, samlKeyInfo);

    // Now verify trust on the signature
    Credential trustCredential = new Credential();
    trustCredential.setPublicKey(samlKeyInfo.getPublicKey());
    trustCredential.setCertificates(samlKeyInfo.getCerts());

    try {
        Validator signatureValidator = new SignatureTrustValidator();
        signatureValidator.validate(trustCredential, requestData);
    } catch (WSSecurityException e) {
        LOG.debug("Error in validating signature on SAML AuthnRequest: {}", e.getMessage(), e);
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
    }
}
 
Example #21
Source File: AssertionHelper.java    From verify-service-provider with MIT License 4 votes vote down vote up
public static EncryptedAssertion anEidasEncryptedAssertion(String requestId, String issuerId, Signature assertionSignature) {
    return anEidasEncryptedAssertion(requestId, issuerId, assertionSignature, anEidasAttributeStatement().build());
}
 
Example #22
Source File: IdpTest.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testSeparateSignatureWrongSignedContent() throws Exception {
    OpenSAMLUtil.initSamlEngine();

    // Create SAML AuthnRequest
    String consumerURL = "https://localhost:" + getRpHttpsPort() + "/"
        + getServletContextName() + "/secure/fedservlet";
    AuthnRequest authnRequest =
        new DefaultAuthnRequestBuilder().createAuthnRequest(
            null, "urn:org:apache:cxf:fediz:fedizhelloworld", consumerURL
        );
    authnRequest.setDestination("https://localhost:" + getIdpHttpsPort() + "/fediz-idp/saml");

    String authnRequestEncoded = encodeAuthnRequest(authnRequest);

    String urlEncodedRequest = URLEncoder.encode(authnRequestEncoded, UTF_8.name());

    String relayState = UUID.randomUUID().toString();

    // Sign request
    Crypto crypto = CryptoFactory.getInstance("stsKeystoreA.properties");

    CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS);
    cryptoType.setAlias("realma");

    // Get the private key
    PrivateKey privateKey = crypto.getPrivateKey("realma", "realma");

    java.security.Signature signature = java.security.Signature.getInstance("SHA1withRSA");
    signature.initSign(privateKey);

    String requestToSign = SSOConstants.SAML_REQUEST + "=" + urlEncodedRequest
            + "&" + SSOConstants.RELAY_STATE + "=" + relayState
            + "&" + SSOConstants.SIG_ALG + "=" + URLEncoder.encode(SSOConstants.RSA_SHA1, UTF_8.name()) + "asf=xyz";

    signature.update(requestToSign.getBytes(UTF_8));
    byte[] signBytes = signature.sign();

    String encodedSignature = Base64.getEncoder().encodeToString(signBytes);

    String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/saml/up?"
            + SSOConstants.RELAY_STATE + "=" + relayState
            + "&" + SSOConstants.SAML_REQUEST + "=" + urlEncodedRequest
            + "&" + SSOConstants.SIGNATURE + "=" + URLEncoder.encode(encodedSignature, UTF_8.name());

    final WebClient webClient = new WebClient();
    webClient.getOptions().setUseInsecureSSL(true);
    webClient.getCredentialsProvider().setCredentials(
        new AuthScope("localhost", Integer.parseInt(getIdpHttpsPort())),
        new UsernamePasswordCredentials(USER, PWD));

    webClient.getOptions().setJavaScriptEnabled(false);
    final HtmlPage idpPage = webClient.getPage(url);

    org.opensaml.saml.saml2.core.Response samlResponse =
        parseSAMLResponse(idpPage, relayState, consumerURL, authnRequest.getID());
    String expected = "urn:oasis:names:tc:SAML:2.0:status:Requester";
    Assert.assertEquals(expected, samlResponse.getStatus().getStatusCode().getValue());

    webClient.close();
}
 
Example #23
Source File: IdpTest.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testChangedSeparateSignature() throws Exception {
    OpenSAMLUtil.initSamlEngine();

    // Create SAML AuthnRequest
    String consumerURL = "https://localhost:" + getRpHttpsPort() + "/"
        + getServletContextName() + "/secure/fedservlet";
    AuthnRequest authnRequest =
        new DefaultAuthnRequestBuilder().createAuthnRequest(
            null, "urn:org:apache:cxf:fediz:fedizhelloworld", consumerURL
        );
    authnRequest.setDestination("https://localhost:" + getIdpHttpsPort() + "/fediz-idp/saml");

    String authnRequestEncoded = encodeAuthnRequest(authnRequest);

    String urlEncodedRequest = URLEncoder.encode(authnRequestEncoded, UTF_8.name());

    String relayState = UUID.randomUUID().toString();

    // Sign request
    Crypto crypto = CryptoFactory.getInstance("stsKeystoreA.properties");

    CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS);
    cryptoType.setAlias("realma");

    // Get the private key
    PrivateKey privateKey = crypto.getPrivateKey("realma", "realma");

    java.security.Signature signature = java.security.Signature.getInstance("SHA1withRSA");
    signature.initSign(privateKey);

    String requestToSign = SSOConstants.SAML_REQUEST + "=" + urlEncodedRequest
            + "&" + SSOConstants.RELAY_STATE + "=" + relayState
            + "&" + SSOConstants.SIG_ALG + "=" + URLEncoder.encode(SSOConstants.RSA_SHA1, UTF_8.name());

    signature.update(requestToSign.getBytes(UTF_8));
    byte[] signBytes = signature.sign();
    if (signBytes[1] != (byte)1) {
        signBytes[1] = (byte)1;
    } else {
        signBytes[1] = (byte)2;
    }

    String encodedSignature = Base64.getEncoder().encodeToString(signBytes);

    String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/saml/up?"
            + SSOConstants.RELAY_STATE + "=" + relayState
            + "&" + SSOConstants.SAML_REQUEST + "=" + urlEncodedRequest
            + "&" + SSOConstants.SIGNATURE + "=" + URLEncoder.encode(encodedSignature, UTF_8.name());

    final WebClient webClient = new WebClient();
    webClient.getOptions().setUseInsecureSSL(true);
    webClient.getCredentialsProvider().setCredentials(
        new AuthScope("localhost", Integer.parseInt(getIdpHttpsPort())),
        new UsernamePasswordCredentials(USER, PWD));

    webClient.getOptions().setJavaScriptEnabled(false);
    final HtmlPage idpPage = webClient.getPage(url);

    org.opensaml.saml.saml2.core.Response samlResponse =
        parseSAMLResponse(idpPage, relayState, consumerURL, authnRequest.getID());
    String expected = "urn:oasis:names:tc:SAML:2.0:status:Requester";
    Assert.assertEquals(expected, samlResponse.getStatus().getStatusCode().getValue());

    webClient.close();
}
 
Example #24
Source File: IdpTest.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testBase64DecodingErrorSeparateSignature() throws Exception {
    OpenSAMLUtil.initSamlEngine();

    // Create SAML AuthnRequest
    String consumerURL = "https://localhost:" + getRpHttpsPort() + "/"
        + getServletContextName() + "/secure/fedservlet";
    AuthnRequest authnRequest =
        new DefaultAuthnRequestBuilder().createAuthnRequest(
            null, "urn:org:apache:cxf:fediz:fedizhelloworld", consumerURL
        );
    authnRequest.setDestination("https://localhost:" + getIdpHttpsPort() + "/fediz-idp/saml");

    String authnRequestEncoded = encodeAuthnRequest(authnRequest);

    String urlEncodedRequest = URLEncoder.encode(authnRequestEncoded, UTF_8.name());

    String relayState = UUID.randomUUID().toString();

    // Sign request
    Crypto crypto = CryptoFactory.getInstance("stsKeystoreA.properties");

    CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS);
    cryptoType.setAlias("realma");

    // Get the private key
    PrivateKey privateKey = crypto.getPrivateKey("realma", "realma");

    java.security.Signature signature = java.security.Signature.getInstance("SHA1withRSA");
    signature.initSign(privateKey);

    String requestToSign = SSOConstants.SAML_REQUEST + "=" + urlEncodedRequest
            + "&" + SSOConstants.RELAY_STATE + "=" + relayState
            + "&" + SSOConstants.SIG_ALG + "=" + URLEncoder.encode(SSOConstants.RSA_SHA1, UTF_8.name());

    signature.update(requestToSign.getBytes(UTF_8));
    byte[] signBytes = signature.sign();

    String encodedSignature = Base64.getEncoder().encodeToString(signBytes);

    String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/saml/up?"
            + SSOConstants.RELAY_STATE + "=" + relayState
            + "&" + SSOConstants.SAML_REQUEST + "=" + urlEncodedRequest
            + "&" + SSOConstants.SIGNATURE + "=" + URLEncoder.encode(encodedSignature, UTF_8.name()) + "-xyz";

    final WebClient webClient = new WebClient();
    webClient.getOptions().setUseInsecureSSL(true);
    webClient.getCredentialsProvider().setCredentials(
        new AuthScope("localhost", Integer.parseInt(getIdpHttpsPort())),
        new UsernamePasswordCredentials(USER, PWD));

    webClient.getOptions().setJavaScriptEnabled(false);
    final HtmlPage idpPage = webClient.getPage(url);

    org.opensaml.saml.saml2.core.Response samlResponse =
        parseSAMLResponse(idpPage, relayState, consumerURL, authnRequest.getID());
    String expected = "urn:oasis:names:tc:SAML:2.0:status:Requester";
    Assert.assertEquals(expected, samlResponse.getStatus().getStatusCode().getValue());

    webClient.close();
}
 
Example #25
Source File: IdpTest.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testSeparateSignatureRSASHA256() throws Exception {
    OpenSAMLUtil.initSamlEngine();

    // Create SAML AuthnRequest
    String consumerURL = "https://localhost:" + getRpHttpsPort() + "/"
        + getServletContextName() + "/secure/fedservlet";
    AuthnRequest authnRequest =
        new DefaultAuthnRequestBuilder().createAuthnRequest(
            null, "urn:org:apache:cxf:fediz:fedizhelloworld", consumerURL
        );
    authnRequest.setDestination("https://localhost:" + getIdpHttpsPort() + "/fediz-idp/saml");

    String authnRequestEncoded = encodeAuthnRequest(authnRequest);

    String urlEncodedRequest = URLEncoder.encode(authnRequestEncoded, UTF_8.name());

    String relayState = UUID.randomUUID().toString();

    // Sign request
    Crypto crypto = CryptoFactory.getInstance("stsKeystoreA.properties");

    CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS);
    cryptoType.setAlias("realma");

    // Get the private key
    PrivateKey privateKey = crypto.getPrivateKey("realma", "realma");

    java.security.Signature signature = java.security.Signature.getInstance("SHA256withRSA");
    signature.initSign(privateKey);

    String encodedSignatureAlgorithm =
            URLEncoder.encode("http://www.w3.org/2001/04/xmldsig-more#rsa-sha256", UTF_8.name());
    String requestToSign = SSOConstants.SAML_REQUEST + "=" + urlEncodedRequest
            + "&" + SSOConstants.RELAY_STATE + "=" + relayState
            + "&" + SSOConstants.SIG_ALG + "=" + encodedSignatureAlgorithm;

    signature.update(requestToSign.getBytes(UTF_8));
    byte[] signBytes = signature.sign();

    String encodedSignature = Base64.getEncoder().encodeToString(signBytes);

    String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/saml/up?"
            + SSOConstants.RELAY_STATE + "=" + relayState
            + "&" + SSOConstants.SAML_REQUEST + "=" + urlEncodedRequest
            + "&" + SSOConstants.SIG_ALG + "=" + encodedSignatureAlgorithm
            + "&" + SSOConstants.SIGNATURE + "=" + URLEncoder.encode(encodedSignature, UTF_8.name());

    final WebClient webClient = new WebClient();
    webClient.getOptions().setUseInsecureSSL(true);
    webClient.getCredentialsProvider().setCredentials(
        new AuthScope("localhost", Integer.parseInt(getIdpHttpsPort())),
        new UsernamePasswordCredentials(USER, PWD));

    webClient.getOptions().setJavaScriptEnabled(false);
    final HtmlPage idpPage = webClient.getPage(url);
    webClient.getOptions().setJavaScriptEnabled(true);
    Assert.assertEquals("IDP SignIn Response Form", idpPage.getTitleText());

    org.opensaml.saml.saml2.core.Response samlResponse =
        parseSAMLResponse(idpPage, relayState, consumerURL, authnRequest.getID());
    String expected = "urn:oasis:names:tc:SAML:2.0:status:Success";
    Assert.assertEquals(expected, samlResponse.getStatus().getStatusCode().getValue());

    // Check claims
    String parsedResponse = DOM2Writer.nodeToString(samlResponse.getDOM().getOwnerDocument());
    String claim = ClaimTypes.FIRSTNAME.toString();
    Assert.assertTrue(parsedResponse.contains(claim));
    claim = ClaimTypes.LASTNAME.toString();
    Assert.assertTrue(parsedResponse.contains(claim));
    claim = ClaimTypes.EMAILADDRESS.toString();
    Assert.assertTrue(parsedResponse.contains(claim));

    webClient.close();
}
 
Example #26
Source File: IdpTest.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testSeparateSignature() throws Exception {
    OpenSAMLUtil.initSamlEngine();

    // Create SAML AuthnRequest
    String consumerURL = "https://localhost:" + getRpHttpsPort() + "/"
        + getServletContextName() + "/secure/fedservlet";
    AuthnRequest authnRequest =
        new DefaultAuthnRequestBuilder().createAuthnRequest(
            null, "urn:org:apache:cxf:fediz:fedizhelloworld", consumerURL
        );
    authnRequest.setDestination("https://localhost:" + getIdpHttpsPort() + "/fediz-idp/saml");

    String authnRequestEncoded = encodeAuthnRequest(authnRequest);

    String urlEncodedRequest = URLEncoder.encode(authnRequestEncoded, UTF_8.name());

    String relayState = UUID.randomUUID().toString();

    // Sign request
    Crypto crypto = CryptoFactory.getInstance("stsKeystoreA.properties");

    CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS);
    cryptoType.setAlias("realma");

    // Get the private key
    PrivateKey privateKey = crypto.getPrivateKey("realma", "realma");

    java.security.Signature signature = java.security.Signature.getInstance("SHA1withRSA");
    signature.initSign(privateKey);

    String requestToSign = SSOConstants.SAML_REQUEST + "=" + urlEncodedRequest
            + "&" + SSOConstants.RELAY_STATE + "=" + relayState
            + "&" + SSOConstants.SIG_ALG + "=" + URLEncoder.encode(SSOConstants.RSA_SHA1, UTF_8.name());

    signature.update(requestToSign.getBytes(UTF_8));
    byte[] signBytes = signature.sign();

    String encodedSignature = Base64.getEncoder().encodeToString(signBytes);

    String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/saml/up?"
        + SSOConstants.RELAY_STATE + "=" + relayState
        + "&" + SSOConstants.SAML_REQUEST + "=" + urlEncodedRequest
        + "&" + SSOConstants.SIGNATURE + "=" + URLEncoder.encode(encodedSignature, UTF_8.name());

    final WebClient webClient = new WebClient();
    webClient.getOptions().setUseInsecureSSL(true);
    webClient.getCredentialsProvider().setCredentials(
        new AuthScope("localhost", Integer.parseInt(getIdpHttpsPort())),
        new UsernamePasswordCredentials(USER, PWD));

    webClient.getOptions().setJavaScriptEnabled(false);
    final HtmlPage idpPage = webClient.getPage(url);
    webClient.getOptions().setJavaScriptEnabled(true);
    Assert.assertEquals("IDP SignIn Response Form", idpPage.getTitleText());

    org.opensaml.saml.saml2.core.Response samlResponse =
        parseSAMLResponse(idpPage, relayState, consumerURL, authnRequest.getID());
    String expected = "urn:oasis:names:tc:SAML:2.0:status:Success";
    Assert.assertEquals(expected, samlResponse.getStatus().getStatusCode().getValue());

    // Check claims
    String parsedResponse = DOM2Writer.nodeToString(samlResponse.getDOM().getOwnerDocument());
    String claim = ClaimTypes.FIRSTNAME.toString();
    Assert.assertTrue(parsedResponse.contains(claim));
    claim = ClaimTypes.LASTNAME.toString();
    Assert.assertTrue(parsedResponse.contains(claim));
    claim = ClaimTypes.EMAILADDRESS.toString();
    Assert.assertTrue(parsedResponse.contains(claim));

    webClient.close();
}
 
Example #27
Source File: CombinedValidatorTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
private void signResponse(
    Response response,
    String issuerKeyName,
    String issuerKeyPassword,
    Crypto issuerCrypto,
    boolean useKeyInfo
) throws Exception {
    //
    // Create the signature
    //
    Signature signature = OpenSAMLUtil.buildSignature();
    signature.setCanonicalizationAlgorithm(SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);

    // prepare to sign the SAML token
    CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS);
    cryptoType.setAlias(issuerKeyName);
    X509Certificate[] issuerCerts = issuerCrypto.getX509Certificates(cryptoType);
    if (issuerCerts == null) {
        throw new Exception(
            "No issuer certs were found to sign the SAML Assertion using issuer name: " + issuerKeyName);
    }

    String sigAlgo = SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA1;
    String pubKeyAlgo = issuerCerts[0].getPublicKey().getAlgorithm();

    if ("DSA".equalsIgnoreCase(pubKeyAlgo)) {
        sigAlgo = SignatureConstants.ALGO_ID_SIGNATURE_DSA;
    }

    PrivateKey privateKey = issuerCrypto.getPrivateKey(issuerKeyName, issuerKeyPassword);

    signature.setSignatureAlgorithm(sigAlgo);

    BasicX509Credential signingCredential =
        new BasicX509Credential(issuerCerts[0], privateKey);
    signature.setSigningCredential(signingCredential);

    if (useKeyInfo) {
        X509KeyInfoGeneratorFactory kiFactory = new X509KeyInfoGeneratorFactory();
        kiFactory.setEmitEntityCertificate(true);

        try {
            KeyInfo keyInfo = kiFactory.newInstance().generate(signingCredential);
            signature.setKeyInfo(keyInfo);
        } catch (org.opensaml.security.SecurityException ex) {
            throw new Exception("Error generating KeyInfo from signing credential", ex);
        }
    }

    // add the signature to the assertion
    SignableSAMLObject signableObject = response;
    signableObject.setSignature(signature);
    signableObject.releaseDOM();
    signableObject.releaseChildrenDOM(true);
}
 
Example #28
Source File: SAMLSSOResponseValidatorTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
/**
 * Sign a SAML Response
 * @throws Exception
 */
private void signResponse(
    Response response,
    String issuerKeyName,
    String issuerKeyPassword,
    Crypto issuerCrypto,
    boolean useKeyInfo
) throws Exception {
    //
    // Create the signature
    //
    Signature signature = OpenSAMLUtil.buildSignature();
    signature.setCanonicalizationAlgorithm(SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);

    // prepare to sign the SAML token
    CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS);
    cryptoType.setAlias(issuerKeyName);
    X509Certificate[] issuerCerts = issuerCrypto.getX509Certificates(cryptoType);
    if (issuerCerts == null) {
        throw new Exception(
                "No issuer certs were found to sign the SAML Assertion using issuer name: "
                        + issuerKeyName);
    }

    String sigAlgo = SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA1;
    String pubKeyAlgo = issuerCerts[0].getPublicKey().getAlgorithm();

    if ("DSA".equalsIgnoreCase(pubKeyAlgo)) {
        sigAlgo = SignatureConstants.ALGO_ID_SIGNATURE_DSA;
    }

    PrivateKey privateKey = issuerCrypto.getPrivateKey(issuerKeyName, issuerKeyPassword);

    signature.setSignatureAlgorithm(sigAlgo);

    BasicX509Credential signingCredential = new BasicX509Credential(issuerCerts[0], privateKey);

    signature.setSigningCredential(signingCredential);

    if (useKeyInfo) {
        X509KeyInfoGeneratorFactory kiFactory = new X509KeyInfoGeneratorFactory();
        kiFactory.setEmitEntityCertificate(true);

        try {
            KeyInfo keyInfo = kiFactory.newInstance().generate(signingCredential);
            signature.setKeyInfo(keyInfo);
        } catch (org.opensaml.security.SecurityException ex) {
            throw new Exception(
                    "Error generating KeyInfo from signing credential", ex);
        }
    }

    // add the signature to the assertion
    SignableSAMLObject signableObject = response;
    signableObject.setSignature(signature);
    signableObject.releaseDOM();
    signableObject.releaseChildrenDOM(true);
}
 
Example #29
Source File: SAMLResponseValidatorTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
/**
 * Sign a SAML Response
 * @throws Exception
 */
private void signResponse(
    Response response,
    String issuerKeyName,
    String issuerKeyPassword,
    Crypto issuerCrypto,
    boolean useKeyInfo
) throws Exception {
    //
    // Create the signature
    //
    Signature signature = OpenSAMLUtil.buildSignature();
    signature.setCanonicalizationAlgorithm(SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);

    // prepare to sign the SAML token
    CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS);
    cryptoType.setAlias(issuerKeyName);
    X509Certificate[] issuerCerts = issuerCrypto.getX509Certificates(cryptoType);
    if (issuerCerts == null) {
        throw new Exception(
                "No issuer certs were found to sign the SAML Assertion using issuer name: "
                        + issuerKeyName);
    }

    String sigAlgo = SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA1;
    String pubKeyAlgo = issuerCerts[0].getPublicKey().getAlgorithm();

    if ("DSA".equalsIgnoreCase(pubKeyAlgo)) {
        sigAlgo = SignatureConstants.ALGO_ID_SIGNATURE_DSA;
    }

    PrivateKey privateKey = issuerCrypto.getPrivateKey(issuerKeyName, issuerKeyPassword);

    signature.setSignatureAlgorithm(sigAlgo);

    BasicX509Credential signingCredential =
        new BasicX509Credential(issuerCerts[0], privateKey);
    signature.setSigningCredential(signingCredential);

    if (useKeyInfo) {
        X509KeyInfoGeneratorFactory kiFactory = new X509KeyInfoGeneratorFactory();
        kiFactory.setEmitEntityCertificate(true);

        try {
            KeyInfo keyInfo = kiFactory.newInstance().generate(signingCredential);
            signature.setKeyInfo(keyInfo);
        } catch (org.opensaml.security.SecurityException ex) {
            throw new Exception(
                    "Error generating KeyInfo from signing credential", ex);
        }
    }

    // add the signature to the assertion
    SignableSAMLObject signableObject = response;
    signableObject.setSignature(signature);
    signableObject.releaseDOM();
    signableObject.releaseChildrenDOM(true);
}
 
Example #30
Source File: SAMLProtocolResponseValidator.java    From cxf with Apache License 2.0 4 votes vote down vote up
/**
 * Validate the response signature
 */
private void validateResponseSignature(
    Signature signature,
    Document doc,
    Crypto sigCrypto,
    CallbackHandler callbackHandler
) throws WSSecurityException {
    RequestData requestData = new RequestData();
    requestData.setSigVerCrypto(sigCrypto);
    WSSConfig wssConfig = WSSConfig.getNewInstance();
    requestData.setWssConfig(wssConfig);
    requestData.setCallbackHandler(callbackHandler);
    requestData.setWsDocInfo(new WSDocInfo(doc));

    SAMLKeyInfo samlKeyInfo = null;

    KeyInfo keyInfo = signature.getKeyInfo();
    if (keyInfo != null) {
        try {
            samlKeyInfo =
                SAMLUtil.getCredentialFromKeyInfo(
                    keyInfo.getDOM(), new WSSSAMLKeyInfoProcessor(requestData), sigCrypto
                );
        } catch (WSSecurityException ex) {
            LOG.log(Level.FINE, "Error in getting KeyInfo from SAML Response: " + ex.getMessage(), ex);
            throw ex;
        }
    } else if (!keyInfoMustBeAvailable) {
        samlKeyInfo = createKeyInfoFromDefaultAlias(sigCrypto);
    }
    if (samlKeyInfo == null) {
        LOG.warning("No KeyInfo supplied in the SAMLResponse signature");
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
    }

    // Validate Signature against profiles
    validateSignatureAgainstProfiles(signature, samlKeyInfo);

    // Now verify trust on the signature
    Credential trustCredential = new Credential();
    trustCredential.setPublicKey(samlKeyInfo.getPublicKey());
    trustCredential.setCertificates(samlKeyInfo.getCerts());

    try {
        signatureValidator.validate(trustCredential, requestData);
    } catch (WSSecurityException e) {
        LOG.log(Level.FINE, "Error in validating signature on SAML Response: " + e.getMessage(), e);
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
    }
}