org.opensaml.Configuration Java Examples

The following examples show how to use org.opensaml.Configuration. 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 Project: carbon-identity   Author: wso2-attic   File: SSOAgentUtils.java    License: Apache License 2.0 7 votes vote down vote up
/**
 * Sign the SAML AuthnRequest message
 *
 * @param logoutRequest
 * @param signatureAlgorithm
 * @param cred
 * @return
 * @throws SSOAgentException
 */
public static LogoutRequest setSignature(LogoutRequest logoutRequest, String signatureAlgorithm,
                                         X509Credential cred) throws SSOAgentException {
    try {
        Signature signature = setSignatureRaw(signatureAlgorithm,cred);

        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 SSOAgentException("Error while signing the Logout Request message", e);
    }
}
 
Example #2
Source Project: micro-integrator   Author: wso2   File: WSXACMLEntitlementServiceClient.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Serialize XML objects
 *
 * @param xmlObject : XACML or SAML objects to be serialized
 * @return serialized XACML or SAML objects
 */
private String marshall(XMLObject xmlObject) throws EntitlementProxyException {

    try {
        doBootstrap();
        System.setProperty(DOCUMENT_BUILDER_FACTORY, DOCUMENT_BUILDER_FACTORY_IMPL);

        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 (Exception e) {
        log.error("Error Serializing the SAML Response");
        throw new EntitlementProxyException("Error Serializing the SAML Response", e);
    }
}
 
Example #3
Source Project: cas4.0.x-server-wechat   Author: luotuo   File: CasHTTPSOAP11Encoder.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected Envelope buildSOAPMessage(final SAMLObject samlMessage) {
    final XMLObjectBuilderFactory builderFactory = Configuration.getBuilderFactory();

    final SOAPObjectBuilder<Envelope> envBuilder =
            (SOAPObjectBuilder<Envelope>) builderFactory.getBuilder(Envelope.DEFAULT_ELEMENT_NAME);
    final Envelope envelope = envBuilder.buildObject(
            SOAPConstants.SOAP11_NS, Envelope.DEFAULT_ELEMENT_LOCAL_NAME, OPENSAML_11_SOAP_NS_PREFIX);

    final SOAPObjectBuilder<Body> bodyBuilder =
            (SOAPObjectBuilder<Body>) builderFactory.getBuilder(Body.DEFAULT_ELEMENT_NAME);
    final Body body = bodyBuilder.buildObject(
            SOAPConstants.SOAP11_NS, Body.DEFAULT_ELEMENT_LOCAL_NAME, OPENSAML_11_SOAP_NS_PREFIX);

    body.getUnknownXMLObjects().add(samlMessage);
    envelope.setBody(body);

    return envelope;
}
 
Example #4
Source Project: lams   Author: lamsfoundation   File: MetadataCredentialResolver.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Constructor.
 * 
 * @param metadataProvider provider of the metadata
 * 
 * @throws IllegalArgumentException thrown if the supplied provider is null
 */
public MetadataCredentialResolver(MetadataProvider metadataProvider) {
    super();
    if (metadataProvider == null) {
        throw new IllegalArgumentException("Metadata provider may not be null");
    }
    metadata = metadataProvider;

    cache = new HashMap<MetadataCacheKey, SoftReference<Collection<Credential>>>();

    keyInfoCredentialResolver = Configuration.getGlobalSecurityConfiguration()
            .getDefaultKeyInfoCredentialResolver();
    
    rwlock = new ReentrantReadWriteLock();

    if (metadata instanceof ObservableMetadataProvider) {
        ObservableMetadataProvider observable = (ObservableMetadataProvider) metadataProvider;
        observable.getObservers().add(new MetadataProviderObserver());
    }

}
 
Example #5
Source Project: lams   Author: lamsfoundation   File: AttributeValueTypeMarshaller.java    License: GNU General Public License v2.0 6 votes vote down vote up
/** {@inheritDoc} */
protected void marshallAttributes(XMLObject xmlObject, Element domElement) throws MarshallingException {
    AttributeValueType attributeValue = (AttributeValueType) xmlObject;

    if(!DatatypeHelper.isEmpty(attributeValue.getDataType())){
    	domElement.setAttributeNS(null,AttributeAssignmentType.DATA_TYPE_ATTRIB_NAME, attributeValue.getDataType());
    }
    
    Attr attribute;
    for (Entry<QName, String> entry : attributeValue.getUnknownAttributes().entrySet()) {
        attribute = XMLHelper.constructAttribute(domElement.getOwnerDocument(), entry.getKey());
        attribute.setValue(entry.getValue());
        domElement.setAttributeNodeNS(attribute);
        if (Configuration.isIDAttribute(entry.getKey())
                || attributeValue.getUnknownAttributes().isIDAttribute(entry.getKey())) {
            attribute.getOwnerElement().setIdAttributeNode(attribute, true);
        }
    }
}
 
Example #6
Source Project: lams   Author: lamsfoundation   File: HTTPSOAP11Encoder.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Builds the SOAP message to be encoded.
 * 
 * @param samlMessage body of the SOAP message
 * 
 * @return the SOAP message
 */
@SuppressWarnings("unchecked")
protected Envelope buildSOAPMessage(SAMLObject samlMessage) {
    log.debug("Building SOAP message");
    XMLObjectBuilderFactory builderFactory = Configuration.getBuilderFactory();

    SOAPObjectBuilder<Envelope> envBuilder = (SOAPObjectBuilder<Envelope>) builderFactory
            .getBuilder(Envelope.DEFAULT_ELEMENT_NAME);
    Envelope envelope = envBuilder.buildObject();

    log.debug("Adding SAML message to the SOAP message's body");
    SOAPObjectBuilder<Body> bodyBuilder = (SOAPObjectBuilder<Body>) builderFactory
            .getBuilder(Body.DEFAULT_ELEMENT_NAME);
    Body body = bodyBuilder.buildObject();
    body.getUnknownXMLObjects().add(samlMessage);
    envelope.setBody(body);

    return envelope;
}
 
Example #7
Source Project: lams   Author: lamsfoundation   File: RequestAbstractTypeMarshaller.java    License: GNU General Public License v2.0 6 votes vote down vote up
/** {@inheritDoc} */
protected void marshallAttributes(XMLObject samlElement, Element domElement) throws MarshallingException {
    RequestAbstractType request = (RequestAbstractType) samlElement;

    if (request.getID() != null) {
        domElement.setAttributeNS(null, RequestAbstractType.ID_ATTRIB_NAME, request.getID());
        if (request.getMinorVersion() != 0) {
            domElement.setIdAttributeNS(null, RequestAbstractType.ID_ATTRIB_NAME, true);
        }
    }

    if (request.getIssueInstant() != null) {
        String date = Configuration.getSAMLDateFormatter().print(request.getIssueInstant());
        domElement.setAttributeNS(null, RequestAbstractType.ISSUEINSTANT_ATTRIB_NAME, date);
    }
    if (request.getMinorVersion() != 0) {
        domElement.setAttributeNS(null, RequestAbstractType.MAJORVERSION_ATTRIB_NAME, "1");
        domElement.setAttributeNS(null, RequestAbstractType.MINORVERSION_ATTRIB_NAME, Integer.toString(request
                .getMinorVersion()));
    }
}
 
Example #8
Source Project: lams   Author: lamsfoundation   File: HTTPSOAP11Encoder.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Builds the SOAP message to be encoded.
 * 
 * @param samlMessage body of the SOAP message
 * 
 * @return the SOAP message
 */
@SuppressWarnings("unchecked")
protected Envelope buildSOAPMessage(SAMLObject samlMessage) {
    if (log.isDebugEnabled()) {
        log.debug("Building SOAP message");
    }
    XMLObjectBuilderFactory builderFactory = Configuration.getBuilderFactory();

    SOAPObjectBuilder<Envelope> envBuilder = (SOAPObjectBuilder<Envelope>) builderFactory
            .getBuilder(Envelope.DEFAULT_ELEMENT_NAME);
    Envelope envelope = envBuilder.buildObject();

    if (log.isDebugEnabled()) {
        log.debug("Adding SAML message to the SOAP message's body");
    }
    SOAPObjectBuilder<Body> bodyBuilder = (SOAPObjectBuilder<Body>) builderFactory
            .getBuilder(Body.DEFAULT_ELEMENT_NAME);
    Body body = bodyBuilder.buildObject();
    body.getUnknownXMLObjects().add(samlMessage);
    envelope.setBody(body);

    return envelope;
}
 
Example #9
Source Project: lams   Author: lamsfoundation   File: Encrypter.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Helper method for constructors.
 */
private void init() {
    builderFactory = Configuration.getBuilderFactory();
    keyInfoBuilder = 
        (XMLSignatureBuilder<KeyInfo>) builderFactory.getBuilder(KeyInfo.DEFAULT_ELEMENT_NAME);
    dataReferenceBuilder = 
        (XMLEncryptionBuilder<DataReference>) builderFactory.getBuilder(DataReference.DEFAULT_ELEMENT_NAME);
    referenceListBuilder = 
        (XMLEncryptionBuilder<ReferenceList>) builderFactory.getBuilder(ReferenceList.DEFAULT_ELEMENT_NAME);
    retrievalMethodBuilder = 
        (XMLSignatureBuilder<RetrievalMethod>) builderFactory.getBuilder(RetrievalMethod.DEFAULT_ELEMENT_NAME);
    keyNameBuilder = 
        (XMLSignatureBuilder<KeyName>) builderFactory.getBuilder(KeyName.DEFAULT_ELEMENT_NAME);
    carriedKeyNameBuilder = 
        (XMLEncryptionBuilder<CarriedKeyName>) builderFactory.getBuilder(CarriedKeyName.DEFAULT_ELEMENT_NAME);
    
    try{
        idGenerator = new SecureRandomIdentifierGenerator();
    }catch(NoSuchAlgorithmException e){
        log.error("JVM does not support SHA1PRNG random number generation algorithm.");
    }
    
    keyPlacement = KeyPlacement.PEER;
}
 
Example #10
Source Project: lams   Author: lamsfoundation   File: AuthnStatementMarshaller.java    License: GNU General Public License v2.0 6 votes vote down vote up
/** {@inheritDoc} */
protected void marshallAttributes(XMLObject samlObject, Element domElement) throws MarshallingException {
    AuthnStatement authnStatement = (AuthnStatement) samlObject;

    if (authnStatement.getAuthnInstant() != null) {
        String authnInstantStr = Configuration.getSAMLDateFormatter().print(authnStatement.getAuthnInstant());
        domElement.setAttributeNS(null, AuthnStatement.AUTHN_INSTANT_ATTRIB_NAME, authnInstantStr);
    }

    if (authnStatement.getSessionIndex() != null) {
        domElement.setAttributeNS(null, AuthnStatement.SESSION_INDEX_ATTRIB_NAME, authnStatement.getSessionIndex());
    }

    if (authnStatement.getSessionNotOnOrAfter() != null) {
        String sessionNotOnOrAfterStr = Configuration.getSAMLDateFormatter().print(
                authnStatement.getSessionNotOnOrAfter());
        domElement.setAttributeNS(null, AuthnStatement.SESSION_NOT_ON_OR_AFTER_ATTRIB_NAME, sessionNotOnOrAfterStr);
    }
}
 
Example #11
Source Project: lams   Author: lamsfoundation   File: AssertionMarshaller.java    License: GNU General Public License v2.0 6 votes vote down vote up
/** {@inheritDoc} */
protected void marshallAttributes(XMLObject samlObject, Element domElement) throws MarshallingException {
    Assertion assertion = (Assertion) samlObject;

    if (assertion.getVersion() != null) {
        domElement.setAttributeNS(null, Assertion.VERSION_ATTRIB_NAME, assertion.getVersion().toString());
    }

    if (assertion.getIssueInstant() != null) {
        String issueInstantStr = Configuration.getSAMLDateFormatter().print(assertion.getIssueInstant());
        domElement.setAttributeNS(null, Assertion.ISSUE_INSTANT_ATTRIB_NAME, issueInstantStr);
    }

    if (assertion.getID() != null) {
        domElement.setAttributeNS(null, Assertion.ID_ATTRIB_NAME, assertion.getID());
        domElement.setIdAttributeNS(null, Assertion.ID_ATTRIB_NAME, true);
    }
}
 
Example #12
Source Project: MaxKey   Author: shimingxy   File: WebServicePostEncoder.java    License: Apache License 2.0 6 votes vote down vote up
protected String getSignatureAlgorithmURI(Credential credential,
		SecurityConfiguration config) throws MessageEncodingException {

	SecurityConfiguration secConfig;
	if (config != null) {
		secConfig = config;
	} else {
		secConfig = Configuration.getGlobalSecurityConfiguration();
	}

	String signAlgo = secConfig.getSignatureAlgorithmURI(credential);

	if (signAlgo == null) {
		throw new MessageEncodingException(
				"The signing credential's algorithm URI could not be derived");
	}

	return signAlgo;
}
 
Example #13
Source Project: carbon-identity   Author: wso2-attic   File: WSXACMLMessageReceiver.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Constructing the SAML or XACML Objects from a String
 *
 * @param xmlString Decoded SAML or XACML String
 * @return SAML or XACML Object
 * @throws org.wso2.carbon.identity.entitlement.EntitlementException
 */
public XMLObject unmarshall(String xmlString) throws EntitlementException {

    try {
        doBootstrap();
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        documentBuilderFactory.setNamespaceAware(true);

        documentBuilderFactory.setExpandEntityReferences(false);
        documentBuilderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
        SecurityManager securityManager = new SecurityManager();
        securityManager.setEntityExpansionLimit(ENTITY_EXPANSION_LIMIT);
        documentBuilderFactory.setAttribute(SECURITY_MANAGER_PROPERTY, securityManager);

        DocumentBuilder docBuilder = documentBuilderFactory.newDocumentBuilder();
        docBuilder.setEntityResolver(new CarbonEntityResolver());
        Document document = docBuilder.parse(new ByteArrayInputStream(xmlString.trim().getBytes()));
        Element element = document.getDocumentElement();
        UnmarshallerFactory unmarshallerFactory = Configuration.getUnmarshallerFactory();
        Unmarshaller unmarshaller = unmarshallerFactory.getUnmarshaller(element);
        return unmarshaller.unmarshall(element);
    } catch (Exception e) {
        log.error("Error in constructing XML(SAML or XACML) Object from the encoded String", e);
        throw new EntitlementException("Error in constructing XML(SAML or XACML) from the encoded String ", e);
    }
}
 
Example #14
Source Project: carbon-identity   Author: wso2-attic   File: WSXACMLMessageReceiver.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * `
 * Serialize XML objects
 *
 * @param xmlObject : XACML or SAML objects to be serialized
 * @return serialized XACML or SAML objects
 * @throws EntitlementException
 */
private String marshall(XMLObject xmlObject) throws EntitlementException {

    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 byteArrayOutputStream = new ByteArrayOutputStream();
        DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
        DOMImplementationLS impl =
                (DOMImplementationLS) registry.getDOMImplementation("LS");
        LSSerializer writer = impl.createLSSerializer();
        LSOutput output = impl.createLSOutput();
        output.setByteStream(byteArrayOutputStream);
        writer.write(element, output);
        return byteArrayOutputStream.toString();
    } catch (Exception e) {
        log.error("Error Serializing the SAML Response");
        throw new EntitlementException("Error Serializing the SAML Response", e);
    }
}
 
Example #15
Source Project: carbon-identity   Author: wso2-attic   File: Util.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Serializing a SAML2 object into a String
 *
 * @param xmlObject object that needs to serialized.
 * @return serialized object
 * @throws SAML2SSOUIAuthenticatorException
 */
public static String marshall(XMLObject xmlObject) throws SAML2SSOUIAuthenticatorException {

    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) {
        log.error("Error Serializing the SAML Response");
        throw new SAML2SSOUIAuthenticatorException("Error Serializing the SAML Response", e);
    }
}
 
Example #16
Source Project: carbon-identity   Author: wso2-attic   File: IdentityUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Constructing the SAML or XACML Objects from a String
 *
 * @param xmlString Decoded SAML or XACML String
 * @return SAML or XACML Object
 * @throws org.wso2.carbon.identity.base.IdentityException
 */
public static XMLObject unmarshall(String xmlString) throws IdentityException {

    try {
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        documentBuilderFactory.setNamespaceAware(true);

        documentBuilderFactory.setExpandEntityReferences(false);
        documentBuilderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
        org.apache.xerces.util.SecurityManager securityManager = new SecurityManager();
        securityManager.setEntityExpansionLimit(ENTITY_EXPANSION_LIMIT);
        documentBuilderFactory.setAttribute(SECURITY_MANAGER_PROPERTY, securityManager);

        DocumentBuilder docBuilder = documentBuilderFactory.newDocumentBuilder();
        docBuilder.setEntityResolver(new CarbonEntityResolver());
        Document document = docBuilder.parse(new ByteArrayInputStream(xmlString.trim().getBytes(Charsets.UTF_8)));
        Element element = document.getDocumentElement();
        UnmarshallerFactory unmarshallerFactory = Configuration.getUnmarshallerFactory();
        Unmarshaller unmarshaller = unmarshallerFactory.getUnmarshaller(element);
        return unmarshaller.unmarshall(element);
    } catch (ParserConfigurationException | UnmarshallingException | SAXException | IOException e) {
        String message = "Error in constructing XML Object from the encoded String";
        throw IdentityException.error(message, e);
    }
}
 
Example #17
Source Project: carbon-identity   Author: wso2-attic   File: SAMLResponseBuilder.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Build Attribute Statement
 *
 * @param claims
 * @return AttributeStatement
 */
private AttributeStatement buildAttributeStatement(Map<String, String> claims) {
    AttributeStatement attStmt = null;
    if (claims != null) {
        attStmt = new AttributeStatementBuilder().buildObject();
        Iterator<String> ite = claims.keySet().iterator();

        for (int i = 0; i < claims.size(); i++) {
            Attribute attrib = new AttributeBuilder().buildObject();
            String claimUri = ite.next();
            attrib.setName(claimUri);
            // look
            // https://wiki.shibboleth.net/confluence/display/OpenSAML/OSTwoUsrManJavaAnyTypes
            XSStringBuilder stringBuilder =
                    (XSStringBuilder) Configuration.getBuilderFactory()
                            .getBuilder(XSString.TYPE_NAME);
            XSString stringValue =
                    stringBuilder.buildObject(AttributeValue.DEFAULT_ELEMENT_NAME,
                            XSString.TYPE_NAME);
            stringValue.setValue(claims.get(claimUri));
            attrib.getAttributeValues().add(stringValue);
            attStmt.getAttributes().add(attrib);
        }
    }
    return attStmt;
}
 
Example #18
Source Project: carbon-commons   Author: wso2   File: Util.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Constructing the XMLObject Object from a String
 *
 * @param authReqStr
 * @return Corresponding XMLObject which is a SAML2 object
 * @throws Exception
 */
public static XMLObject unmarshall(String authReqStr) throws Exception {
    try {
        doBootstrap();
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        documentBuilderFactory.setNamespaceAware(true);
        DocumentBuilder docBuilder = documentBuilderFactory.newDocumentBuilder();
        Document document = docBuilder.parse(new ByteArrayInputStream(authReqStr.trim().getBytes()));
        Element element = document.getDocumentElement();
        UnmarshallerFactory unmarshallerFactory = Configuration.getUnmarshallerFactory();
        Unmarshaller unmarshaller = unmarshallerFactory.getUnmarshaller(element);
        return unmarshaller.unmarshall(element);
    } catch (Exception e) {
        throw new Exception("Error in constructing AuthRequest from " +
                            "the encoded String ", e);
    }
}
 
Example #19
Source Project: carbon-commons   Author: wso2   File: Util.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example #20
Source Project: cloudstack   Author: apache   File: SAMLUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static String encodeSAMLRequest(XMLObject authnRequest)
        throws MarshallingException, IOException {
    Marshaller marshaller = Configuration.getMarshallerFactory()
            .getMarshaller(authnRequest);
    Element authDOM = marshaller.marshall(authnRequest);
    StringWriter requestWriter = new StringWriter();
    XMLHelper.writeNode(authDOM, requestWriter);
    String requestMessage = requestWriter.toString();
    Deflater deflater = new Deflater(Deflater.DEFLATED, true);
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream(byteArrayOutputStream, deflater);
    deflaterOutputStream.write(requestMessage.getBytes(Charset.forName("UTF-8")));
    deflaterOutputStream.close();
    String encodedRequestMessage = Base64.encodeBytes(byteArrayOutputStream.toByteArray(), Base64.DONT_BREAK_LINES);
    encodedRequestMessage = URLEncoder.encode(encodedRequestMessage, HttpUtils.UTF_8).trim();
    return encodedRequestMessage;
}
 
Example #21
Source Project: micro-integrator   Author: wso2   File: WSXACMLEntitlementServiceClient.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Create the issuer object to be added
 *
 * @return : the issuer of the statements
 */
private static Issuer createIssuer() {

    IssuerBuilder issuer = (IssuerBuilder) org.opensaml.xml.Configuration.getBuilderFactory().
            getBuilder(Issuer.DEFAULT_ELEMENT_NAME);
    Issuer issuerObject = issuer.buildObject();
    issuerObject.setValue(ISSUER_URL);
    issuerObject.setSPProvidedID("SPPProvierId");

    return issuerObject;
}
 
Example #22
Source Project: micro-integrator   Author: wso2   File: WSXACMLEntitlementServiceClient.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Create XMLObject from a given QName
 *
 * @param objectQName: QName of the object to be built into a XMLObject
 * @return built xmlObject
 * @throws EntitlementProxyException
 */
private XMLObject buildXMLObject(QName objectQName) throws EntitlementProxyException {

    XMLObjectBuilder builder = org.opensaml.xml.Configuration.getBuilderFactory().getBuilder(objectQName);
    if (builder == null) {
        throw new EntitlementProxyException("Unable to retrieve builder for object QName " + objectQName);
    }
    return builder.buildObject(objectQName.getNamespaceURI(), objectQName.getLocalPart(), objectQName.getPrefix());
}
 
Example #23
Source Project: lams   Author: lamsfoundation   File: AttributeValueTypeMarshaller.java    License: GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
protected void marshallAttributes(XMLObject xmlObject, Element domElement) throws MarshallingException {
    AttributeValueType attributeValue = (AttributeValueType) xmlObject;

    Attr attribute;
    for (Entry<QName, String> entry : attributeValue.getUnknownAttributes().entrySet()) {
        attribute = XMLHelper.constructAttribute(domElement.getOwnerDocument(), entry.getKey());
        attribute.setValue(entry.getValue());
        domElement.setAttributeNodeNS(attribute);
        if (Configuration.isIDAttribute(entry.getKey())
                || attributeValue.getUnknownAttributes().isIDAttribute(entry.getKey())) {
            attribute.getOwnerElement().setIdAttributeNode(attribute, true);
        }
    }
}
 
Example #24
Source Project: lams   Author: lamsfoundation   File: ResourceContentTypeMarshaller.java    License: GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
protected void marshallAttributes(XMLObject xmlObject, Element domElement) throws MarshallingException {
    ResourceContentType resourceContent  = (ResourceContentType)xmlObject;
    
    Attr attribute;
    for (Entry<QName, String> entry : resourceContent.getUnknownAttributes().entrySet()) {
        attribute = XMLHelper.constructAttribute(domElement.getOwnerDocument(), entry.getKey());
        attribute.setValue(entry.getValue());
        domElement.setAttributeNodeNS(attribute);
        if (Configuration.isIDAttribute(entry.getKey())
                || resourceContent.getUnknownAttributes().isIDAttribute(entry.getKey())) {
            attribute.getOwnerElement().setIdAttributeNode(attribute, true);
        }
    }
}
 
Example #25
Source Project: lams   Author: lamsfoundation   File: AuthenticationStatementMarshaller.java    License: GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
protected void marshallAttributes(XMLObject samlElement, Element domElement) throws MarshallingException {
    AuthenticationStatement authenticationStatement = (AuthenticationStatement) samlElement;

    if (authenticationStatement.getAuthenticationMethod() != null) {
        domElement.setAttributeNS(null, AuthenticationStatement.AUTHENTICATIONMETHOD_ATTRIB_NAME,
                authenticationStatement.getAuthenticationMethod());
    }

    if (authenticationStatement.getAuthenticationInstant() != null) {
        String value = Configuration.getSAMLDateFormatter().print(
                authenticationStatement.getAuthenticationInstant());
        domElement.setAttributeNS(null, AuthenticationStatement.AUTHENTICATIONINSTANT_ATTRIB_NAME, value);
    }
}
 
Example #26
Source Project: lams   Author: lamsfoundation   File: ResponseAbstractTypeMarshaller.java    License: GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
protected void marshallAttributes(XMLObject samlElement, Element domElement) throws MarshallingException {
    ResponseAbstractType response = (ResponseAbstractType) samlElement;

    if (response.getID() != null) {
        domElement.setAttributeNS(null, ResponseAbstractType.ID_ATTRIB_NAME, response.getID());
        if (response.getMinorVersion() != 0) {
            domElement.setIdAttributeNS(null, ResponseAbstractType.ID_ATTRIB_NAME, true);
        }
    }

    if (response.getInResponseTo() != null) {
        domElement.setAttributeNS(null, ResponseAbstractType.INRESPONSETO_ATTRIB_NAME, response.getInResponseTo());
    }

    if (response.getIssueInstant() != null) {
        String date = Configuration.getSAMLDateFormatter().print(response.getIssueInstant());
        domElement.setAttributeNS(null, ResponseAbstractType.ISSUEINSTANT_ATTRIB_NAME, date);
    }

    if (response.getMinorVersion() != 0) {
        String minorVersion = Integer.toString(response.getMinorVersion());
        domElement.setAttributeNS(null, ResponseAbstractType.MINORVERSION_ATTRIB_NAME, minorVersion);
        domElement.setAttributeNS(null, ResponseAbstractType.MAJORVERSION_ATTRIB_NAME, "1");
    }

    if (response.getRecipient() != null) {
        domElement.setAttributeNS(null, ResponseAbstractType.RECIPIENT_ATTRIB_NAME, response.getRecipient());
    }
}
 
Example #27
Source Project: lams   Author: lamsfoundation   File: DelegateMarshaller.java    License: GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
protected void marshallAttributes(XMLObject xmlObject, Element domElement) throws MarshallingException {
    Delegate delegate = (Delegate) xmlObject;
    
    if (delegate.getDelegationInstant() != null) {
        String delInstant = Configuration.getSAMLDateFormatter().print(delegate.getDelegationInstant());
        domElement.setAttributeNS(null, Delegate.DELEGATION_INSTANT_ATTRIB_NAME, delInstant);
    }
    if (!DatatypeHelper.isEmpty(delegate.getConfirmationMethod())) {
        domElement.setAttributeNS(null, Delegate.CONFIRMATION_METHOD_ATTRIB_NAME, delegate.getConfirmationMethod());
    }
    
    super.marshallAttributes(xmlObject, domElement);
}
 
Example #28
Source Project: lams   Author: lamsfoundation   File: HTTPArtifactEncoder.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Builds the SAML 2 artifact for the outgoing message.
 * 
 * @param artifactContext current request context
 * 
 * @return SAML 2 artifact for outgoing message
 * 
 * @throws MessageEncodingException thrown if the artifact can not be created
 */
protected AbstractSAML2Artifact buildArtifact(SAMLMessageContext artifactContext) throws MessageEncodingException {

    SAML2ArtifactBuilder artifactBuilder;
    if (artifactContext.getOutboundMessageArtifactType() != null) {
        artifactBuilder = Configuration.getSAML2ArtifactBuilderFactory().getArtifactBuilder(
                artifactContext.getOutboundMessageArtifactType());
    } else {
        artifactBuilder = Configuration.getSAML2ArtifactBuilderFactory().getArtifactBuilder(defaultArtifactType);
        artifactContext.setOutboundMessageArtifactType(defaultArtifactType);
    }

    AbstractSAML2Artifact artifact = artifactBuilder.buildArtifact(artifactContext);
    if(artifact == null){
        log.error("Unable to build artifact for message to relying party");
        throw new MessageEncodingException("Unable to builder artifact for message to relying party");
    }
    String encodedArtifact = artifact.base64Encode();
    try {
        artifactMap.put(encodedArtifact, artifactContext.getInboundMessageIssuer(), artifactContext
                .getOutboundMessageIssuer(), artifactContext.getOutboundSAMLMessage());
    } catch (MarshallingException e) {
        log.error("Unable to marshall assertion to be represented as an artifact", e);
        throw new MessageEncodingException("Unable to marshall assertion to be represented as an artifact", e);
    }

    return artifact;
}
 
Example #29
Source Project: lams   Author: lamsfoundation   File: EntitiesDescriptorMarshaller.java    License: GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
protected void marshallAttributes(XMLObject samlElement, Element domElement) {

    EntitiesDescriptor entitiesDescriptor = (EntitiesDescriptor) samlElement;

    // Set the ID attribute
    if (entitiesDescriptor.getID() != null) {
        log.debug("Writing ID attribute to EntitiesDescriptor DOM element.");
        domElement.setAttributeNS(null, EntitiesDescriptor.ID_ATTRIB_NAME, entitiesDescriptor.getID());
        domElement.setIdAttributeNS(null, EntitiesDescriptor.ID_ATTRIB_NAME, true);
    }

    // Set the validUntil attribute
    if (entitiesDescriptor.getValidUntil() != null) {
        log.debug("Writting validUntil attribute to EntitiesDescriptor DOM element");
        String validUntilStr = Configuration.getSAMLDateFormatter().print(entitiesDescriptor.getValidUntil());
        domElement.setAttributeNS(null, TimeBoundSAMLObject.VALID_UNTIL_ATTRIB_NAME, validUntilStr);
    }

    // Set the cacheDuration attribute
    if (entitiesDescriptor.getCacheDuration() != null) {
        log.debug("Writting cacheDuration attribute to EntitiesDescriptor DOM element");
        String cacheDuration = XMLHelper.longToDuration(entitiesDescriptor.getCacheDuration());
        domElement.setAttributeNS(null, CacheableSAMLObject.CACHE_DURATION_ATTRIB_NAME, cacheDuration);
    }

    // Set the Name attribute
    if (entitiesDescriptor.getName() != null) {
        log.debug("Writting Name attribute to EntitiesDescriptor DOM element");
        domElement.setAttributeNS(null, EntitiesDescriptor.NAME_ATTRIB_NAME, entitiesDescriptor.getName());
    }
}
 
Example #30
Source Project: lams   Author: lamsfoundation   File: AffiliationDescriptorMarshaller.java    License: GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
protected void marshallAttributes(XMLObject samlElement, Element domElement) throws MarshallingException {
    AffiliationDescriptor descriptor = (AffiliationDescriptor) samlElement;

    // Set affiliationOwnerID
    if (descriptor.getOwnerID() != null) {
        domElement.setAttributeNS(null, AffiliationDescriptor.OWNER_ID_ATTRIB_NAME, descriptor.getOwnerID());
    }

    // Set ID
    if (descriptor.getID() != null) {
        domElement.setAttributeNS(null, AffiliationDescriptor.ID_ATTRIB_NAME, descriptor.getID());
        domElement.setIdAttributeNS(null, AffiliationDescriptor.ID_ATTRIB_NAME, true);
    }

    // Set the validUntil attribute
    if (descriptor.getValidUntil() != null) {
        log.debug("Writting validUntil attribute to AffiliationDescriptor DOM element");
        String validUntilStr = Configuration.getSAMLDateFormatter().print(descriptor.getValidUntil());
        domElement.setAttributeNS(null, TimeBoundSAMLObject.VALID_UNTIL_ATTRIB_NAME, validUntilStr);
    }

    // Set the cacheDuration attribute
    if (descriptor.getCacheDuration() != null) {
        log.debug("Writting cacheDuration attribute to AffiliationDescriptor DOM element");
        String cacheDuration = XMLHelper.longToDuration(descriptor.getCacheDuration());
        domElement.setAttributeNS(null, CacheableSAMLObject.CACHE_DURATION_ATTRIB_NAME, cacheDuration);
    }

    Attr attribute;
    for (Entry<QName, String> entry : descriptor.getUnknownAttributes().entrySet()) {
        attribute = XMLHelper.constructAttribute(domElement.getOwnerDocument(), entry.getKey());
        attribute.setValue(entry.getValue());
        domElement.setAttributeNodeNS(attribute);
        if (Configuration.isIDAttribute(entry.getKey())
                || descriptor.getUnknownAttributes().isIDAttribute(entry.getKey())) {
            attribute.getOwnerElement().setIdAttributeNode(attribute, true);
        }
    }
}