Java Code Examples for org.apache.cxf.binding.soap.SoapMessage#put()

The following examples show how to use org.apache.cxf.binding.soap.SoapMessage#put() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AbstractPolicySecurityTest.java    From steady with Apache License 2.0 6 votes vote down vote up
/**
 * Gets a SoapMessage, but with the needed SecurityConstants in the context properties
 * so that it can be passed to PolicyBasedWSS4JOutInterceptor.
 *
 * @see #getSoapMessageForDom(Document, AssertionInfoMap)
 */
protected SoapMessage getOutSoapMessageForDom(Document doc, AssertionInfoMap aim)
    throws SOAPException {
    SoapMessage msg = this.getSoapMessageForDom(doc, aim);
    msg.put(SecurityConstants.SIGNATURE_PROPERTIES, "outsecurity.properties");
    msg.put(SecurityConstants.ENCRYPT_PROPERTIES, "outsecurity.properties");
    msg.put(SecurityConstants.CALLBACK_HANDLER, TestPwdCallback.class.getName());
    msg.put(SecurityConstants.SIGNATURE_USERNAME, "myalias");
    msg.put(SecurityConstants.ENCRYPT_USERNAME, "myalias");
    
    msg.getExchange().put(Endpoint.class, new MockEndpoint());
    msg.getExchange().put(Bus.class, this.bus);
    msg.put(Message.REQUESTOR_ROLE, true);
    
    return msg;
}
 
Example 2
Source File: AbstractUsernameTokenAuthenticatingInterceptor.java    From steady with Apache License 2.0 6 votes vote down vote up
@Override
public void handleMessage(SoapMessage msg) throws Fault {
    SecurityToken token = msg.get(SecurityToken.class);
    SecurityContext context = msg.get(SecurityContext.class);
    if (token == null || context == null || context.getUserPrincipal() == null) {
        super.handleMessage(msg);
        return;
    }
    UsernameToken ut = (UsernameToken)token;
    
    Subject subject = createSubject(ut.getName(), ut.getPassword(), ut.isHashed(),
                                    ut.getNonce(), ut.getCreatedTime());
    
    SecurityContext sc = doCreateSecurityContext(context.getUserPrincipal(), subject);
    msg.put(SecurityContext.class, sc);
}
 
Example 3
Source File: AbstractUsernameTokenAuthenticatingInterceptor.java    From steady with Apache License 2.0 6 votes vote down vote up
@Override
public void handleMessage(SoapMessage msg) throws Fault {
    SecurityToken token = msg.get(SecurityToken.class);
    SecurityContext context = msg.get(SecurityContext.class);
    if (token == null || context == null || context.getUserPrincipal() == null) {
        super.handleMessage(msg);
        return;
    }
    UsernameToken ut = (UsernameToken)token;
    
    Subject subject = createSubject(ut.getName(), ut.getPassword(), ut.isHashed(),
                                    ut.getNonce(), ut.getCreatedTime());
    
    SecurityContext sc = doCreateSecurityContext(context.getUserPrincipal(), subject);
    msg.put(SecurityContext.class, sc);
}
 
Example 4
Source File: WSS4JOutInterceptorTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testUsernameTokenDigest() throws Exception {
    Document doc = readDocument("wsse-request-clean.xml");
    SoapMessage msg = getSoapMessageForDom(doc);

    WSS4JOutInterceptor ohandler = new WSS4JOutInterceptor();
    PhaseInterceptor<SoapMessage> handler = ohandler.createEndingInterceptor();

    msg.put(ConfigurationConstants.ACTION, ConfigurationConstants.USERNAME_TOKEN);
    msg.put(ConfigurationConstants.SIG_PROP_FILE, "outsecurity.properties");
    msg.put(ConfigurationConstants.USER, "username");
    msg.put("password", "myAliasPassword");
    msg.put(ConfigurationConstants.PASSWORD_TYPE, WSS4JConstants.PW_DIGEST);
    handler.handleMessage(msg);

    doc = msg.getContent(SOAPMessage.class).getSOAPPart();
    assertValid("//wsse:Security", doc);
    assertValid("//wsse:Security/wsse:UsernameToken", doc);
    assertValid("//wsse:Security/wsse:UsernameToken/wsse:Username[text()='username']", doc);
    // Test to see that the password digest is used in the header
    assertInvalid("//wsse:Security/wsse:UsernameToken/wsse:Password[text()='myAliasPassword']", doc);
}
 
Example 5
Source File: WSS4JInInterceptor.java    From steady with Apache License 2.0 5 votes vote down vote up
public final boolean isGET(SoapMessage message) {
    String method = (String)message.get(SoapMessage.HTTP_REQUEST_METHOD);
    boolean isGet = 
        "GET".equals(method) && message.getContent(XMLStreamReader.class) == null;
    if (isGet) {
        //make sure we skip the URIMapping as we cannot apply security requirements to that
        message.put(URIMappingInterceptor.URIMAPPING_SKIP, Boolean.TRUE);
    }
    return isGet;
}
 
Example 6
Source File: AbstractPolicySecurityTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected SoapMessage getSoapMessageForDom(Document doc, AssertionInfoMap aim)
    throws Exception {

    SoapMessage msg = this.getSoapMessageForDom(doc);
    if (aim != null) {
        msg.put(AssertionInfoMap.class, aim);
    }

    return msg;
}
 
Example 7
Source File: WSS4JStaxOutInterceptor.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected void handleSecureMTOM(SoapMessage mc, WSSSecurityProperties secProps) {
    if (mtomEnabled) {
        return;
    }

    //must turn off mtom when using WS-Sec so binary is inlined so it can
    //be properly signed/encrypted/etc...
    String mtomKey = org.apache.cxf.message.Message.MTOM_ENABLED;
    if (Boolean.TRUE.equals(mc.get(mtomKey))) {
        LOG.warning("MTOM will be disabled as the WSS4JOutInterceptor.mtomEnabled property"
                + " is set to false");
    }
    mc.put(mtomKey, Boolean.FALSE);
}
 
Example 8
Source File: WSS4JOutInterceptorTest.java    From steady with Apache License 2.0 5 votes vote down vote up
@Test
public void testUsernameTokenText() throws Exception {
    SOAPMessage saaj = readSAAJDocument("wsse-request-clean.xml");

    WSS4JOutInterceptor ohandler = new WSS4JOutInterceptor();
    PhaseInterceptor<SoapMessage> handler = ohandler.createEndingInterceptor();

    SoapMessage msg = new SoapMessage(new MessageImpl());
    Exchange ex = new ExchangeImpl();
    ex.setInMessage(msg);

    msg.setContent(SOAPMessage.class, saaj);

    msg.put(WSHandlerConstants.ACTION, WSHandlerConstants.USERNAME_TOKEN);
    msg.put(WSHandlerConstants.SIG_PROP_FILE, "outsecurity.properties");
    msg.put(WSHandlerConstants.USER, "username");
    msg.put("password", "myAliasPassword");
    msg.put(WSHandlerConstants.PASSWORD_TYPE, WSConstants.PW_TEXT);
    handler.handleMessage(msg);

    SOAPPart doc = saaj.getSOAPPart();
    assertValid("//wsse:Security", doc);
    assertValid("//wsse:Security/wsse:UsernameToken", doc);
    assertValid("//wsse:Security/wsse:UsernameToken/wsse:Username[text()='username']", doc);
    // Test to see that the plaintext password is used in the header
    assertValid("//wsse:Security/wsse:UsernameToken/wsse:Password[text()='myAliasPassword']", doc);
}
 
Example 9
Source File: SOAPHandlerInterceptor.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
protected MessageContext createProtocolMessageContext(SoapMessage message) {
    SOAPMessageContextImpl sm = new SOAPMessageContextImpl(message);

    Exchange exch = message.getExchange();
    setupBindingOperationInfo(exch, sm);
    SOAPMessage msg = sm.getMessage();
    if (msg != null) {
        try {
            List<SOAPElement> params = new ArrayList<>();
            message.put(MessageContext.REFERENCE_PARAMETERS, params);
            SOAPHeader head = SAAJUtils.getHeader(msg);
            if (head != null) {
                Iterator<Node> it = CastUtils.cast(head.getChildElements());
                while (it != null && it.hasNext()) {
                    Node nd = it.next();
                    if (nd instanceof SOAPElement) {
                        SOAPElement el = (SOAPElement) nd;
                        if (el.hasAttributeNS(Names.WSA_NAMESPACE_NAME, "IsReferenceParameter")
                                && ("1".equals(el.getAttributeNS(Names.WSA_NAMESPACE_NAME,
                                "IsReferenceParameter"))
                                || Boolean.parseBoolean(el.getAttributeNS(Names.WSA_NAMESPACE_NAME,
                                "IsReferenceParameter")))) {
                            params.add(el);
                        }
                    }
                }
            }
            if (isRequestor(message) && msg.getSOAPPart().getEnvelope().getBody() != null
                    && msg.getSOAPPart().getEnvelope().getBody().hasFault()) {
                return null;
            }
        } catch (SOAPException e) {
            throw new Fault(e);
        }
    }

    return sm;
}
 
Example 10
Source File: SamlTokenInterceptor.java    From steady with Apache License 2.0 5 votes vote down vote up
private void processSamlToken(SoapMessage message) {
    Header h = findSecurityHeader(message, false);
    if (h == null) {
        return;
    }
    Element el = (Element)h.getObject();
    Element child = DOMUtils.getFirstElement(el);
    while (child != null) {
        if ("Assertion".equals(child.getLocalName())) {
            try {
                List<WSSecurityEngineResult> samlResults = processToken(child, message);
                if (samlResults != null) {
                    List<WSHandlerResult> results = CastUtils.cast((List<?>)message
                            .get(WSHandlerConstants.RECV_RESULTS));
                    if (results == null) {
                        results = new ArrayList<WSHandlerResult>();
                        message.put(WSHandlerConstants.RECV_RESULTS, results);
                    }
                    WSHandlerResult rResult = new WSHandlerResult(null, samlResults);
                    results.add(0, rResult);

                    assertSamlTokens(message);
                    
                    Principal principal = 
                        (Principal)samlResults.get(0).get(WSSecurityEngineResult.TAG_PRINCIPAL);
                    message.put(WSS4JInInterceptor.PRINCIPAL_RESULT, principal);                   
                    
                    SecurityContext sc = message.get(SecurityContext.class);
                    if (sc == null || sc.getUserPrincipal() == null) {
                        message.put(SecurityContext.class, new DefaultSecurityContext(principal, null));
                    }

                }
            } catch (WSSecurityException ex) {
                throw new Fault(ex);
            }
        }
        child = DOMUtils.getNextElement(child);
    }
}
 
Example 11
Source File: WSS4JOutInterceptorTest.java    From steady with Apache License 2.0 5 votes vote down vote up
@Test
public void testUsernameTokenDigest() throws Exception {
    SOAPMessage saaj = readSAAJDocument("wsse-request-clean.xml");

    WSS4JOutInterceptor ohandler = new WSS4JOutInterceptor();
    PhaseInterceptor<SoapMessage> handler = ohandler.createEndingInterceptor();

    SoapMessage msg = new SoapMessage(new MessageImpl());
    Exchange ex = new ExchangeImpl();
    ex.setInMessage(msg);

    msg.setContent(SOAPMessage.class, saaj);

    msg.put(WSHandlerConstants.ACTION, WSHandlerConstants.USERNAME_TOKEN);
    msg.put(WSHandlerConstants.SIG_PROP_FILE, "outsecurity.properties");
    msg.put(WSHandlerConstants.USER, "username");
    msg.put("password", "myAliasPassword");
    msg.put(WSHandlerConstants.PASSWORD_TYPE, WSConstants.PW_DIGEST);
    handler.handleMessage(msg);

    SOAPPart doc = saaj.getSOAPPart();
    assertValid("//wsse:Security", doc);
    assertValid("//wsse:Security/wsse:UsernameToken", doc);
    assertValid("//wsse:Security/wsse:UsernameToken/wsse:Username[text()='username']", doc);
    // Test to see that the password digest is used in the header
    assertInvalid("//wsse:Security/wsse:UsernameToken/wsse:Password[text()='myAliasPassword']", doc);
}
 
Example 12
Source File: PolicyBasedWSS4JOutInterceptor.java    From steady with Apache License 2.0 5 votes vote down vote up
public void handleMessage(SoapMessage mc) throws Fault {
    if (mc.getContent(SOAPMessage.class) == null) {
        saajOut.handleMessage(mc);
    }
    mc.put(SECURITY_PROCESSED, Boolean.TRUE);
    mc.getInterceptorChain().add(ending);
}
 
Example 13
Source File: PolicyBasedSamlTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
protected void runInInterceptorAndValidateWss(Document document, AssertionInfoMap aim,
                                              List<CoverageType> types) throws Exception {

    PolicyBasedWSS4JInInterceptor inHandler =
        this.getInInterceptor(types);

    SoapMessage inmsg = this.getSoapMessageForDom(document, aim);

    Element securityHeaderElem = WSSecurityUtil.getSecurityHeader(document, "");
    if (securityHeaderElem != null) {
        SoapHeader securityHeader = new SoapHeader(new QName(securityHeaderElem.getNamespaceURI(),
                                                             securityHeaderElem.getLocalName()),
                                                   securityHeaderElem);
        inmsg.getHeaders().add(securityHeader);
    }

    // Necessary because the Bearer Assertion does not have an internal signature
    SamlAssertionValidator assertionValidator = new SamlAssertionValidator();
    assertionValidator.setRequireBearerSignature(false);
    inmsg.put(SecurityConstants.SAML2_TOKEN_VALIDATOR, assertionValidator);
    inmsg.put(SecurityConstants.SAML1_TOKEN_VALIDATOR, assertionValidator);
    inHandler.handleMessage(inmsg);

    for (CoverageType type : types) {
        switch(type) {
        case SIGNED:
            this.verifyWss4jSigResults(inmsg);
            break;
        case ENCRYPTED:
            this.verifyWss4jEncResults(inmsg);
            break;
        default:
            fail("Unsupported coverage type.");
        }
    }
}
 
Example 14
Source File: SignatureConfirmationTest.java    From steady with Apache License 2.0 4 votes vote down vote up
private void testSignatureConfirmationResponse(
    List<WSHandlerResult> sigSaved,
    List<WSHandlerResult> sigReceived
) throws Exception {
    Document doc = readDocument("wsse-request-clean.xml");

    WSS4JOutInterceptor ohandler = new WSS4JOutInterceptor();
    PhaseInterceptor<SoapMessage> handler = ohandler.createEndingInterceptor();

    SoapMessage msg = new SoapMessage(new MessageImpl());
    Exchange ex = new ExchangeImpl();
    ex.setInMessage(msg);
    
    SOAPMessage saajMsg = MessageFactory.newInstance().createMessage();
    SOAPPart part = saajMsg.getSOAPPart();
    part.setContent(new DOMSource(doc));
    saajMsg.saveChanges();

    msg.setContent(SOAPMessage.class, saajMsg);

    msg.put(WSHandlerConstants.ACTION, WSHandlerConstants.TIMESTAMP);
    msg.put(WSHandlerConstants.RECV_RESULTS, sigReceived);
    
    handler.handleMessage(msg);

    doc = part;
    
    assertValid("//wsse:Security", doc);
    // assertValid("//wsse:Security/wsse11:SignatureConfirmation", doc);

    byte[] docbytes = getMessageBytes(doc);
    // System.out.println(new String(docbytes));
    
    XMLStreamReader reader = StaxUtils.createXMLStreamReader(new ByteArrayInputStream(docbytes));

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

    dbf.setValidating(false);
    dbf.setIgnoringComments(false);
    dbf.setIgnoringElementContentWhitespace(true);
    dbf.setNamespaceAware(true);

    DocumentBuilder db = dbf.newDocumentBuilder();
    db.setEntityResolver(new NullResolver());
    doc = StaxUtils.read(db, reader, false);

    WSS4JInInterceptor inHandler = new WSS4JInInterceptor();

    SoapMessage inmsg = new SoapMessage(new MessageImpl());
    ex.setInMessage(inmsg);
    inmsg.setContent(SOAPMessage.class, saajMsg);

    inHandler.setProperty(WSHandlerConstants.ACTION, WSHandlerConstants.TIMESTAMP);
    inmsg.put(WSHandlerConstants.SEND_SIGV, sigSaved);

    inHandler.handleMessage(inmsg);
}
 
Example 15
Source File: WSS4JFaultCodeTest.java    From steady with Apache License 2.0 4 votes vote down vote up
/**
 * Test that an action mismatch gets mapped to a proper fault code 
 */
@Test
public void testActionMismatch() throws Exception {
    Document doc = readDocument("wsse-request-clean.xml");

    WSS4JOutInterceptor ohandler = new WSS4JOutInterceptor();
    PhaseInterceptor<SoapMessage> handler = ohandler.createEndingInterceptor();

    SoapMessage msg = new SoapMessage(new MessageImpl());
    Exchange ex = new ExchangeImpl();
    ex.setInMessage(msg);
    
    SOAPMessage saajMsg = MessageFactory.newInstance().createMessage();
    SOAPPart part = saajMsg.getSOAPPart();
    part.setContent(new DOMSource(doc));
    saajMsg.saveChanges();

    msg.setContent(SOAPMessage.class, saajMsg);

    msg.put(WSHandlerConstants.ACTION, WSHandlerConstants.TIMESTAMP);

    handler.handleMessage(msg);

    doc = part;
    
    assertValid("//wsse:Security", doc);

    byte[] docbytes = getMessageBytes(doc);
    XMLStreamReader reader = StaxUtils.createXMLStreamReader(new ByteArrayInputStream(docbytes));

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

    dbf.setValidating(false);
    dbf.setIgnoringComments(false);
    dbf.setIgnoringElementContentWhitespace(true);
    dbf.setNamespaceAware(true);

    DocumentBuilder db = dbf.newDocumentBuilder();
    db.setEntityResolver(new NullResolver());
    doc = StaxUtils.read(db, reader, false);

    WSS4JInInterceptor inHandler = new WSS4JInInterceptor();

    SoapMessage inmsg = new SoapMessage(new MessageImpl());
    ex.setInMessage(inmsg);
    inmsg.setContent(SOAPMessage.class, saajMsg);

    inHandler.setProperty(WSHandlerConstants.ACTION, 
        WSHandlerConstants.TIMESTAMP + " " + WSHandlerConstants.USERNAME_TOKEN);
    inHandler.setProperty(WSHandlerConstants.PW_CALLBACK_CLASS, TestPwdCallback.class.getName());

    try {
        inHandler.handleMessage(inmsg);
        fail("Expected failure on an action mismatch");
    } catch (SoapFault fault) {
        assertTrue(fault.getReason().startsWith(
            "An error was discovered processing the <wsse:Security> header"));
        QName faultCode = new QName(WSConstants.WSSE_NS, "InvalidSecurity");
        assertTrue(fault.getFaultCode().equals(faultCode));
    }
}
 
Example 16
Source File: PolicyBasedWSS4JOutInterceptor.java    From cxf with Apache License 2.0 4 votes vote down vote up
private void translateProperties(SoapMessage msg) {
    String bspCompliant = (String)msg.getContextualProperty(SecurityConstants.IS_BSP_COMPLIANT);
    if (bspCompliant != null) {
        msg.put(ConfigurationConstants.IS_BSP_COMPLIANT, bspCompliant);
    }
}
 
Example 17
Source File: UsernameTokenInterceptor.java    From steady with Apache License 2.0 4 votes vote down vote up
private void processUsernameToken(SoapMessage message) {
    Header h = findSecurityHeader(message, false);
    if (h == null) {
        return;
    }
    Element el = (Element)h.getObject();
    Element child = DOMUtils.getFirstElement(el);
    while (child != null) {
        if (SPConstants.USERNAME_TOKEN.equals(child.getLocalName())) {
            try  {
                final WSUsernameTokenPrincipal princ = getPrincipal(child, message);
                if (princ != null) {
                    List<WSSecurityEngineResult>v = new ArrayList<WSSecurityEngineResult>();
                    int action = WSConstants.UT;
                    if (princ.getPassword() == null) {
                        action = WSConstants.UT_NOPASSWORD;
                    }
                    v.add(0, new WSSecurityEngineResult(action, princ, null, null, null));
                    List<WSHandlerResult> results = CastUtils.cast((List<?>)message
                                                              .get(WSHandlerConstants.RECV_RESULTS));
                    if (results == null) {
                        results = new ArrayList<WSHandlerResult>();
                        message.put(WSHandlerConstants.RECV_RESULTS, results);
                    }
                    WSHandlerResult rResult = new WSHandlerResult(null, v);
                    results.add(0, rResult);

                    assertUsernameTokens(message, princ);
                    message.put(WSS4JInInterceptor.PRINCIPAL_RESULT, princ);                   
                    
                    SecurityContext sc = message.get(SecurityContext.class);
                    if (sc == null || sc.getUserPrincipal() == null) {
                        Subject subject = createSubject(princ.getName(), princ.getPassword(),
                            princ.isPasswordDigest(), princ.getNonce(), princ.getCreatedTime());
                        message.put(SecurityContext.class, 
                                    createSecurityContext(princ, subject));
                    }

                }
            } catch (WSSecurityException ex) {
                throw new Fault(ex);
            }
        }
        child = DOMUtils.getNextElement(child);
    }
}
 
Example 18
Source File: PolicyBasedWSS4JInInterceptor.java    From steady with Apache License 2.0 4 votes vote down vote up
private String checkAsymmetricBinding(
    AssertionInfoMap aim, String action, SoapMessage message
) throws WSSecurityException {
    Collection<AssertionInfo> ais = aim.get(SP12Constants.ASYMMETRIC_BINDING);
    if (ais == null || ais.isEmpty()) {
        return action;
    }
    
    action = addToAction(action, "Signature", true);
    action = addToAction(action, "Encrypt", true);
    Object s = message.getContextualProperty(SecurityConstants.SIGNATURE_CRYPTO);
    if (s == null) {
        s = message.getContextualProperty(SecurityConstants.SIGNATURE_PROPERTIES);
    }
    Object e = message.getContextualProperty(SecurityConstants.ENCRYPT_CRYPTO);
    if (e == null) {
        e = message.getContextualProperty(SecurityConstants.ENCRYPT_PROPERTIES);
    }
    
    Crypto encrCrypto = getEncryptionCrypto(e, message);
    Crypto signCrypto = null;
    if (e != null && e.equals(s)) {
        signCrypto = encrCrypto;
    } else {
        signCrypto = getSignatureCrypto(s, message);
    }
    
    if (signCrypto != null) {
        message.put(WSHandlerConstants.DEC_PROP_REF_ID, "RefId-" + signCrypto.hashCode());
        message.put("RefId-" + signCrypto.hashCode(), signCrypto);
    }
    
    if (encrCrypto != null) {
        message.put(WSHandlerConstants.SIG_PROP_REF_ID, "RefId-" + encrCrypto.hashCode());
        message.put("RefId-" + encrCrypto.hashCode(), (Crypto)encrCrypto);
    } else if (signCrypto != null) {
        message.put(WSHandlerConstants.SIG_PROP_REF_ID, "RefId-" + signCrypto.hashCode());
        message.put("RefId-" + signCrypto.hashCode(), (Crypto)signCrypto);
    }
 
    return action;
}
 
Example 19
Source File: BinarySecurityTokenInterceptor.java    From cxf with Apache License 2.0 4 votes vote down vote up
protected void processToken(SoapMessage message) {
    Header h = findSecurityHeader(message, false);
    if (h == null) {
        return;
    }
    Element el = (Element)h.getObject();
    Element child = DOMUtils.getFirstElement(el);
    while (child != null) {
        if (WSS4JConstants.BINARY_TOKEN_LN.equals(child.getLocalName())
            && WSS4JConstants.WSSE_NS.equals(child.getNamespaceURI())) {
            try {
                List<WSSecurityEngineResult> bstResults = processToken(child, message);
                if (bstResults != null) {
                    List<WSHandlerResult> results = CastUtils.cast((List<?>)message
                            .get(WSHandlerConstants.RECV_RESULTS));
                    if (results == null) {
                        results = new ArrayList<>();
                        message.put(WSHandlerConstants.RECV_RESULTS, results);
                    }
                    WSHandlerResult rResult =
                        new WSHandlerResult(null, bstResults,
                                            Collections.singletonMap(WSConstants.BST, bstResults));
                    results.add(0, rResult);

                    assertTokens(message);

                    Principal principal =
                        (Principal)bstResults.get(0).get(WSSecurityEngineResult.TAG_PRINCIPAL);

                    SecurityContext sc = message.get(SecurityContext.class);
                    if (sc == null || sc.getUserPrincipal() == null) {
                        message.put(SecurityContext.class, new DefaultSecurityContext(principal, null));
                    }

                }
            } catch (WSSecurityException ex) {
                throw WSS4JUtils.createSoapFault(message, message.getVersion(), ex);
            }
        }
        child = DOMUtils.getNextElement(child);
    }
}
 
Example 20
Source File: SignatureConfirmationTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testSignatureConfirmationRequest() throws Exception {
    Document doc = readDocument("wsse-request-clean.xml");

    WSS4JOutInterceptor ohandler = new WSS4JOutInterceptor();
    PhaseInterceptor<SoapMessage> handler = ohandler.createEndingInterceptor();

    SoapMessage msg = getSoapMessageForDom(doc);

    msg.put(ConfigurationConstants.ACTION, ConfigurationConstants.SIGNATURE);
    msg.put(ConfigurationConstants.ENABLE_SIGNATURE_CONFIRMATION, "true");
    msg.put(ConfigurationConstants.SIG_PROP_FILE, "outsecurity.properties");
    msg.put(ConfigurationConstants.USER, "myalias");
    msg.put("password", "myAliasPassword");
    //
    // This is necessary to convince the WSS4JOutInterceptor that we're
    // functioning as a requestor
    //
    msg.put(org.apache.cxf.message.Message.REQUESTOR_ROLE, true);

    handler.handleMessage(msg);

    SOAPMessage saajMsg = msg.getContent(SOAPMessage.class);
    doc = saajMsg.getSOAPPart();

    assertValid("//wsse:Security", doc);
    assertValid("//wsse:Security/ds:Signature", doc);

    //
    // Save the signature for future confirmation
    //
    Set<Integer> sigv = CastUtils.cast((Set<?>)msg.get(WSHandlerConstants.SEND_SIGV));
    assertNotNull(sigv);
    assertFalse(sigv.isEmpty());

    byte[] docbytes = getMessageBytes(doc);
    doc = StaxUtils.read(new ByteArrayInputStream(docbytes));

    WSS4JInInterceptor inHandler = new WSS4JInInterceptor();

    SoapMessage inmsg = new SoapMessage(new MessageImpl());
    Exchange ex = new ExchangeImpl();
    ex.setInMessage(inmsg);
    inmsg.setContent(SOAPMessage.class, saajMsg);

    inHandler.setProperty(ConfigurationConstants.ACTION, ConfigurationConstants.SIGNATURE);
    inHandler.setProperty(ConfigurationConstants.SIG_VER_PROP_FILE, "insecurity.properties");
    inHandler.setProperty(ConfigurationConstants.ENABLE_SIGNATURE_CONFIRMATION, "true");

    inHandler.handleMessage(inmsg);

    //
    // Check that the inbound signature result was saved
    //
    List<WSHandlerResult> sigReceived =
        CastUtils.cast((List<?>)inmsg.get(WSHandlerConstants.RECV_RESULTS));
    assertNotNull(sigReceived);
    assertFalse(sigReceived.isEmpty());

    testSignatureConfirmationResponse(sigv, sigReceived);
}