Package org.opensaml.xml

Examples of org.opensaml.xml.XMLObjectBuilderFactory


    }

    public static Response createErrorResponse(XACMLPolicyQueryType inResponseTo, Exception e) {

        // get a builder factory
        XMLObjectBuilderFactory builderFactory = Configuration.getBuilderFactory();

        /* prepare the response */

        ResponseBuilder responseBuilder = (ResponseBuilder) builderFactory.getBuilder(Response.DEFAULT_ELEMENT_NAME);
        Response response = responseBuilder.buildObject();

        // set a few attributes for the response
        response.setID("_" + UUID.randomUUID().toString());
        response.setVersion(SAMLVersion.VERSION_20);
        response.setIssueInstant(new DateTime());
        response.setInResponseTo(inResponseTo.getID());

        /* add the Status element */

        // build a status object
        StatusBuilder statusBuilder = (StatusBuilder) builderFactory.getBuilder(Status.DEFAULT_ELEMENT_NAME);
        Status status = statusBuilder.buildObject();

        // build a status code object
        StatusCodeBuilder statusCodeBuilder = (StatusCodeBuilder) builderFactory.getBuilder(StatusCode.DEFAULT_ELEMENT_NAME);
        StatusCode statusCode = statusCodeBuilder.buildObject();

        // TODO now discriminates by exception but the code must be improved

        if (e instanceof VersionMismatchException) {

            statusCode.setValue(StatusCode.VERSION_MISMATCH_URI);

        } else if (e instanceof MissingIssuerException || e instanceof WrongFormatIssuerException) {

            // set the status code

            statusCode.setValue(StatusCode.REQUESTER_URI);

            // set status message with some details, when provided

            if (e.getMessage() != null) {

                StatusMessageBuilder statusMessageBuilder = (StatusMessageBuilder) builderFactory.getBuilder(StatusMessage.DEFAULT_ELEMENT_NAME);

                StatusMessage statusMessage = statusMessageBuilder.buildObject();

                statusMessage.setMessage(e.getMessage());

View Full Code Here


    // TODO this method is too long, should be split
    public static Response createResponse(XACMLPolicyQueryType inResponseTo, List<XACMLObject> policyObjects,
            HttpServletRequest request) {

        // get a builder factory
        XMLObjectBuilderFactory builderFactory = Configuration.getBuilderFactory();

        /* prepare the Response object to return */

        // build a response object
        ResponseBuilder responseBuilder = (ResponseBuilder) builderFactory.getBuilder(Response.DEFAULT_ELEMENT_NAME);
        Response response = responseBuilder.buildObject();

        // set a few attributes for the response
        response.setID("_" + UUID.randomUUID().toString());
        response.setVersion(SAMLVersion.VERSION_20);
        response.setIssueInstant(new DateTime());
        response.setInResponseTo(inResponseTo.getID());

        /* add the Assertion element */

        // build an assertion object
        AssertionBuilder assertionBuilder = (AssertionBuilder) builderFactory.getBuilder(Assertion.DEFAULT_ELEMENT_NAME);
        Assertion assertion = assertionBuilder.buildObject();

        // set a few attributes for the assertion
        assertion.setID("_" + UUID.randomUUID().toString());
        assertion.setVersion(SAMLVersion.VERSION_20);
        assertion.setIssueInstant(new DateTime());

        // build an issuer object
        IssuerBuilder issuerBuilder = (IssuerBuilder) builderFactory.getBuilder(Issuer.DEFAULT_ELEMENT_NAME);
        Issuer issuer = issuerBuilder.buildObject();

       
        String defaultEntityId = String.format("%s://%s:%s/%s/services/ProvisioningService",
                request.getScheme(),
                request.getServerName(),
                request.getServerPort(),
                PAPConfiguration.DEFAULT_WEBAPP_CONTEXT);
       
        PAPConfiguration conf = PAPConfiguration.instance();
       
        String issuerValue = conf.getString(PAPConfiguration.STANDALONE_SERVICE_STANZA+".entity_id", defaultEntityId);

        issuer.setValue(issuerValue);

        assertion.setIssuer(issuer);

        /* build policy statements objects */

        XACMLPolicyStatementTypeImplBuilder policyStatementBuilder = (XACMLPolicyStatementTypeImplBuilder) builderFactory.getBuilder(XACMLPolicyStatementType.TYPE_NAME_XACML20);

        XACMLPolicyStatementType policyStatement = policyStatementBuilder.buildObject(Statement.DEFAULT_ELEMENT_NAME,
                                                                                      XACMLPolicyStatementType.TYPE_NAME_XACML20);

        Iterator<XACMLObject> iterator = policyObjects.iterator();

        while (iterator.hasNext()) {

            XACMLObject xacmlObject = iterator.next();

            if (xacmlObject instanceof PolicySetType) {

                policyStatement.getPolicySets().add((PolicySetType) xacmlObject);

                // if (xacmlObject instanceof PolicySetTypeString) {
                // ((PolicySetTypeString) xacmlObject).releasePolicySetType();
                // }

            } else {

                policyStatement.getPolicies().add((PolicyType) xacmlObject);

                // if (xacmlObject instanceof PolicyTypeString) {
                // ((PolicyTypeString) xacmlObject).releasePolicyType();
                // }

            }

            // add the statement to the assertion
            assertion.getStatements().add(policyStatement);
        }

        // add the assertion to the response
        response.getAssertions().add(assertion);

        /* add the Status element */

        // build a status object
        StatusBuilder statusBuilder = (StatusBuilder) builderFactory.getBuilder(Status.DEFAULT_ELEMENT_NAME);
        Status status = statusBuilder.buildObject();

        // build a status code object
        StatusCodeBuilder statusCodeBuilder = (StatusCodeBuilder) builderFactory.getBuilder(StatusCode.DEFAULT_ELEMENT_NAME);
        StatusCode statusCode = statusCodeBuilder.buildObject();

        statusCode.setValue(StatusCode.SUCCESS_URI);

        status.setStatusCode(statusCode);
View Full Code Here

        }
        if (relayStateValue.length() > 80) {
            throw new IllegalArgumentException("Relay state can't exceed size 80 when using ECP profile");
        }

        XMLObjectBuilderFactory builderFactory = Configuration.getBuilderFactory();
        SAMLObjectBuilder<RelayState> relayStateBuilder = (SAMLObjectBuilder<RelayState>) builderFactory.getBuilder(RelayState.DEFAULT_ELEMENT_NAME);
        RelayState relayState = relayStateBuilder.buildObject();
        relayState.setSOAP11Actor(RelayState.SOAP11_ACTOR_NEXT);
        relayState.setSOAP11MustUnderstand(true);
        relayState.setValue(relayStateValue);
        return relayState;
View Full Code Here

    }

    protected Envelope buildPAOSMessage(SAMLObject samlMessage, XMLObject outboundEnvelope) {

        Envelope envelope;
        XMLObjectBuilderFactory builderFactory = Configuration.getBuilderFactory();

        if (outboundEnvelope != null && outboundEnvelope instanceof Envelope) {
            // We already have a complete envelope with specified headers that we want to keep.
            envelope = (Envelope) outboundEnvelope;
        } else {
            // We don't have an existing envelope, so we create it.
            SOAPObjectBuilder<Envelope> envBuilder = (SOAPObjectBuilder<Envelope>) builderFactory.getBuilder(Envelope.DEFAULT_ELEMENT_NAME);
            envelope = envBuilder.buildObject();
        }

        SOAPObjectBuilder<Body> bodyBuilder = (SOAPObjectBuilder<Body>) builderFactory.getBuilder(Body.DEFAULT_ELEMENT_NAME);
        Body body = bodyBuilder.buildObject();
        body.getUnknownXMLObjects().add(samlMessage);
        envelope.setBody(body);

        return envelope;
View Full Code Here

                                                   DateTime expirationTime, RahasData data) throws Exception {


        // TODO modify these to use proper SAML apis

        XMLObjectBuilderFactory builderFactory = Configuration.getBuilderFactory();
        SAMLObjectBuilder<Subject> subjectBuilder =
                (SAMLObjectBuilder<Subject>) builderFactory.getBuilder(Subject.DEFAULT_ELEMENT_NAME);
        Subject subject = subjectBuilder.buildObject();
        Element keyInfoElem = null;

        // If it is a Symmetric Key
        if (data.getKeyType().endsWith(RahasConstants.KEY_TYPE_SYMM_KEY)) {

            isSymmetricKeyBasedHoK = true;
            Element encryptedKeyElem;
            X509Certificate serviceCert = null;
            try {

                // Get ApliesTo to figure out which service to issue the token
                // for
                serviceCert = config.getServiceCert(crypto, data.getAppliesToAddress());

                // Create the encrypted key
                WSSecEncryptedKey encrKeyBuilder = new WSSecEncryptedKey();

                // Use thumbprint id
                encrKeyBuilder
                        .setKeyIdentifierType(WSConstants.THUMBPRINT_IDENTIFIER);

                // SEt the encryption cert
                encrKeyBuilder.setUseThisCert(serviceCert);

                // set keysize
                int keysize = data.getKeysize();
                keysize = (keysize != -1) ? keysize : config.keySize;

                // TODO setting keysize is removed with wss4j 1.6 migration - do we actually need this ?

                encrKeyBuilder.setEphemeralKey(TokenIssuerUtil.getSharedSecret(
                        data, config.keyComputation, keysize));


                // Set key encryption algo
                encrKeyBuilder
                        .setKeyEncAlgo(EncryptionConstants.ALGO_ID_KEYTRANSPORT_RSA15);

                // Build
                encrKeyBuilder.prepare(doc, crypto);

                // Extract the base64 encoded secret value
                byte[] tempKey = new byte[keysize / 8];
                System.arraycopy(encrKeyBuilder.getEphemeralKey(), 0, tempKey,
                        0, keysize / 8);

                data.setEphmeralKey(tempKey);

                // Extract the Encryptedkey DOM element
                encryptedKeyElem = encrKeyBuilder.getEncryptedKeyElement();
            } catch (WSSecurityException e) {
                throw new TrustException(
                        "errorInBuildingTheEncryptedKeyForPrincipal",
                        new String[]{serviceCert.getSubjectDN().getName()},
                        e);
            }

            keyInfoElem = doc.createElementNS(WSConstants.SIG_NS,
                    "ds:KeyInfo");
            ((OMElement) encryptedKeyElem).declareNamespace(WSConstants.SIG_NS,
                    WSConstants.SIG_PREFIX);
            ((OMElement) encryptedKeyElem).declareNamespace(WSConstants.ENC_NS,
                    WSConstants.ENC_PREFIX);

            keyInfoElem.appendChild(encryptedKeyElem);

        }

        // If it is a public Key
        else if(data.getKeyType().endsWith(RahasConstants.KEY_TYPE_PUBLIC_KEY)){
            try {
                String subjectNameId = data.getPrincipal().getName();

                //Create NameID and attach it to the subject
                NameIDBuilder nb = new NameIDBuilder();
                NameID nameID = nb.buildObject();
                nameID.setValue(subjectNameId);
                nameID.setFormat(NameIdentifier.EMAIL);
                subject.setNameID(nameID);


                // Create the ds:KeyValue element with the ds:X509Data
                X509Certificate clientCert = data.getClientCert();

                if (clientCert == null) {
                    // TODO are we always looking up by alias ? Dont we need to lookup by any other attribute ?
                    clientCert = CommonUtil.getCertificateByAlias(crypto, data.getPrincipal().getName());
                }

                byte[] clientCertBytes = clientCert.getEncoded();

                String base64Cert = Base64.encode(clientCertBytes);

                Text base64CertText = doc.createTextNode(base64Cert);

                //-----------------------------------------

                Element x509CertElem = doc.createElementNS(WSConstants.SIG_NS,
                        "ds:X509Certificate");
                x509CertElem.appendChild(base64CertText);
                Element x509DataElem = doc.createElementNS(WSConstants.SIG_NS,
                        "ds:X509Data");
                x509DataElem.appendChild(x509CertElem);


                if (x509DataElem != null) {
                    keyInfoElem = doc.createElementNS(WSConstants.SIG_NS, "ds:KeyInfo");
                    ((OMElement) x509DataElem).declareNamespace(
                            WSConstants.SIG_NS, WSConstants.SIG_PREFIX);
                    keyInfoElem.appendChild(x509DataElem);
                }

            } catch (Exception e) {
                throw new TrustException("samlAssertionCreationError", e);
            }
        }

        // Unmarshall the keyInfo DOM element into an XMLObject
        String keyInfoElementString = keyInfoElem.toString();
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        documentBuilderFactory.setNamespaceAware(true);
        DocumentBuilder docBuilder = documentBuilderFactory.newDocumentBuilder();
        Document document = docBuilder.parse(new ByteArrayInputStream(keyInfoElementString.trim().getBytes()));
        Element element = document.getDocumentElement();


        // Get appropriate unmarshaller
        UnmarshallerFactory unmarshallerFactory = Configuration.getUnmarshallerFactory();
        Unmarshaller unmarshaller = unmarshallerFactory.getUnmarshaller(element);

        // Unmarshall using the document root element, an keyInfo element in this case
        XMLObject keyInfoElement = null;
        try {
            keyInfoElement = unmarshaller.unmarshall(element);
        } catch (UnmarshallingException e) {
            throw new TrustException("Error unmarshalling KeyInfo Element", e);
        }


        //Build the Subject Confirmation
        SAMLObjectBuilder<SubjectConfirmation> subjectConfirmationBuilder =
                (SAMLObjectBuilder<SubjectConfirmation>) builderFactory.getBuilder(SubjectConfirmation.DEFAULT_ELEMENT_NAME);
        SubjectConfirmation subjectConfirmation = subjectConfirmationBuilder.buildObject();

        //Set the subject Confirmation method
        subjectConfirmation.setMethod("urn:oasis:names:tc:SAML:2.0:cm:holder-of-key");

        SAMLObjectBuilder<KeyInfoConfirmationDataType> keyInfoSubjectConfirmationDataBuilder =
                (SAMLObjectBuilder<KeyInfoConfirmationDataType>) builderFactory.getBuilder(KeyInfoConfirmationDataType.TYPE_NAME);

        //Build the subject confirmation data element
        KeyInfoConfirmationDataType scData = keyInfoSubjectConfirmationDataBuilder.
                buildObject(SubjectConfirmationData.DEFAULT_ELEMENT_NAME, KeyInfoConfirmationDataType.TYPE_NAME);
View Full Code Here

     * This method creates a subject element with the bearer subject confirmation method
     * @param data RahasData element
     * @return  SAML 2.0 Subject element with Bearer subject confirmation
     */
    private Subject createSubjectWithBearerSC(RahasData data){
        XMLObjectBuilderFactory builderFactory = Configuration.getBuilderFactory();
        SAMLObjectBuilder<Subject> subjectBuilder =
                (SAMLObjectBuilder<Subject>) builderFactory.getBuilder(Subject.DEFAULT_ELEMENT_NAME);
        Subject subject = subjectBuilder.buildObject();

        //Create NameID and attach it to the subject
        NameID nameID = new NameIDBuilder().buildObject();
        nameID.setValue(data.getPrincipal().getName());
        nameID.setFormat(NameIdentifier.EMAIL);
        subject.setNameID(nameID);

        //Build the Subject Confirmation
        SAMLObjectBuilder<SubjectConfirmation> subjectConfirmationBuilder =
                (SAMLObjectBuilder<SubjectConfirmation>) builderFactory.getBuilder(SubjectConfirmation.DEFAULT_ELEMENT_NAME);
        SubjectConfirmation subjectConfirmation = subjectConfirmationBuilder.buildObject();

        //Set the subject Confirmation method
        subjectConfirmation.setMethod("urn:oasis:names:tc:SAML:2.0:cm:bearer");

View Full Code Here

     * @return
     * @throws SAMLException
     */
    private AttributeStatement createAttributeStatement(RahasData data, SAMLTokenIssuerConfig config) throws SAMLException, TrustException {

        XMLObjectBuilderFactory builderFactory = Configuration.getBuilderFactory();
        SAMLObjectBuilder<AttributeStatement> attrStmtBuilder =
                (SAMLObjectBuilder<AttributeStatement>) builderFactory.getBuilder(AttributeStatement.DEFAULT_ELEMENT_NAME);

        SAMLObjectBuilder<Attribute> attrBuilder =
                    (SAMLObjectBuilder<Attribute>) builderFactory.getBuilder(Attribute.DEFAULT_ELEMENT_NAME);

        AttributeStatement attrstmt = attrStmtBuilder.buildObject();

        Attribute[] attributes = null;

        //Call the attribute callback handlers to get any attributes if exists
        if (config.getCallbackHandler() != null) {
            SAMLAttributeCallback cb = new SAMLAttributeCallback(data);
            SAMLCallbackHandler handler = config.getCallbackHandler();
            handler.handle(cb);
            attributes = cb.getSAML2Attributes();
        }
        else if (config.getCallbackHandlerName() != null
                && config.getCallbackHandlerName().trim().length() > 0) {
            SAMLAttributeCallback cb = new SAMLAttributeCallback(data);
            SAMLCallbackHandler handler = null;
            MessageContext msgContext = data.getInMessageContext();
            ClassLoader classLoader = msgContext.getAxisService().getClassLoader();
            Class cbClass = null;
            try {
                cbClass = Loader.loadClass(classLoader, config.getCallbackHandlerName());
            } catch (ClassNotFoundException e) {
                throw new TrustException("cannotLoadPWCBClass", new String[]{config
                        .getCallbackHandlerName()}, e);
            }
            try {
                handler = (SAMLCallbackHandler) cbClass.newInstance();
            } catch (java.lang.Exception e) {
                throw new TrustException("cannotCreatePWCBInstance", new String[]{config
                        .getCallbackHandlerName()}, e);
            }
            handler.handle(cb);
            attributes = cb.getSAML2Attributes();
            // else add the attribute with a default value
        }

        //else add the attribute with a default value
        else {
            Attribute attribute = attrBuilder.buildObject();
            attribute.setName("Name");
            attribute.setNameFormat("urn:oasis:names:tc:SAML:2.0:attrname-format:unspecified");

            XSStringBuilder attributeValueBuilder = (XSStringBuilder) builderFactory
                    .getBuilder(XSString.TYPE_NAME);

            XSString stringValue = attributeValueBuilder.buildObject(
                    AttributeValue.DEFAULT_ELEMENT_NAME, XSString.TYPE_NAME);
            stringValue.setValue("Colombo/Rahas");
View Full Code Here

     * build the authentication statement
     * @param data
     * @return
     */
    private AuthnStatement createAuthnStatement(RahasData data) {
        XMLObjectBuilderFactory builderFactory = Configuration.getBuilderFactory();
        MessageContext inMsgCtx = data.getInMessageContext();

        SAMLObjectBuilder<AuthnStatement> authStmtBuilder =
                (SAMLObjectBuilder<AuthnStatement>) builderFactory.getBuilder(AuthnStatement.DEFAULT_ELEMENT_NAME);

        //build the auth stmt
        AuthnStatement authStmt = authStmtBuilder.buildObject();

        // set the authn instance
        authStmt.setAuthnInstant(new DateTime());

        SAMLObjectBuilder<AuthnContext> authCtxBuilder =
                (SAMLObjectBuilder<AuthnContext>) builderFactory.getBuilder(AuthnContext.DEFAULT_ELEMENT_NAME);
        AuthnContext authContext = authCtxBuilder.buildObject();

        SAMLObjectBuilder<AuthnContextClassRef> authCtxClassRefBuilder =
                (SAMLObjectBuilder<AuthnContextClassRef>) builderFactory.getBuilder(AuthnContextClassRef.DEFAULT_ELEMENT_NAME);
        AuthnContextClassRef authCtxClassRef = authCtxClassRefBuilder.buildObject();
       
        //if username/password based authn
        if (inMsgCtx.getProperty(RahasConstants.USERNAME) != null) {
            authCtxClassRef.setAuthnContextClassRef(AuthnContext.PASSWORD_AUTHN_CTX);
View Full Code Here

            callbackHandler.setIssuer("www.example.com");
            callbackHandler.setSignAssertion(false);
            callbackHandler.setSamlVersion(SAMLVersion.VERSION_20);

            // Create and add a custom Attribute (conditions Object)
            XMLObjectBuilderFactory builderFactory = Configuration.getBuilderFactory();

            SAMLObjectBuilder<Conditions> conditionsV2Builder =
                    (SAMLObjectBuilder<Conditions>) builderFactory.getBuilder(Conditions.DEFAULT_ELEMENT_NAME);
            Conditions conditions = conditionsV2Builder.buildObject();
            DateTime newNotBefore = new DateTime();
            conditions.setNotBefore(newNotBefore);
            conditions.setNotOnOrAfter(newNotBefore.plusMinutes(5));

            XMLObjectBuilder<XSAny> xsAnyBuilder = builderFactory.getBuilder(XSAny.TYPE_NAME);
            XSAny attributeValue = xsAnyBuilder.buildObject(AttributeValue.DEFAULT_ELEMENT_NAME);
            attributeValue.getUnknownXMLObjects().add(conditions);

            List<Object> attributeValues = new ArrayList<Object>();
            attributeValues.add(attributeValue);
View Full Code Here

    @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);
View Full Code Here

TOP

Related Classes of org.opensaml.xml.XMLObjectBuilderFactory

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.