コード例 #1
0
  /**
   * Serialize the Auth. Request
   *
   * @param xmlObject
   * @return serialized auth. req
   */
  protected String marshall(XMLObject xmlObject) throws SSOAgentException {

    try {
      System.setProperty(
          "javax.xml.parsers.DocumentBuilderFactory",
          "org.apache.xerces.jaxp.DocumentBuilderFactoryImpl");
      MarshallerFactory marshallerFactory = org.opensaml.xml.Configuration.getMarshallerFactory();
      Marshaller marshaller = marshallerFactory.getMarshaller(xmlObject);
      Element element = marshaller.marshall(xmlObject);
      ByteArrayOutputStream byteArrayOutputStrm = new ByteArrayOutputStream();
      DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
      DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");
      LSSerializer writer = impl.createLSSerializer();
      LSOutput output = impl.createLSOutput();
      output.setByteStream(byteArrayOutputStrm);
      writer.write(element, output);
      return new String(byteArrayOutputStrm.toByteArray(), Charset.forName("UTF-8"));
    } catch (ClassNotFoundException e) {
      throw new SSOAgentException("Error in marshalling SAML2 Assertion", e);
    } catch (InstantiationException e) {
      throw new SSOAgentException("Error in marshalling SAML2 Assertion", e);
    } catch (MarshallingException e) {
      throw new SSOAgentException("Error in marshalling SAML2 Assertion", e);
    } catch (IllegalAccessException e) {
      throw new SSOAgentException("Error in marshalling SAML2 Assertion", e);
    }
  }
コード例 #2
0
 /**
  * Serializes an authentication request into a string.
  *
  * @param request the request to serialize
  * @return the serialized form of the string
  * @throws MarshallingException thrown if the request can not be marshalled and serialized
  */
 protected String serializeRequest(AuthnRequest request) throws MarshallingException {
   Marshaller marshaller = Configuration.getMarshallerFactory().getMarshaller(request);
   Element requestElem = marshaller.marshall(request);
   StringWriter writer = new StringWriter();
   XMLHelper.writeNode(requestElem, writer);
   return writer.toString();
 }
コード例 #3
0
  /**
   * Applies the XML Digital Signature to the SAML 2.0 based Logout Request (LogoutRequest).
   *
   * @param logoutRequest the SAML 2.0 based Logout Request (LogoutRequest)
   * @param signatureAlgorithm the algorithm used to compute the signature
   * @param credential the signature signing credential
   * @return the SAML 2.0 based Logout Request (LogoutRequest) with XML Digital Signature set
   * @throws SSOException if an error occurs while signing the SAML 2.0 LogoutRequest message
   */
  protected static LogoutRequest setSignature(
      LogoutRequest logoutRequest, String signatureAlgorithm, X509Credential credential)
      throws SSOException {
    try {
      Signature signature = setSignatureRaw(signatureAlgorithm, credential);
      logoutRequest.setSignature(signature);

      List<Signature> signatureList = new ArrayList<>();
      signatureList.add(signature);

      // Marshall and Sign
      MarshallerFactory marshallerFactory = org.opensaml.xml.Configuration.getMarshallerFactory();
      Marshaller marshaller = marshallerFactory.getMarshaller(logoutRequest);
      marshaller.marshall(logoutRequest);

      //  Initializes and configures the library
      Init.init();
      //  Signer is responsible for creating the digital signatures for the given XML Objects.
      //  Signs the XML Objects based on the given order of the Signature list
      Signer.signObjects(signatureList);
      return logoutRequest;
    } catch (MarshallingException | SignatureException e) {
      throw new SSOException("Error while signing the SAML 2.0 based LogoutRequest message", e);
    }
  }
コード例 #4
0
 /**
  * Serializes the specified SAML 2.0 based XML content representation to its corresponding actual
  * XML syntax representation.
  *
  * @param xmlObject the SAML 2.0 based XML content object
  * @return a {@link String} representation of the actual XML representation of the SAML 2.0 based
  *     XML content representation
  * @throws SSOException if an error occurs during the marshalling process
  */
 public static String marshall(XMLObject xmlObject) throws SSOException {
   try {
     //  Explicitly sets the special XML parser library to be used, in the global variables
     System.setProperty(
         "javax.xml.parsers.DocumentBuilderFactory",
         "org.apache.xerces.jaxp.DocumentBuilderFactoryImpl");
     MarshallerFactory marshallerFactory = Configuration.getMarshallerFactory();
     Marshaller marshaller = marshallerFactory.getMarshaller(xmlObject);
     Element element = marshaller.marshall(xmlObject);
     ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
     DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
     DOMImplementationLS implementation =
         (DOMImplementationLS) registry.getDOMImplementation("LS");
     LSSerializer writer = implementation.createLSSerializer();
     LSOutput output = implementation.createLSOutput();
     output.setByteStream(byteArrayOutputStream);
     writer.write(element, output);
     return new String(byteArrayOutputStream.toByteArray(), Charset.forName("UTF-8"));
   } catch (ClassNotFoundException
       | InstantiationException
       | MarshallingException
       | IllegalAccessException e) {
     throw new SSOException("Error in marshalling SAML2 Assertion", e);
   }
 }
  private static String getMetadataAsString(final EntityDescriptor descriptor)
      throws MarshallingException {

    final MarshallerFactory marshallerFactory = Configuration.getMarshallerFactory();
    final Marshaller marshaller = marshallerFactory.getMarshaller(descriptor);
    final Element element = marshaller.marshall(descriptor);
    return XMLHelper.nodeToString(element);
  }
  @Override
  public SignableXMLObject setSignature(
      SignableXMLObject signableXMLObject,
      String signatureAlgorithm,
      String digestAlgorithm,
      X509Credential cred)
      throws IdentityException {

    Signature signature = (Signature) buildXMLObject(Signature.DEFAULT_ELEMENT_NAME);
    signature.setSigningCredential(cred);
    signature.setSignatureAlgorithm(signatureAlgorithm);
    signature.setCanonicalizationAlgorithm(Canonicalizer.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);

    KeyInfo keyInfo = (KeyInfo) buildXMLObject(KeyInfo.DEFAULT_ELEMENT_NAME);
    X509Data data = (X509Data) buildXMLObject(X509Data.DEFAULT_ELEMENT_NAME);
    X509Certificate cert = (X509Certificate) buildXMLObject(X509Certificate.DEFAULT_ELEMENT_NAME);

    String value;
    try {
      value = org.apache.xml.security.utils.Base64.encode(cred.getEntityCertificate().getEncoded());
    } catch (CertificateEncodingException e) {
      throw IdentityException.error("Error occurred while retrieving encoded cert", e);
    }

    cert.setValue(value);
    data.getX509Certificates().add(cert);
    keyInfo.getX509Datas().add(data);
    signature.setKeyInfo(keyInfo);

    signableXMLObject.setSignature(signature);
    ((SAMLObjectContentReference) signature.getContentReferences().get(0))
        .setDigestAlgorithm(digestAlgorithm);

    List<Signature> signatureList = new ArrayList<Signature>();
    signatureList.add(signature);

    MarshallerFactory marshallerFactory = org.opensaml.xml.Configuration.getMarshallerFactory();
    Marshaller marshaller = marshallerFactory.getMarshaller(signableXMLObject);

    try {
      marshaller.marshall(signableXMLObject);
    } catch (MarshallingException e) {
      throw IdentityException.error("Unable to marshall the request", e);
    }

    org.apache.xml.security.Init.init();
    try {
      Signer.signObjects(signatureList);
    } catch (SignatureException e) {
      throw IdentityException.error("Error occurred while signing request", e);
    }

    return signableXMLObject;
  }
コード例 #7
0
  /*
   * Create a fully formed SAML Request.
   * @return The SAML Request as XML.
   */
  public String buildAuthnRequest2String()
      throws org.opensaml.xml.io.MarshallingException, BindingException, IOException,
          ValidationException {
    // build an AuthnRequest object
    final AuthnRequestImpl auth = buildAuthnRequest();

    // Now we must marshall the object for the transfer over the wire.
    final Marshaller marshaller = Configuration.getMarshallerFactory().getMarshaller(auth);
    final Element authDOM = marshaller.marshall(auth);
    // We use a StringWriter to produce our XML output. This gets us XML where
    // the encoding is UTF-8. We must have UTF-8 or bad things happen.
    return XMLHelper.prettyPrintXML(authDOM);
  }
コード例 #8
0
  /**
   * Encodes the SAML 2.0 based request XML object into its corresponding Base64 notation, based on
   * the type of SAML 2.0 binding.
   *
   * @param requestMessage the {@link RequestAbstractType} XML object to be encoded
   * @param binding the SAML 2.0 binding type
   * @return encoded {@link String} corresponding to the request XML object
   * @throws SSOException if an error occurs while encoding SAML2 request
   */
  protected static String encodeRequestMessage(RequestAbstractType requestMessage, String binding)
      throws SSOException {
    Marshaller marshaller = Configuration.getMarshallerFactory().getMarshaller(requestMessage);
    Element authDOM;
    try {
      //  Marshall this element, and its children, and root them in a newly created Document
      authDOM = marshaller.marshall(requestMessage);
    } catch (MarshallingException e) {
      throw new SSOException(
          "Error occurred while encoding SAML2 request, failed to marshall the SAML 2.0. "
              + "Request element XMLObject to its corresponding W3C DOM element",
          e);
    }

    StringWriter writer = new StringWriter();
    //  Writes the node out to the writer using the DOM
    XMLHelper.writeNode(authDOM, writer);

    if (SAMLConstants.SAML2_REDIRECT_BINDING_URI.equals(binding)) {
      //  Compress the message, Base 64 encode and URL encode
      Deflater deflater = new Deflater(Deflater.DEFLATED, true);
      ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
      try (DeflaterOutputStream deflaterOutputStream =
          new DeflaterOutputStream(byteArrayOutputStream, deflater)) {
        deflaterOutputStream.write(writer.toString().getBytes(Charset.forName("UTF-8")));
      } catch (IOException e) {
        throw new SSOException("Error occurred while deflate encoding SAML2 request", e);
      }

      String encodedRequestMessage =
          Base64.encodeBytes(byteArrayOutputStream.toByteArray(), Base64.DONT_BREAK_LINES);
      try {
        return URLEncoder.encode(encodedRequestMessage, "UTF-8").trim();
      } catch (UnsupportedEncodingException e) {
        throw new SSOException("Error occurred while encoding SAML2 request", e);
      }
    } else if (SAMLConstants.SAML2_POST_BINDING_URI.equals(binding)) {
      return Base64.encodeBytes(
          writer.toString().getBytes(Charset.forName("UTF-8")), Base64.DONT_BREAK_LINES);
    } else {
      logger.log(
          Level.FINE,
          "Unsupported SAML2 HTTP Binding. Defaulting to " + SAMLConstants.SAML2_POST_BINDING_URI);
      return Base64.encodeBytes(
          writer.toString().getBytes(Charset.forName("UTF-8")), Base64.DONT_BREAK_LINES);
    }
  }
コード例 #9
0
  /**
   * Sign the SAML AuthnRequest message
   *
   * @param logoutRequest
   * @param signatureAlgorithm
   * @param cred
   * @return
   * @throws SAMLSSOException
   */
  public static LogoutRequest setSignature(
      LogoutRequest logoutRequest, String signatureAlgorithm, X509Credential cred)
      throws SAMLSSOException {
    try {
      Signature signature = (Signature) buildXMLObject(Signature.DEFAULT_ELEMENT_NAME);
      signature.setSigningCredential(cred);
      signature.setSignatureAlgorithm(signatureAlgorithm);
      signature.setCanonicalizationAlgorithm(Canonicalizer.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);

      try {
        KeyInfo keyInfo = (KeyInfo) buildXMLObject(KeyInfo.DEFAULT_ELEMENT_NAME);
        X509Data data = (X509Data) buildXMLObject(X509Data.DEFAULT_ELEMENT_NAME);
        org.opensaml.xml.signature.X509Certificate cert =
            (org.opensaml.xml.signature.X509Certificate)
                buildXMLObject(org.opensaml.xml.signature.X509Certificate.DEFAULT_ELEMENT_NAME);
        String value =
            org.apache.xml.security.utils.Base64.encode(cred.getEntityCertificate().getEncoded());
        cert.setValue(value);
        data.getX509Certificates().add(cert);
        keyInfo.getX509Datas().add(data);
        signature.setKeyInfo(keyInfo);
      } catch (CertificateEncodingException e) {
        throw new SAMLSSOException("Error getting certificate", e);
      }

      logoutRequest.setSignature(signature);

      List<Signature> signatureList = new ArrayList<Signature>();
      signatureList.add(signature);

      // Marshall and Sign
      MarshallerFactory marshallerFactory = org.opensaml.xml.Configuration.getMarshallerFactory();
      Marshaller marshaller = marshallerFactory.getMarshaller(logoutRequest);

      marshaller.marshall(logoutRequest);

      org.apache.xml.security.Init.init();
      Signer.signObjects(signatureList);
      return logoutRequest;

    } catch (Exception e) {
      throw new SAMLSSOException("Error while signing the Logout Request message", e);
    }
  }
コード例 #10
0
  private String encodeRequestMessage(RequestAbstractType requestMessage) throws SAMLSSOException {

    Marshaller marshaller = Configuration.getMarshallerFactory().getMarshaller(requestMessage);
    Element authDOM = null;
    try {
      authDOM = marshaller.marshall(requestMessage);

      /* Compress the message */
      Deflater deflater = new Deflater(Deflater.DEFLATED, true);
      ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
      DeflaterOutputStream deflaterOutputStream =
          new DeflaterOutputStream(byteArrayOutputStream, deflater);
      StringWriter rspWrt = new StringWriter();
      XMLHelper.writeNode(authDOM, rspWrt);
      deflaterOutputStream.write(rspWrt.toString().getBytes());
      deflaterOutputStream.close();

      /* Encoding the compressed message */
      String encodedRequestMessage =
          Base64.encodeBytes(byteArrayOutputStream.toByteArray(), Base64.DONT_BREAK_LINES);

      byteArrayOutputStream.write(byteArrayOutputStream.toByteArray());
      byteArrayOutputStream.toString();

      // log saml
      if (log.isDebugEnabled()) {
        log.debug("SAML Request  :  " + rspWrt.toString());
      }

      return URLEncoder.encode(encodedRequestMessage, "UTF-8").trim();

    } catch (MarshallingException e) {
      throw new SAMLSSOException("Error occurred while encoding SAML request", e);
    } catch (UnsupportedEncodingException e) {
      throw new SAMLSSOException("Error occurred while encoding SAML request", e);
    } catch (IOException e) {
      throw new SAMLSSOException("Error occurred while encoding SAML request", e);
    }
  }
コード例 #11
0
ファイル: Util.java プロジェクト: GayashanNA/carbon-utils
  /**
   * Serializing a SAML2 object into a String
   *
   * @param xmlObject object that needs to serialized.
   * @return serialized object
   * @throws Exception
   */
  public static String marshall(XMLObject xmlObject) throws Exception {
    try {
      doBootstrap();
      System.setProperty(
          "javax.xml.parsers.DocumentBuilderFactory",
          "org.apache.xerces.jaxp.DocumentBuilderFactoryImpl");

      MarshallerFactory marshallerFactory = org.opensaml.xml.Configuration.getMarshallerFactory();
      Marshaller marshaller = marshallerFactory.getMarshaller(xmlObject);
      Element element = marshaller.marshall(xmlObject);

      ByteArrayOutputStream byteArrayOutputStrm = new ByteArrayOutputStream();
      DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
      DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");
      LSSerializer writer = impl.createLSSerializer();
      LSOutput output = impl.createLSOutput();
      output.setByteStream(byteArrayOutputStrm);
      writer.write(element, output);
      return byteArrayOutputStrm.toString();
    } catch (Exception e) {
      throw new Exception("Error Serializing the SAML Response", e);
    }
  }
コード例 #12
0
  protected String encodeRequestMessage(RequestAbstractType requestMessage, String binding)
      throws SSOAgentException {

    Marshaller marshaller = Configuration.getMarshallerFactory().getMarshaller(requestMessage);
    Element authDOM = null;
    try {
      authDOM = marshaller.marshall(requestMessage);
      StringWriter rspWrt = new StringWriter();
      XMLHelper.writeNode(authDOM, rspWrt);
      if (SAMLConstants.SAML2_REDIRECT_BINDING_URI.equals(binding)) {
        // Compress the message, Base 64 encode and URL encode
        Deflater deflater = new Deflater(Deflater.DEFLATED, true);
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        DeflaterOutputStream deflaterOutputStream =
            new DeflaterOutputStream(byteArrayOutputStream, deflater);
        deflaterOutputStream.write(rspWrt.toString().getBytes(Charset.forName("UTF-8")));
        deflaterOutputStream.close();
        String encodedRequestMessage =
            Base64.encodeBytes(byteArrayOutputStream.toByteArray(), Base64.DONT_BREAK_LINES);
        return URLEncoder.encode(encodedRequestMessage, "UTF-8").trim();
      } else if (SAMLConstants.SAML2_POST_BINDING_URI.equals(binding)) {
        return Base64.encodeBytes(rspWrt.toString().getBytes(), Base64.DONT_BREAK_LINES);
      } else {
        LOGGER.log(
            Level.FINE,
            "Unsupported SAML2 HTTP Binding. Defaulting to "
                + SAMLConstants.SAML2_POST_BINDING_URI);
        return Base64.encodeBytes(rspWrt.toString().getBytes(), Base64.DONT_BREAK_LINES);
      }
    } catch (MarshallingException e) {
      throw new SSOAgentException("Error occurred while encoding SAML2 request", e);
    } catch (UnsupportedEncodingException e) {
      throw new SSOAgentException("Error occurred while encoding SAML2 request", e);
    } catch (IOException e) {
      throw new SSOAgentException("Error occurred while encoding SAML2 request", e);
    }
  }