Example usage for javax.xml.ws.handler.soap SOAPMessageContext get

List of usage examples for javax.xml.ws.handler.soap SOAPMessageContext get

Introduction

In this page you can find the example usage for javax.xml.ws.handler.soap SOAPMessageContext get.

Prototype

V get(Object key);

Source Link

Document

Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.

Usage

From source file:be.fedict.eid.idp.protocol.saml2.artifact.ArtifactServiceServerHandler.java

private void handleOutboundDocument(SOAPPart soapPart, SOAPMessageContext soapMessageContext) {

    LOG.debug("handle outbound");

    // find optional IdP Identity for signing
    ServletContext servletContext = (ServletContext) soapMessageContext.get(MessageContext.SERVLET_CONTEXT);
    IdentityProviderConfiguration configuration = AbstractSAML2ProtocolService
            .getIdPConfiguration(servletContext);
    IdPIdentity idpIdentity = configuration.findIdentity();

    if (null != idpIdentity) {

        try {/*from w  ww  .  ja  va  2s . c  o m*/
            LOG.debug("IdP Identity found, singing...");

            // find assertion and sing
            if (null != Saml2Util.find(soapPart, XPATH_RESPONSE_ASSERTION)) {
                sign(soapPart, XPATH_RESPONSE_ASSERTION, XPATH_RESPONSE_ASSERTION_ISSUER, idpIdentity);
            }

            // find Response and sign
            if (null != Saml2Util.find(soapPart, XPATH_RESPONSE)) {
                sign(soapPart, XPATH_RESPONSE, XPATH_RESPONSE_STATUS, idpIdentity);

            }

            // find ArtifactResponse and sign
            sign(soapPart, XPATH_ARTIFACT_RESPONSE, XPATH_STATUS, idpIdentity);

        } catch (NoSuchAlgorithmException e) {
            throw createSOAPFaultException("Signing failed: " + "NoSuchAlgorithmException: " + e.getMessage());
        } catch (InvalidAlgorithmParameterException e) {
            throw createSOAPFaultException(
                    "Signing failed: " + "InvalidAlgorithmParameterException: " + e.getMessage());
        } catch (MarshalException e) {
            throw createSOAPFaultException("Signing failed: " + "MarshalException: " + e.getMessage());
        } catch (XMLSignatureException e) {
            throw createSOAPFaultException("Signing failed: " + "XMLSignatureException: " + e.getMessage());
        }

    }
}

From source file:be.fedict.trust.xkms2.WSSecurityServerHandler.java

/**
 * Handles the outbound SOAP message. Adds the WS Security Header containing
 * a signed timestamp, and signed SOAP body.
 *///  w  w  w.j a va 2 s  . c  o m
private void handleOutboundDocument(SOAPPart soapPart, SOAPMessageContext soapMessageContext) {

    LOG.debug("handle outbound document");
    ServletContext servletContext = (ServletContext) soapMessageContext.get(MessageContext.SERVLET_CONTEXT);
    TrustService trustService = ServiceConsumerServletContextListener.getTrustService(servletContext);
    WSSecurityConfigEntity wsSecurityConfig = trustService.getWsSecurityConfig();

    if (wsSecurityConfig.isSigning()) {
        LOG.debug("adding WS-Security SOAP header");

        try {
            PrivateKeyEntry privateKeyEntry = KeyStoreUtils.loadPrivateKeyEntry(wsSecurityConfig);
            X509Certificate certificate = (X509Certificate) privateKeyEntry.getCertificate();
            PrivateKey privateKey = privateKeyEntry.getPrivateKey();

            WSSecHeader wsSecHeader = new WSSecHeader();
            wsSecHeader.insertSecurityHeader(soapPart);

            WSSecTimestamp wsSecTimeStamp = new WSSecTimestamp();
            wsSecTimeStamp.setTimeToLive(0);
            wsSecTimeStamp.build(soapPart, wsSecHeader);

            ClientCrypto crypto = new ClientCrypto(certificate, privateKey);
            WSSConfig wssConfig = new WSSConfig();
            wssConfig.setWsiBSPCompliant(false);
            WSSecSignature sign = new WSSecSignature(wssConfig);
            sign.setKeyIdentifierType(WSConstants.BST_DIRECT_REFERENCE);
            sign.prepare(soapPart, crypto, wsSecHeader);
            sign.appendBSTElementToHeader(wsSecHeader);
            Vector<WSEncryptionPart> signParts = new Vector<WSEncryptionPart>();
            signParts.add(new WSEncryptionPart(wsSecTimeStamp.getId()));
            SOAPConstants soapConstants = WSSecurityUtil.getSOAPConstants(soapPart.getDocumentElement());
            signParts.add(new WSEncryptionPart(soapConstants.getBodyQName().getLocalPart(),
                    soapConstants.getEnvelopeURI(), "Content"));
            sign.addReferencesToSign(signParts, wsSecHeader);
            List<Reference> referenceList = sign.addReferencesToSign(signParts, wsSecHeader);
            sign.computeSignature(referenceList, false, null);

        } catch (WSSecurityException e) {
            trustService.logAudit("WS-Security error: " + e.getMessage());
            throw new RuntimeException("WSS4J error: " + e.getMessage(), e);
        } catch (KeyStoreLoadException e) {
            trustService.logAudit("Load keystore error: " + e.getMessage());
            throw new RuntimeException("Failed to laod keystore: " + e.getMessage(), e);
        }
    }
}

From source file:be.e_contract.mycarenet.xkms.ProofOfPossessionSignatureSOAPHandler.java

@Override
public boolean handleMessage(SOAPMessageContext context) {
    if (null == this.sessionKey) {
        return true;
    }/*from  w  w w.j  av  a  2 s.  c om*/
    if (null == this.prototypeKeyBindingId) {
        return true;
    }

    Boolean outboundProperty = (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
    if (false == outboundProperty) {
        return true;
    }
    LOG.debug("adding proof of possession signature");
    SOAPMessage soapMessage = context.getMessage();
    SOAPPart soapPart = soapMessage.getSOAPPart();

    NodeList registerRequestNodeList = soapPart.getElementsByTagNameNS(XKMS_NAMESPACE, "Register");
    Element registerRequestElement = (Element) registerRequestNodeList.item(0);
    Document xkmsDocument;
    try {
        xkmsDocument = copyDocument(registerRequestElement);
    } catch (ParserConfigurationException e) {
        LOG.error("error copying XKMS request: " + e.getMessage(), e);
        return false;
    }

    NodeList proofOfPossessionNodeList = xkmsDocument.getElementsByTagNameNS(XKMS_NAMESPACE,
            "ProofOfPossession");
    Element proofOfPossessionElement = (Element) proofOfPossessionNodeList.item(0);
    try {
        prepareDocument(xkmsDocument);
        addSignature(proofOfPossessionElement);
    } catch (Exception e) {
        LOG.error("error adding proof signature: " + e.getMessage(), e);
        return false;
    }
    Node signatureNode = soapPart.importNode(proofOfPossessionElement.getFirstChild(), true);

    proofOfPossessionNodeList = soapPart.getElementsByTagNameNS(XKMS_NAMESPACE, "ProofOfPossession");
    proofOfPossessionElement = (Element) proofOfPossessionNodeList.item(0);
    proofOfPossessionElement.appendChild(signatureNode);
    return true;
}

From source file:be.e_contract.mycarenet.xkms2.ProofOfPossessionSignatureSOAPHandler.java

@Override
public boolean handleMessage(SOAPMessageContext context) {
    if (null == this.sessionKey) {
        return true;
    }/*  w w  w .  j a  v  a  2s  .  c om*/
    if (null == this.prototypeKeyBindingId) {
        return true;
    }

    Boolean outboundProperty = (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
    if (false == outboundProperty) {
        return true;
    }
    LOG.debug("adding proof of possession signature");
    SOAPMessage soapMessage = context.getMessage();
    SOAPPart soapPart = soapMessage.getSOAPPart();

    NodeList registerRequestNodeList = soapPart.getElementsByTagNameNS(XKMS2ServiceFactory.XKMS2_NAMESPACE,
            "RegisterRequest");
    Element registerRequestElement = (Element) registerRequestNodeList.item(0);
    Document xkmsDocument;
    try {
        xkmsDocument = copyDocument(registerRequestElement);
    } catch (ParserConfigurationException e) {
        LOG.error("error copying XKMS request: " + e.getMessage(), e);
        return false;
    }

    NodeList proofOfPossessionNodeList = xkmsDocument
            .getElementsByTagNameNS(XKMS2ServiceFactory.XKMS2_NAMESPACE, "ProofOfPossession");
    Element proofOfPossessionElement = (Element) proofOfPossessionNodeList.item(0);
    try {
        prepareDocument(xkmsDocument);
        addSignature(proofOfPossessionElement);
    } catch (Exception e) {
        LOG.error("error adding proof signature: " + e.getMessage(), e);
        return false;
    }
    Node signatureNode = soapPart.importNode(proofOfPossessionElement.getFirstChild(), true);

    proofOfPossessionNodeList = soapPart.getElementsByTagNameNS(XKMS2ServiceFactory.XKMS2_NAMESPACE,
            "ProofOfPossession");
    proofOfPossessionElement = (Element) proofOfPossessionNodeList.item(0);
    proofOfPossessionElement.appendChild(signatureNode);
    return true;
}

From source file:edu.duke.cabig.c3pr.web.security.SecureWebServiceHandler.java

public void handleMessage(SoapMessage message) throws Fault {
    SOAPMessageContext ctx = new SOAPMessageContextImpl(message);
    try {//from  w  w w.  ja va  2  s .c o  m
        ServletContext servletContext = (ServletContext) ctx.get(MessageContext.SERVLET_CONTEXT);
        HttpServletRequest request = (HttpServletRequest) ctx.get(MessageContext.SERVLET_REQUEST);

        SAMLAssertion samlAssertion = extractSAMLAssertion(message);
        verifyAssertion(samlAssertion);

        authenticateSubject(servletContext, samlAssertion);

        if (SecurityContextHolder.getContext().getAuthentication() == null) {
            throw new RuntimeException(
                    "Unable to authenticate service caller: perhaps, invalid SAML assertion?");
        }
        AuditInfoFilter.setAuditInfo(request);
    } catch (Exception e) {
        log.error(e, e);
        generateSecurityFault(e);
    }
}

From source file:org.apache.juddi.xlt.util.LoggingHandler.java

private String getOperationName(SOAPMessageContext context) {
    // service is optional :-(
    QName service = (QName) context.get(MessageContext.WSDL_SERVICE);
    if (service == null) {
        service = new QName("<unknown>");
    }// www.jav a2  s . co  m

    // operation is optional :-(
    QName operation = (QName) context.get(MessageContext.WSDL_OPERATION);
    if (operation == null) {
        // operation = new QName("<unknown>");

        try {
            operation = new QName(context.getMessage().getSOAPBody().getFirstChild().getLocalName());
        } catch (SOAPException ex) {
            throw new RuntimeException("", ex);
        }
    }

    return service.getLocalPart() + "." + operation.getLocalPart();
}

From source file:org.apache.juddi.xlt.util.LoggingHandler.java

private void logMessage(SOAPMessageContext context) {
    boolean isOutbound = isOutboundMessage(context);

    // optionally append the HTTP request/response headers
    String headersKey = isOutbound ? MessageContext.HTTP_REQUEST_HEADERS : MessageContext.HTTP_RESPONSE_HEADERS;
    StringBuilder httpHeaders = new StringBuilder();
    Map<Object, Object> headers = (Map<Object, Object>) context.get(headersKey);
    if (headers != null && headers.size() > 0) {
        for (Entry<Object, Object> entry : headers.entrySet()) {
            httpHeaders.append("- " + entry.getKey() + " = " + entry.getValue() + "\n");
        }//from  ww w  .jav a  2  s.c o m
    }

    // append the SOAP message
    String soapMessage = DomUtils.prettyPrintNode(context.getMessage().getSOAPPart());

    // append the message context properties
    StringBuilder messageContextProperties = new StringBuilder();
    TreeMap<String, Object> sortedContextProperties = new TreeMap<String, Object>(context);
    for (Entry<String, Object> entry : sortedContextProperties.entrySet()) {
        messageContextProperties.append("- " + entry.getKey() + " = " + entry.getValue() + "\n");
    }

    // finally log all
    String format = isOutbound ? OUTBOUND_MESSAGE_FORMAT : INBOUND_MESSAGE_FORMAT;
    LOG.debug(String.format(format, httpHeaders, soapMessage, messageContextProperties));
}

From source file:org.nuxeo.ecm.core.opencmis.bindings.NuxeoCmisAuthHandler.java

@Override
public boolean handleMessage(SOAPMessageContext context) {
    boolean res = super.handleMessage(context);

    HttpServletRequest request = (HttpServletRequest) context.get(MessageContext.SERVLET_REQUEST);
    request.setAttribute(CmisWebServicesServlet.CMIS_VERSION, CmisVersion.CMIS_1_1);

    @SuppressWarnings("unchecked")
    Map<String, String> callContextMap = (Map<String, String>) context.get(AbstractService.CALL_CONTEXT_MAP);
    if (callContextMap != null) {
        // login to Nuxeo
        String username = callContextMap.get(CallContext.USERNAME);
        String password = callContextMap.get(CallContext.PASSWORD);
        try {//from   www.j ava2 s.c  o  m
            LoginContext loginContext = getLoginProvider().login(username, password);
            // store in message context, for later logout
            context.put(NUXEO_LOGIN_CONTEXT, loginContext);
            context.setScope(NUXEO_LOGIN_CONTEXT, Scope.APPLICATION);
        } catch (LoginException e) {
            throw new RuntimeException("Login failed for user '" + username + "'", e);
        }
    }
    return res;
}

From source file:org.springframework.integration.sqs.AWSSecurityHandler.java

private void logMessage(final SOAPMessageContext smc) {
    Boolean outboundProperty = (Boolean) smc.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);

    SOAPMessage message = smc.getMessage();
    if (outboundProperty.booleanValue()) {
        logMessage("Outbound message: ", message);
    } else {/*from   ww  w .  j a  v a 2  s.  c o  m*/
        logMessage("Inbound message: ", message);
    }
}

From source file:org.springframework.integration.sqs.AWSSecurityHandler.java

/**
 * {@inheritDoc}//  w  w  w.  ja v  a2s  .  c  om
 */
public boolean handleMessage(final SOAPMessageContext context) {
    logMessage(context);
    Boolean outboundProperty = (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
    if (!outboundProperty) {
        return true;
    }

    /*
     * Example SOAP header from
     * http://docs.amazonwebservices.com/AWSSimpleQueueService
     * /2008-01-01/SQSDeveloperGuide
     * /MakingRequests_MakingSOAPRequestsArticle.html
     * 
     * <soapenv:Header
     * xmlns:aws="http://security.amazonaws.com/doc/2007-01-01/">
     * <aws:AWSAccessKeyId>1D9FVRAYCP1VJS767E02EXAMPLE</aws:AWSAccessKeyId>
     * <aws:Timestamp>2008-02-10T23:59:59Z</aws:Timestamp>
     * <aws:Signature>SZf1CHmQ/nrZbsrC13hCZS061ywsEXAMPLE</aws:Signature>
     * </soapenv:Header>
     */

    SOAPMessage aSOAPMessage = context.getMessage();
    try {
        SOAPEnvelope aEnvelope = aSOAPMessage.getSOAPPart().getEnvelope();
        SOAPHeader aHeader = aEnvelope.addHeader();
        String aTimestampStr = this.getTimestamp();
        // ADD AWS SECURITY HEADER ----------------------------------------
        aHeader.addNamespaceDeclaration(NAMESPACE_AWS_PREFIX, NAMESPACE_AWS);

        // ADD ACCESS KEY -------------------------------------------------
        Name aKeyName = aEnvelope.createName("AWSAccessKeyId", NAMESPACE_AWS_PREFIX, NAMESPACE_AWS);
        SOAPHeaderElement aKey = aHeader.addHeaderElement(aKeyName);
        aKey.addTextNode(s_key);

        // ADD TIMESTAMP --------------------------------------------------
        Name aTimestampName = aEnvelope.createName("Timestamp", NAMESPACE_AWS_PREFIX, NAMESPACE_AWS);
        SOAPHeaderElement aTimestamp = aHeader.addHeaderElement(aTimestampName);
        aTimestamp.addTextNode(aTimestampStr);

        // ADD SIGNATURE --------------------------------------------------
        Name aSignatureName = aEnvelope.createName("Signature", NAMESPACE_AWS_PREFIX, NAMESPACE_AWS);
        SOAPHeaderElement aSignature = aHeader.addHeaderElement(aSignatureName);

        SOAPBody aBody = aEnvelope.getBody();
        Iterator<?> aChildren = aBody.getChildElements();
        SOAPBodyElement aAction = (SOAPBodyElement) aChildren.next();
        if (aChildren.hasNext()) {
            throw new IllegalStateException(
                    "Unexpected number of actions in soap request. Cannot calculate signature.");
        }
        aSignature.addTextNode(this.calculateSignature(aAction.getLocalName(), aTimestampStr));
        aSOAPMessage.saveChanges();
        logMessage("Final out message: ", aSOAPMessage);
    } catch (Exception e) {
        throw new IllegalStateException("Failed to add aws headers!", e);
    }
    return true;
}