org.opensaml.core.xml.io.MarshallingException Java Examples

The following examples show how to use org.opensaml.core.xml.io.MarshallingException. 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: MockSamlIdpServer.java    From deprecated-security-advanced-modules with Apache License 2.0 7 votes vote down vote up
private String marshallSamlXml(XMLObject xmlObject) {
    try {
        Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
        Marshaller out = XMLObjectProviderRegistrySupport.getMarshallerFactory().getMarshaller(xmlObject);
        out.marshall(xmlObject, document);

        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        DOMSource source = new DOMSource(document);
        StringWriter stringWriter = new StringWriter();

        transformer.transform(source, new StreamResult(stringWriter));
        return stringWriter.toString();
    } catch (ParserConfigurationException | MarshallingException | TransformerFactoryConfigurationError
            | TransformerException e) {
        throw new RuntimeException(e);
    }
}
 
Example #2
Source File: AuthnRequestFactory.java    From verify-service-provider with MIT License 6 votes vote down vote up
public AuthnRequest build(String serviceEntityId) {
    AuthnRequest authnRequest = new AuthnRequestBuilder().buildObject();
    authnRequest.setID(String.format("_%s", UUID.randomUUID()));
    authnRequest.setIssueInstant(DateTime.now());
    authnRequest.setForceAuthn(false);
    authnRequest.setDestination(destination.toString());
    authnRequest.setExtensions(createExtensions());

    Issuer issuer = new IssuerBuilder().buildObject();
    issuer.setValue(serviceEntityId);
    authnRequest.setIssuer(issuer);

    authnRequest.setSignature(createSignature());

    try {
        XMLObjectProviderRegistrySupport.getMarshallerFactory().getMarshaller(authnRequest).marshall(authnRequest);
        Signer.signObject(authnRequest.getSignature());
    } catch (SignatureException | MarshallingException e) {
        throw new SAMLRuntimeException("Unknown problem while signing SAML object", e);
    }

    return authnRequest;
}
 
Example #3
Source File: SamlMessageUtil.java    From armeria with Apache License 2.0 6 votes vote down vote up
static Element serialize(XMLObject message) {
    requireNonNull(message, "message");

    if (message.getDOM() != null) {
        // Return cached DOM if it exists.
        return message.getDOM();
    }

    final Marshaller marshaller =
            XMLObjectProviderRegistrySupport.getMarshallerFactory().getMarshaller(message);
    if (marshaller == null) {
        throw new SamlException("failed to serialize a SAML object into an XML document, " +
                                "no serializer registered for message object: " +
                                message.getElementQName());
    }

    try {
        return marshaller.marshall(message);
    } catch (MarshallingException e) {
        throw new SamlException("failed to serialize a SAML object into an XML document", e);
    }
}
 
Example #4
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 #5
Source File: NonMatchingEidasAcceptanceTest.java    From verify-service-provider with MIT License 5 votes vote down vote up
@Test
public void shouldReturn400WhenAssertionContainsAnInvalidSignature() throws MarshallingException, SignatureException {
    String base64Response = xmlToB64Transformer.apply(
            anInvalidAssertionSignatureEidasResponse("requestId", appWithEidasEnabled.getCountryEntityId()).build()
    );
    Response response = appWithEidasEnabled.client().target(format("http://localhost:%s/translate-response", appWithEidasEnabled.getLocalPort())).request().post(
            Entity.json(new TranslateSamlResponseBody(base64Response, "requestId", LEVEL_2, null))
    );

    assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_BAD_REQUEST);

    String responseBody = response.readEntity(String.class);
    assertThat(responseBody).contains("Signature was not valid.");
}
 
Example #6
Source File: NonMatchingEidasAcceptanceTest.java    From verify-service-provider with MIT License 5 votes vote down vote up
@Test
public void shouldReturn400WhenAssertionSignedByCountryNotInTrustAnchor() throws MarshallingException, SignatureException {
    String base64Response = xmlToB64Transformer.apply(
            aValidEidasResponse("requestId", STUB_COUNTRY_ONE).build()
    );
    Response response = appWithEidasEnabled.client().target(format("http://localhost:%s/translate-response", appWithEidasEnabled.getLocalPort())).request().post(
            Entity.json(new TranslateSamlResponseBody(base64Response, "requestId", LEVEL_2, null))
    );

    assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_BAD_REQUEST);
}
 
Example #7
Source File: ResponseServiceTest.java    From verify-service-provider with MIT License 5 votes vote down vote up
private EntityDescriptor createEntityDescriptorWithSigningCertificate(String signingCert) throws MarshallingException, SignatureException {
    return anEntityDescriptor()
        .addSpServiceDescriptor(anSpServiceDescriptor()
            .withoutDefaultSigningKey()
            .addKeyDescriptor(aKeyDescriptor().withX509ForSigning(signingCert).build())
            .build()
        )
        .build();
}
 
Example #8
Source File: MockMsaServer.java    From verify-service-provider with MIT License 5 votes vote down vote up
public static String msaMetadata() {
    EntityDescriptor entityDescriptor = new EntityDescriptorFactory().idpEntityDescriptor(MSA_ENTITY_ID);
    try {
        return new MetadataFactory().metadata(anEntitiesDescriptor()
                .withEntityDescriptors(ImmutableList.of(entityDescriptor))
                .withValidUntil(DateTime.now().plusWeeks(2)).build());
    } catch (MarshallingException | SignatureException e) {
        Throwables.throwIfUnchecked(e);
        throw new RuntimeException(e);
    }

}
 
Example #9
Source File: SamlClient.java    From saml-client with MIT License 5 votes vote down vote up
/** Convert a SAML request to a base64-encoded String
 *
 * @param request The request to encode
 * @throws SamlException if marshalling the request fails
 * */
private String marshallAndEncodeSamlObject(RequestAbstractType request) throws SamlException {
  StringWriter stringWriter;
  try {
    stringWriter = marshallXmlObject(request);
  } catch (MarshallingException e) {
    throw new SamlException("Error while marshalling SAML request to XML", e);
  }

  logger.trace("Issuing SAML request: " + stringWriter.toString());

  return Base64.encodeBase64String(stringWriter.toString().getBytes(StandardCharsets.UTF_8));
}
 
Example #10
Source File: SamlClient.java    From saml-client with MIT License 5 votes vote down vote up
/**
 * Gets saml logout response.
 *
 * @param status  the status code @See StatusCode.java
 * @param statMsg the status message
 * @return saml logout response
 * @throws SamlException the saml exception
 */
public String getSamlLogoutResponse(final String status, final String statMsg)
    throws SamlException {
  LogoutResponse response = (LogoutResponse) buildSamlObject(LogoutResponse.DEFAULT_ELEMENT_NAME);
  response.setID("z" + UUID.randomUUID().toString()); // ADFS needs IDs to start with a letter

  response.setVersion(SAMLVersion.VERSION_20);
  response.setIssueInstant(DateTime.now());

  Issuer issuer = (Issuer) buildSamlObject(Issuer.DEFAULT_ELEMENT_NAME);
  issuer.setValue(relyingPartyIdentifier);
  response.setIssuer(issuer);

  //Status
  Status stat = (Status) buildSamlObject(Status.DEFAULT_ELEMENT_NAME);
  StatusCode statCode = new StatusCodeBuilder().buildObject();
  statCode.setValue(status);
  stat.setStatusCode(statCode);
  if (statMsg != null) {
    StatusMessage statMessage = new StatusMessageBuilder().buildObject();
    statMessage.setMessage(statMsg);
    stat.setStatusMessage(statMessage);
  }
  response.setStatus(stat);
  //Add a signature into the response
  signSAMLObject(response);

  StringWriter stringWriter;
  try {
    stringWriter = marshallXmlObject(response);
  } catch (MarshallingException ex) {
    throw new SamlException("Error while marshalling SAML request to XML", ex);
  }

  logger.trace("Issuing SAML Logout request: " + stringWriter.toString());

  return Base64.encodeBase64String(stringWriter.toString().getBytes(StandardCharsets.UTF_8));
}
 
Example #11
Source File: SamlClient.java    From saml-client with MIT License 5 votes vote down vote up
private StringWriter marshallXmlObject(XMLObject object) throws MarshallingException {
  StringWriter stringWriter = new StringWriter();
  Marshaller marshaller =
      XMLObjectProviderRegistrySupport.getMarshallerFactory().getMarshaller(object);
  Element dom = marshaller.marshall(object);
  XMLHelper.writeNode(dom, stringWriter);

  return stringWriter;
}
 
Example #12
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 #13
Source File: ResponseServiceTest.java    From verify-service-provider with MIT License 4 votes vote down vote up
private Response signResponse(ResponseBuilder responseBuilder, Credential signingCredential) throws MarshallingException, SignatureException {
    return responseBuilder
        .withSigningCredential(signingCredential).build();
}