Java Code Examples for org.apache.cxf.helpers.DOMUtils

The following examples show how to use org.apache.cxf.helpers.DOMUtils. These examples are extracted from open source projects. 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: steady   Source File: AbstractSTSClient.java    License: Apache License 2.0 6 votes vote down vote up
protected String findMEXLocation(Element ref) {
    Element el = DOMUtils.getFirstElement(ref);
    while (el != null) {
        if (el.getLocalName().equals("Address")
            && VersionTransformer.isSupported(el.getNamespaceURI())
            && "MetadataReference".equals(ref.getLocalName())) {
            return DOMUtils.getContent(el);
        } else {
            String ad = findMEXLocation(el);
            if (ad != null) {
                return ad;
            }
        }
        el = DOMUtils.getNextElement(el);
    }
    return null;
}
 
Example 2
Source Project: steady   Source File: AbstractSTSClient.java    License: Apache License 2.0 6 votes vote down vote up
protected String findMEXLocation(Element ref) {
    Element el = DOMUtils.getFirstElement(ref);
    while (el != null) {
        if (el.getLocalName().equals("Address")
            && VersionTransformer.isSupported(el.getNamespaceURI())
            && "MetadataReference".equals(ref.getLocalName())) {
            return DOMUtils.getContent(el);
        } else {
            String ad = findMEXLocation(el);
            if (ad != null) {
                return ad;
            }
        }
        el = DOMUtils.getNextElement(el);
    }
    return null;
}
 
Example 3
Source Project: steady   Source File: AbstractSTSClient.java    License: Apache License 2.0 6 votes vote down vote up
protected Element getDelegationSecurityToken(Object delegationObject) throws Exception {
    if (delegationObject != null) {
        final boolean isString = delegationObject instanceof String;
        final boolean isElement = delegationObject instanceof Element; 
        final boolean isCallbackHandler = delegationObject instanceof CallbackHandler;
        if (isString || isElement || isCallbackHandler) {
            if (isString) {
                final Document doc =
                    DOMUtils.readXml(new StringReader((String) delegationObject));
                return doc.getDocumentElement();
            } else if (isElement) {
                return (Element) delegationObject;
            } else {
                DelegationCallback callback = new DelegationCallback(message);
                ((CallbackHandler)delegationObject).handle(new Callback[]{callback});
                return callback.getToken();
            }
        }
    }
    return null;
}
 
Example 4
Source Project: cxf   Source File: SCTValidatorTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Test an invalid SecurityContextToken
 */
@org.junit.Test
public void testInvalidSecurityContextToken() throws Exception {
    TokenValidator sctValidator = new SCTValidator();
    TokenValidatorParameters validatorParameters = createValidatorParameters();
    TokenRequirements tokenRequirements = validatorParameters.getTokenRequirements();

    // Create a ValidateTarget consisting of a SecurityContextToken
    Document doc = DOMUtils.createDocument();
    SecurityContextToken sct = new SecurityContextToken(doc);
    ReceivedToken validateTarget = new ReceivedToken(sct.getElement());
    tokenRequirements.setValidateTarget(validateTarget);
    validatorParameters.setToken(validateTarget);

    assertTrue(sctValidator.canHandleToken(validateTarget));

    TokenValidatorResponse validatorResponse =
        sctValidator.validateToken(validatorParameters);
    assertNotNull(validatorResponse);
    assertNotNull(validatorResponse.getToken());
    assertTrue(validatorResponse.getToken().getState() == STATE.INVALID);
}
 
Example 5
Source Project: steady   Source File: WSSUsernameCallbackHandler.java    License: Apache License 2.0 6 votes vote down vote up
public void handle(Callback[] callbacks)
    throws IOException, UnsupportedCallbackException {
    for (int i = 0; i < callbacks.length; i++) {
        if (callbacks[i] instanceof DelegationCallback) {
            DelegationCallback callback = (DelegationCallback) callbacks[i];
            Message message = callback.getCurrentMessage();
            
            String username = 
                (String)message.getContextualProperty(SecurityConstants.USERNAME);
            if (username != null) {
                Node contentNode = message.getContent(Node.class);
                Document doc = null;
                if (contentNode != null) {
                    doc = contentNode.getOwnerDocument();
                } else {
                    doc = DOMUtils.createDocument();
                }
                UsernameToken usernameToken = createWSSEUsernameToken(username, doc);
                callback.setToken(usernameToken.getElement());
            }
        } else {
            throw new UnsupportedCallbackException(callbacks[i], "Unrecognized Callback");
        }
    }
}
 
Example 6
Source Project: cxf   Source File: MemoryResourceManager.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public ReferenceParametersType create(Representation initRepresentation) {
    // Store xmlResource
    String uuid = UUID.randomUUID().toString();
    Element representationEl = (Element) initRepresentation.getAny();
    if (representationEl == null) {
        storage.put(uuid, "");
    } else {
        storage.put(uuid, StaxUtils.toString(representationEl));
    }

    Element uuidEl = DOMUtils.getEmptyDocument().createElementNS(REF_NAMESPACE, REF_LOCAL_NAME);
    uuidEl.setTextContent(uuid);

    // Create referenceParameter
    ReferenceParametersType refParam = new ReferenceParametersType();
    refParam.getAny().add(uuidEl);
    return refParam;
}
 
Example 7
Source Project: steady   Source File: AbstractSTSClient.java    License: Apache License 2.0 6 votes vote down vote up
protected String findID(Element rar, Element rur, Element rst) {
    String id = null;
    if (rst != null) {
        QName elName = DOMUtils.getElementQName(rst);
        if (elName.equals(new QName(WSConstants.SAML_NS, "Assertion"))
            && rst.hasAttributeNS(null, "AssertionID")) {
            id = rst.getAttributeNS(null, "AssertionID");
        } else if (elName.equals(new QName(WSConstants.SAML2_NS, "Assertion"))
            && rst.hasAttributeNS(null, "ID")) {
            id = rst.getAttributeNS(null, "ID");
        }
        if (id == null) {
            id = this.getIDFromSTR(rst);
        }
    }
    if (id == null && rar != null) {
        id = this.getIDFromSTR(rar);
    }
    if (id == null && rur != null) {
        id = this.getIDFromSTR(rur);
    }
    if (id == null && rst != null) {
        id = rst.getAttributeNS(WSConstants.WSU_NS, "Id");
    }
    return id;
}
 
Example 8
Source Project: cxf   Source File: W3CDOMStreamWriter.java    License: Apache License 2.0 6 votes vote down vote up
protected void setChild(Element element, boolean append) {
    Node appendedChildNode = null;
    if (currentNode != null) {
        stack.push(currentNode);
        if (append) {
            appendedChildNode = currentNode.appendChild(element);
        }
    } else {
        if (append) {
            appendedChildNode = document.appendChild(element);
        }
    }
    if (!(context instanceof W3CNamespaceContext)) {
        // set the outside namespace context
        W3CNamespaceContext childContext = new W3CNamespaceContext();
        childContext.setOutNamespaceContext(context);
        context = childContext;
    }
    ((W3CNamespaceContext)context).setElement(element);
    if (appendedChildNode != null) {
        currentNode = org.apache.cxf.helpers.DOMUtils.getDomElement(appendedChildNode);
    } else {
        currentNode = element;
    }
}
 
Example 9
Source Project: cxf   Source File: HandlerInvocationTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testSOAPHandlerHandleMessageThrowsSOAPFaultExceptionServerInbound() throws PingException {
    try {
        handlerTest.pingWithArgs("soapHandler3 inbound throw SOAPFaultExceptionWDetail");
        fail("did not get expected SOAPFaultException");
    } catch (SOAPFaultException e) {
        assertEquals("HandleMessage throws exception", e.getMessage());
        SOAPFault fault = e.getFault();
        assertNotNull(fault);
        assertEquals(new QName(SOAPConstants.URI_NS_SOAP_ENVELOPE, "Server"),
                     fault.getFaultCodeAsQName());
        assertEquals("http://gizmos.com/orders", fault.getFaultActor());

        Detail detail = fault.getDetail();
        assertNotNull(detail);

        QName nn = new QName("http://gizmos.com/orders/", "order");
        Element el = DOMUtils.getFirstChildWithName(detail, nn);
        assertNotNull(el);
        el.normalize();
        assertEquals("Quantity element does not have a value", el.getFirstChild().getNodeValue());
        el = DOMUtils.getNextElement(el);
        el.normalize();
        assertEquals("Incomplete address: no zip code", el.getFirstChild().getNodeValue());
    }
}
 
Example 10
Source Project: syncope   Source File: SAML2ITCase.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void validateIdpInitiatedLoginResponse() throws Exception {
    assumeTrue(SAML2SPDetector.isSAML2SPAvailable());

    SAML2SPService saml2Service = anonymous.getService(SAML2SPService.class);

    // Create a SAML Response using WSS4J
    SAML2ReceivedResponseTO response = new SAML2ReceivedResponseTO();
    response.setSpEntityID("http://recipient.apache.org/");
    response.setUrlContext("saml2sp");

    org.opensaml.saml.saml2.core.Response samlResponse =
            createResponse(null, true, SAML2Constants.CONF_BEARER, "urn:org:apache:cxf:fediz:idp:realm-B");

    Document doc = DOMUtils.newDocument();
    Element responseElement = OpenSAMLUtil.toDom(samlResponse, doc);
    String responseStr = DOM2Writer.nodeToString(responseElement);

    // Validate the SAML Response
    response.setSamlResponse(Base64.getEncoder().encodeToString(responseStr.getBytes()));
    response.setRelayState("idpInitiated");
    SAML2LoginResponseTO loginResponse = saml2Service.validateLoginResponse(response);
    assertNotNull(loginResponse.getAccessToken());
    assertEquals("puccini", loginResponse.getNameID());
}
 
Example 11
Source Project: cxf   Source File: SCTCancellerTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Try to cancel an invalid SecurityContextToken
 */
@org.junit.Test
public void testCancelInvalidToken() throws Exception {
    TokenCanceller sctCanceller = new SCTCanceller();
    sctCanceller.setVerifyProofOfPossession(false);
    TokenCancellerParameters cancellerParameters = createCancellerParameters();
    TokenRequirements tokenRequirements = cancellerParameters.getTokenRequirements();

    // Create a CancelTarget consisting of a SecurityContextToken
    Document doc = DOMUtils.getEmptyDocument();
    SecurityContextToken sct = new SecurityContextToken(doc);
    ReceivedToken cancelTarget = new ReceivedToken(sct.getElement());
    tokenRequirements.setCancelTarget(cancelTarget);
    cancellerParameters.setToken(cancelTarget);

    assertTrue(sctCanceller.canHandleToken(cancelTarget));

    TokenCancellerResponse cancellerResponse = sctCanceller.cancelToken(cancellerParameters);
    assertNotNull(cancellerResponse);
    assertFalse(cancellerResponse.getToken().getState() == STATE.CANCELLED);
}
 
Example 12
Source Project: cxf   Source File: WSAActionAssertingHandler.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean handleMessage(SOAPMessageContext context) {
    // only inbound messages are of use
    if ((Boolean)context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY)) {
        return true;
    }
    try {
        Element elm = DOMUtils.getFirstElement(context.getMessage().getSOAPHeader());
        while (elm != null) {
            if ("Action".equals(elm.getLocalName()) && elm.getNamespaceURI().contains("addressing")) {
                if (!elm.getTextContent().equals(action)) {
                    throw new RuntimeException("The event sink should have received "
                            + "WSA-Action: " + action + " but received: "
                            + elm.getTextContent());
                }
                return true;
            }
            elm = DOMUtils.getNextElement(elm);
        }
    } catch (SOAPException e) {
        throw new RuntimeException(e);
    }
    throw new RuntimeException("The event sink should have received a WSA-Action associated with"
            + "the notification");
}
 
Example 13
Source Project: cxf   Source File: SamlHeaderOutInterceptor.java    License: Apache License 2.0 6 votes vote down vote up
public void handleMessage(Message message) throws Fault {
    try {
        SamlAssertionWrapper assertionWrapper = createAssertion(message);

        Document doc = DOMUtils.newDocument();
        Element assertionElement = assertionWrapper.toDOM(doc);
        String encodedToken = encodeToken(DOM2Writer.nodeToString(assertionElement));

        Map<String, List<String>> headers = getHeaders(message);

        StringBuilder builder = new StringBuilder();
        builder.append("SAML").append(' ').append(encodedToken);
        headers.put("Authorization",
            CastUtils.cast(Collections.singletonList(builder.toString()), String.class));

    } catch (Exception ex) {
        StringWriter sw = new StringWriter();
        ex.printStackTrace(new PrintWriter(sw));
        LOG.warning(sw.toString());
        throw new Fault(new RuntimeException(ex.getMessage() + ", stacktrace: " + sw.toString()));
    }

}
 
Example 14
Source Project: cxf   Source File: WadlGeneratorTest.java    License: Apache License 2.0 6 votes vote down vote up
private void checkParameter(Element paramEl, Param p) {
    assertEquals(p.getName(), paramEl.getAttribute("name"));
    assertEquals(p.getType(), paramEl.getAttribute("style"));
    assertEquals(p.getSchemaType(), paramEl.getAttribute("type"));
    assertEquals(p.isRepeating(), Boolean.valueOf(paramEl.getAttribute("repeating")));
    assertEquals(p.getDefaultValue(), paramEl.getAttribute("default"));
    Set<String> options = p.getOptions();
    if (options != null) {
        Set<String> actualOptions = new HashSet<>();
        List<Element> els = DOMUtils.getChildrenWithNamespace(paramEl, WadlGenerator.WADL_NS);
        assertFalse(els.isEmpty());
        assertEquals(options.size(), els.size());
        for (Element op : els) {
            actualOptions.add(op.getAttribute("value"));
        }
        assertEquals(options, actualOptions);
    }
    String docs = p.getDocs();
    if (docs != null) {
        checkDocs(paramEl, "", docs, "");
    }
}
 
Example 15
Source Project: cxf   Source File: CorbaStreamFaultInInterceptor.java    License: Apache License 2.0 6 votes vote down vote up
private void createFaultDetail(Document faultData, FaultInfo faultInfo, Fault faultEx) {
    MessagePartInfo partInfo = faultInfo.getMessageParts().get(0);
    QName partInfoName = partInfo.getElementQName();
    Document faultDoc = DOMUtils.getEmptyDocument();
    Element faultElement = faultDoc.createElement("detail");
    Element partElement =
        faultDoc.createElementNS(partInfoName.getNamespaceURI(), partInfoName.getLocalPart());

    Element faultDataElement = (Element) faultData.getFirstChild();
    Node node = faultDataElement.getFirstChild();
    while (node != null) {
        Node importedFaultData = faultDoc.importNode(node, true);
        partElement.appendChild(importedFaultData);
        node = node.getNextSibling();
    }
    faultElement.appendChild(partElement);
    faultEx.setDetail(faultElement);
}
 
Example 16
Source Project: cxf   Source File: WadlGeneratorTest.java    License: Apache License 2.0 6 votes vote down vote up
private void checkGrammarsWithLinks(Element appElement, List<String> links) {
    assertFalse(links.isEmpty());
    List<Element> grammarEls = DOMUtils.getChildrenWithName(appElement, WadlGenerator.WADL_NS,
                                                            "grammars");
    assertEquals(1, grammarEls.size());
    List<Element> schemasEls = DOMUtils.getChildrenWithName(grammarEls.get(0),
                                                            Constants.URI_2001_SCHEMA_XSD,
                                                            "schema");
    assertEquals(0, schemasEls.size());

    List<Element> includeEls = DOMUtils.getChildrenWithName(grammarEls.get(0), WadlGenerator.WADL_NS,
                                                            "include");
    assertEquals(links.size(), includeEls.size());
    for (Element el : includeEls) {
        assertTrue(links.contains(el.getAttribute("href")));
    }
}
 
Example 17
Source Project: steady   Source File: SamlTokenInterceptor.java    License: Apache License 2.0 6 votes vote down vote up
private Header findSecurityHeader(SoapMessage message, boolean create) {
    for (Header h : message.getHeaders()) {
        QName n = h.getName();
        if (n.getLocalPart().equals("Security")
            && (n.getNamespaceURI().equals(WSConstants.WSSE_NS) 
                || n.getNamespaceURI().equals(WSConstants.WSSE11_NS))) {
            return h;
        }
    }
    if (!create) {
        return null;
    }
    Document doc = DOMUtils.createDocument();
    Element el = doc.createElementNS(WSConstants.WSSE_NS, "wsse:Security");
    el.setAttributeNS(WSConstants.XMLNS_NS, "xmlns:wsse", WSConstants.WSSE_NS);
    SoapHeader sh = new SoapHeader(new QName(WSConstants.WSSE_NS, "Security"), el);
    sh.setMustUnderstand(true);
    message.getHeaders().add(sh);
    return sh;
}
 
Example 18
Source Project: steady   Source File: RecipientSignatureTokenBuilder.java    License: Apache License 2.0 6 votes vote down vote up
public Assertion build(Element element, AssertionBuilderFactory factory)
    throws IllegalArgumentException {
    
    SPConstants consts = SP11Constants.SP_NS.equals(element.getNamespaceURI())
        ? SP11Constants.INSTANCE : SP12Constants.INSTANCE;

    RecipientSignatureToken recipientSignatureToken = new RecipientSignatureToken(consts, builder);
    recipientSignatureToken.setOptional(PolicyConstants.isOptional(element));
    recipientSignatureToken.setIgnorable(PolicyConstants.isIgnorable(element));

    Policy policy = builder.getPolicy(DOMUtils.getFirstElement(element));
    policy = policy.normalize(builder.getPolicyRegistry(), false);

    for (Iterator<List<Assertion>> iterator = policy.getAlternatives(); iterator.hasNext();) {
        processAlternative(iterator.next(), recipientSignatureToken);
        break; // TODO process all the token that must be set ..
    }

    return recipientSignatureToken;
}
 
Example 19
Source Project: cxf   Source File: SubscriptionReferenceParsingHandler.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean handleMessage(SOAPMessageContext context) {
    // we are interested only in inbound messages here
    if ((Boolean)context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY)) {
        return true;
    }
    try {
        // read headers
        LOG.finer("Examining header elements");
        Element el = DOMUtils.getFirstElement(context.getMessage().getSOAPHeader());
        while (el != null) {
            if (el.getNamespaceURI().equals(namespace)
                && el.getLocalName().equals(elementName)) {
                LOG.log(Level.FINE, "found UUID parameter in header, uuid={0}", el.getTextContent());
                context.put("uuid", el.getTextContent());
            }
            el = DOMUtils.getNextElement(el);
        }
    } catch (SOAPException e) {
        throw new RuntimeException(e);
    }
    return true;
}
 
Example 20
Source Project: steady   Source File: UsernameTokenInterceptor.java    License: Apache License 2.0 6 votes vote down vote up
private Header findSecurityHeader(SoapMessage message, boolean create) {
    for (Header h : message.getHeaders()) {
        QName n = h.getName();
        if (n.getLocalPart().equals("Security")
            && (n.getNamespaceURI().equals(WSConstants.WSSE_NS) 
                || n.getNamespaceURI().equals(WSConstants.WSSE11_NS))) {
            return h;
        }
    }
    if (!create) {
        return null;
    }
    Document doc = DOMUtils.createDocument();
    Element el = doc.createElementNS(WSConstants.WSSE_NS, "wsse:Security");
    el.setAttributeNS(WSConstants.XMLNS_NS, "xmlns:wsse", WSConstants.WSSE_NS);
    SoapHeader sh = new SoapHeader(new QName(WSConstants.WSSE_NS, "Security"), el);
    sh.setMustUnderstand(true);
    message.getHeaders().add(sh);
    return sh;
}
 
Example 21
Source Project: cxf   Source File: VersionTransformer.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Parse an EndpointReferenceType from a DOM element.  Handles all of
 * the WS-Addressing namespaces currently supported.
 * @param ref
 * @throws JAXBException
 */
public static EndpointReferenceType parseEndpointReference(Element ref) throws JAXBException {
    Element child = DOMUtils.getFirstElement(ref);
    String tns = null;
    while (child != null && tns == null) {
        if (isSupported(child.getNamespaceURI())) {
            tns = child.getNamespaceURI();
        }
        child = DOMUtils.getNextElement(child);
    }
    if (tns == null) {
        return null;
    }
    JAXBContext ctx = getExposedJAXBContext(tns);
    Unmarshaller um = ctx.createUnmarshaller();
    um.setEventHandler(null);
    try {
        JAXBElement<?> o = um.unmarshal(ref, getExposedReferenceType(tns));
        if (o != null) {
            return convertToNative(o.getValue());
        }
        return convertToNative(null);
    } finally {
        JAXBUtils.closeUnmarshaller(um);
    }
}
 
Example 22
Source Project: cxf   Source File: AuthnRequestBuilderTest.java    License: Apache License 2.0 6 votes vote down vote up
@org.junit.Test
public void testCreateLogoutRequest() throws Exception {
    Document doc = DOMUtils.createDocument();

    Issuer issuer =
        SamlpRequestComponentBuilder.createIssuer("http://localhost:9001/app");

    NameIDBean nameIdBean = new NameIDBean();
    nameIdBean.setNameValue("uid=joe,ou=people,ou=saml-demo,o=example.com");
    nameIdBean.setNameQualifier("www.example.com");
    NameID nameID = SAML2ComponentBuilder.createNameID(nameIdBean);

    Date notOnOrAfter = new Date();
    notOnOrAfter.setTime(notOnOrAfter.getTime() + 60L * 1000L);
    LogoutRequest logoutRequest =
        SamlpRequestComponentBuilder.createLogoutRequest(SAMLVersion.VERSION_20, issuer, null, null,
                                                         notOnOrAfter, null, nameID);

    Element policyElement = OpenSAMLUtil.toDom(logoutRequest, doc);
    doc.appendChild(policyElement);
    // String outputString = DOM2Writer.nodeToString(policyElement);
    assertNotNull(policyElement);
}
 
Example 23
Source Project: cxf   Source File: JAXRSClientServerSpringBookTest.java    License: Apache License 2.0 6 votes vote down vote up
private void checkSchemas(String address, String schemaSegment,
                          String includedSchema,
                          String refAttrName) throws Exception {
    WebClient client = WebClient.create(address + schemaSegment);
    WebClient.getConfig(client).getHttpConduit().getClient().setReceiveTimeout(10000000L);
    Document doc = StaxUtils.read(new InputStreamReader(client.get(InputStream.class), StandardCharsets.UTF_8));
    Element root = doc.getDocumentElement();
    assertEquals(Constants.URI_2001_SCHEMA_XSD, root.getNamespaceURI());
    assertEquals("schema", root.getLocalName());
    if (includedSchema != null) {
        List<Element> includeEls = DOMUtils.getChildrenWithName(root,
                                                                Constants.URI_2001_SCHEMA_XSD,
                                                                refAttrName);
        assertEquals(1, includeEls.size());
        String href = includeEls.get(0).getAttribute("schemaLocation");
        assertEquals(address + includedSchema, href);
    }

}
 
Example 24
Source Project: cxf   Source File: SamlEnvelopedInHandler.java    License: Apache License 2.0 5 votes vote down vote up
private Element getActualBody(Element root) {
    Element node = DOMUtils.getFirstElement(root);
    if (node != null) {
        root.removeChild(node);
    }
    return node;
}
 
Example 25
Source Project: steady   Source File: SpnegoContextTokenInInterceptor.java    License: Apache License 2.0 5 votes vote down vote up
private SpnegoTokenContext handleBinaryExchange(
    Element binaryExchange,
    Message message,
    String namespace
) throws Exception {
    if (binaryExchange == null) {
        throw new Exception("No BinaryExchange element received");
    }
    String encoding = binaryExchange.getAttributeNS(null, "EncodingType");
    if (!BinarySecurity.BASE64_ENCODING.equals(encoding)) {
        throw new Exception("Unknown encoding type: " + encoding);
    }

    String valueType = binaryExchange.getAttributeNS(null, "ValueType");
    if (!(namespace + "/spnego").equals(valueType)) {
        throw new Exception("Unknown value type: " + valueType);
    }

    String content = DOMUtils.getContent(binaryExchange);
    byte[] decodedContent = Base64.decode(content);
    
    String jaasContext = 
        (String)message.getContextualProperty(SecurityConstants.KERBEROS_JAAS_CONTEXT_NAME);
    String kerberosSpn = 
        (String)message.getContextualProperty(SecurityConstants.KERBEROS_SPN);
    CallbackHandler callbackHandler = 
        NegotiationUtils.getCallbackHandler(
            message.getContextualProperty(SecurityConstants.CALLBACK_HANDLER), this.getClass()
        );

    SpnegoTokenContext spnegoToken = new SpnegoTokenContext();
    spnegoToken.validateServiceTicket(
        jaasContext, callbackHandler, kerberosSpn, decodedContent
    );
    return spnegoToken;
}
 
Example 26
Source Project: cxf   Source File: WSDLToJavaContainer.java    License: Apache License 2.0 5 votes vote down vote up
private void updateWSDLImports(Element el, Map<String, String> wsdlSourceMap) {
    List<Element> imps = DOMUtils.getChildrenWithName(el,
                                                      WSDLConstants.QNAME_IMPORT.getNamespaceURI(),
                                                      "import");
    for (Element e : imps) {
        String ns = e.getAttribute("namespace");
        e.setAttribute("location", wsdlSourceMap.get(ns));
    }
}
 
Example 27
Source Project: cxf   Source File: SimpleBatchSTSClient.java    License: Apache License 2.0 5 votes vote down vote up
protected byte[] decryptKey(Element child) throws TrustException, WSSecurityException {
    String encryptionAlgorithm = X509Util.getEncAlgo(child);
    // For the SPNEGO case just return the decoded cipher value and decrypt it later
    if (encryptionAlgorithm != null && encryptionAlgorithm.endsWith("spnego#GSS_Wrap")) {
        // Get the CipherValue
        Element tmpE =
            XMLUtils.getDirectChildElement(child, "CipherData", WSS4JConstants.ENC_NS);
        byte[] cipherValue = null;
        if (tmpE != null) {
            tmpE =
                XMLUtils.getDirectChildElement(tmpE, "CipherValue", WSS4JConstants.ENC_NS);
            if (tmpE != null) {
                String content = DOMUtils.getContent(tmpE);
                cipherValue = Base64.getMimeDecoder().decode(content);
            }
        }
        if (cipherValue == null) {
            throw new WSSecurityException(WSSecurityException.ErrorCode.INVALID_SECURITY, "noCipher");
        }
        return cipherValue;
    }
    try {
        EncryptedKeyProcessor proc = new EncryptedKeyProcessor();
        RequestData data = new RequestData();
        data.setWssConfig(WSSConfig.getNewInstance());
        data.setDecCrypto(createCrypto(true));
        data.setCallbackHandler(createHandler());

        WSDocInfo docInfo = new WSDocInfo(child.getOwnerDocument());
        data.setWsDocInfo(docInfo);

        List<WSSecurityEngineResult> result = proc.handleToken(child, data);
        return
            (byte[])result.get(0).get(
                WSSecurityEngineResult.TAG_SECRET
            );
    } catch (IOException e) {
        throw new TrustException("ENCRYPTED_KEY_ERROR", e, LOG);
    }
}
 
Example 28
Source Project: cxf   Source File: AbstractXOPType.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void addToSchemaElement(XmlSchemaElement schemaElement) {
    if (expectedContentTypes != null) {
        Map<String, Node> extAttrMap = new HashMap<>();
        Attr theAttr = DOMUtils.getEmptyDocument().createAttributeNS(XML_MIME_NS, "xmime");
        theAttr.setNodeValue(expectedContentTypes);
        extAttrMap.put("xmime", theAttr);
        schemaElement.addMetaInfo(Constants.MetaDataConstants.EXTERNAL_ATTRIBUTES, extAttrMap);
    }
}
 
Example 29
Source Project: cxf   Source File: XSLTResourceTransformer.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public ResourceValidator transform(Representation newRepresentation, Representation oldRepresentation) {
    Document doc = DOMUtils.createDocument();
    Node representation = (Node) newRepresentation.getAny();
    Node importedNode = doc.importNode(representation, true);
    doc.appendChild(importedNode);
    Document result = XSLTUtils.transform(templates, doc);
    newRepresentation.setAny(result.getDocumentElement());
    return validator;
}
 
Example 30
Source Project: steady   Source File: AbstractSTSClient.java    License: Apache License 2.0 5 votes vote down vote up
protected byte[] decryptKey(Element child) throws TrustException, WSSecurityException {
    String encryptionAlgorithm = X509Util.getEncAlgo(child);
    // For the SPNEGO case just return the decoded cipher value and decrypt it later
    if (encryptionAlgorithm != null && encryptionAlgorithm.endsWith("spnego#GSS_Wrap")) {
        // Get the CipherValue
        Element tmpE = 
            WSSecurityUtil.getDirectChildElement(child, "CipherData", WSConstants.ENC_NS);
        byte[] cipherValue = null;
        if (tmpE != null) {
            tmpE = 
                WSSecurityUtil.getDirectChildElement(tmpE, "CipherValue", WSConstants.ENC_NS);
            if (tmpE != null) {
                String content = DOMUtils.getContent(tmpE);
                cipherValue = Base64.decode(content);
            }
        }
        if (cipherValue == null) {
            throw new WSSecurityException(WSSecurityException.INVALID_SECURITY, "noCipher");
        }
        return cipherValue;
    } else {
        try {
            EncryptedKeyProcessor proc = new EncryptedKeyProcessor();
            WSDocInfo docInfo = new WSDocInfo(child.getOwnerDocument());
            RequestData data = new RequestData();
            data.setWssConfig(WSSConfig.getNewInstance());
            data.setDecCrypto(createCrypto(true));
            data.setCallbackHandler(createHandler());
            List<WSSecurityEngineResult> result =
                proc.handleToken(child, data, docInfo);
            return 
                (byte[])result.get(0).get(
                    WSSecurityEngineResult.TAG_SECRET
                );
        } catch (IOException e) {
            throw new TrustException("ENCRYPTED_KEY_ERROR", LOG, e);
        }
    }
}