List of usage examples for javax.xml.ws.handler.soap SOAPMessageContext getMessage
public SOAPMessage getMessage();
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 . jav a2 s . com logMessage("Inbound message: ", message); } }
From source file:org.springframework.integration.sqs.AWSSecurityHandler.java
/** * {@inheritDoc}/*from www.ja v a2 s . c o m*/ */ 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; }
From source file:org.wso2.carbon.device.mgt.mobile.windows.api.services.enrollment.util.MessageHandler.java
/** * This method adds Timestamp for SOAP header, and adds Content-length for HTTP header for * avoiding HTTP chunking.//from w w w .j av a 2 s .co m * * @param context - Context of the SOAP Message */ @Override public boolean handleMessage(SOAPMessageContext context) { Boolean outBoundProperty = (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY); if (outBoundProperty) { SOAPMessage message = context.getMessage(); SOAPHeader header = null; SOAPEnvelope envelope = null; try { header = message.getSOAPHeader(); envelope = message.getSOAPPart().getEnvelope(); } catch (SOAPException e) { Response.serverError().entity("SOAP message content cannot be read.").build(); } try { if ((header == null) && (envelope != null)) { header = envelope.addHeader(); } } catch (SOAPException e) { Response.serverError().entity("SOAP header cannot be added.").build(); } SOAPFactory soapFactory = null; try { soapFactory = SOAPFactory.newInstance(); } catch (SOAPException e) { Response.serverError().entity("Cannot get an instance of SOAP factory.").build(); } QName qNamesSecurity = new QName(PluginConstants.WS_SECURITY_TARGET_NAMESPACE, PluginConstants.CertificateEnrolment.SECURITY); SOAPHeaderElement Security = null; Name attributeName = null; try { if (header != null) { Security = header.addHeaderElement(qNamesSecurity); } if (soapFactory != null) { attributeName = soapFactory.createName(PluginConstants.CertificateEnrolment.TIMESTAMP_ID, PluginConstants.CertificateEnrolment.TIMESTAMP_U, PluginConstants.CertificateEnrolment.WSS_SECURITY_UTILITY); } } catch (SOAPException e) { Response.serverError().entity("Security header cannot be added.").build(); } QName qNameTimestamp = new QName(PluginConstants.CertificateEnrolment.WSS_SECURITY_UTILITY, PluginConstants.CertificateEnrolment.TIMESTAMP); SOAPHeaderElement timestamp = null; try { if (header != null) { timestamp = header.addHeaderElement(qNameTimestamp); timestamp.addAttribute(attributeName, PluginConstants.CertificateEnrolment.TIMESTAMP_0); } } catch (SOAPException e) { Response.serverError().entity("Exception while adding timestamp header.").build(); } DateTime dateTime = new DateTime(); DateTime expiredDateTime = dateTime.plusMinutes(VALIDITY_TIME); String createdISOTime = dateTime.toString(ISODateTimeFormat.dateTime()); String expiredISOTime = expiredDateTime.toString(ISODateTimeFormat.dateTime()); createdISOTime = createdISOTime.substring(TIMESTAMP_BEGIN_INDEX, createdISOTime.length() - TIMESTAMP_END_INDEX); createdISOTime = createdISOTime + TIME_ZONE; expiredISOTime = expiredISOTime.substring(TIMESTAMP_BEGIN_INDEX, expiredISOTime.length() - TIMESTAMP_END_INDEX); expiredISOTime = expiredISOTime + TIME_ZONE; QName qNameCreated = new QName(PluginConstants.CertificateEnrolment.WSS_SECURITY_UTILITY, PluginConstants.CertificateEnrolment.CREATED); SOAPHeaderElement SOAPHeaderCreated = null; try { if (header != null) { SOAPHeaderCreated = header.addHeaderElement(qNameCreated); SOAPHeaderCreated.addTextNode(createdISOTime); } } catch (SOAPException e) { Response.serverError().entity("Exception while creating SOAP header.").build(); } QName qNameExpires = new QName(PluginConstants.CertificateEnrolment.WSS_SECURITY_UTILITY, PluginConstants.CertificateEnrolment.EXPIRES); SOAPHeaderElement SOAPHeaderExpires = null; ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); String messageString = null; try { if (header != null) { SOAPHeaderExpires = header.addHeaderElement(qNameExpires); SOAPHeaderExpires.addTextNode(expiredISOTime); } if ((timestamp != null) && (Security != null)) { timestamp.addChildElement(SOAPHeaderCreated); timestamp.addChildElement(SOAPHeaderExpires); Security.addChildElement(timestamp); } message.saveChanges(); message.writeTo(outputStream); messageString = new String(outputStream.toByteArray(), PluginConstants.CertificateEnrolment.UTF_8); } catch (SOAPException e) { Response.serverError().entity("Exception while creating timestamp SOAP header.").build(); } catch (IOException e) { Response.serverError().entity("Exception while writing message to output stream.").build(); } Map<String, List<String>> headers = (Map<String, List<String>>) context .get(MessageContext.HTTP_REQUEST_HEADERS); headers = new HashMap<String, List<String>>(); if (messageString != null) { headers.put(PluginConstants.CONTENT_LENGTH, Arrays.asList(String.valueOf(messageString.length()))); } context.put(MessageContext.HTTP_REQUEST_HEADERS, headers); } return true; }
From source file:org.wso2.carbon.mdm.mobileservices.windowspc.services.wstep.util.MessageHandler.java
/** * This method adds Timestamp for SOAP header, and adds Content-length for HTTP header for * avoiding HTTP chunking./*from ww w.ja v a 2s . com*/ * * @param context */ @Override public boolean handleMessage(SOAPMessageContext context) { Boolean outBoundProperty = (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY); if (outBoundProperty) { SOAPMessage message = context.getMessage(); SOAPHeader header = null; SOAPEnvelope envelope = null; try { header = message.getSOAPHeader(); envelope = message.getSOAPPart().getEnvelope(); } catch (SOAPException e) { Response.serverError().build(); } if (header == null) { try { header = envelope.addHeader(); } catch (SOAPException e) { Response.serverError().build(); } } SOAPFactory soapFactory = null; try { soapFactory = SOAPFactory.newInstance(); } catch (SOAPException e) { Response.serverError().build(); } QName qNamesSecurity = new QName(Constants.CertificateEnrollment.WS_SECURITY_TARGET_NAMESPACE, Constants.CertificateEnrollment.SECURITY); SOAPHeaderElement Security = null; try { Security = header.addHeaderElement(qNamesSecurity); } catch (SOAPException e) { Response.serverError().build(); } Name attributeName = null; try { attributeName = soapFactory.createName(Constants.CertificateEnrollment.TIMESTAMP_ID, Constants.CertificateEnrollment.TIMESTAMP_U, Constants.CertificateEnrollment.WSS_SECURITY_UTILITY); } catch (SOAPException e) { Response.serverError().build(); } QName qNameTimestamp = new QName(Constants.CertificateEnrollment.WSS_SECURITY_UTILITY, Constants.CertificateEnrollment.TIMESTAMP); SOAPHeaderElement timestamp = null; try { timestamp = header.addHeaderElement(qNameTimestamp); timestamp.addAttribute(attributeName, Constants.CertificateEnrollment.TIMESTAMP_0); } catch (SOAPException e) { Response.serverError().build(); } DateTime dateTime = new DateTime(); DateTime expiredDateTime = dateTime.plusMinutes(5); String createdISOTime = dateTime.toString(ISODateTimeFormat.dateTime()); String expiredISOTime = expiredDateTime.toString(ISODateTimeFormat.dateTime()); createdISOTime = createdISOTime.substring(0, createdISOTime.length() - 6); createdISOTime = createdISOTime + "Z"; expiredISOTime = expiredISOTime.substring(0, expiredISOTime.length() - 6); expiredISOTime = expiredISOTime + "Z"; QName qNameCreated = new QName(Constants.CertificateEnrollment.WSS_SECURITY_UTILITY, Constants.CertificateEnrollment.CREATED); SOAPHeaderElement SOAPHeaderCreated = null; try { SOAPHeaderCreated = header.addHeaderElement(qNameCreated); SOAPHeaderCreated.addTextNode(createdISOTime); } catch (SOAPException e) { Response.serverError().build(); } QName qNameExpires = new QName(Constants.CertificateEnrollment.WSS_SECURITY_UTILITY, Constants.CertificateEnrollment.EXPIRES); SOAPHeaderElement SOAPHeaderExpires = null; try { SOAPHeaderExpires = header.addHeaderElement(qNameExpires); SOAPHeaderExpires.addTextNode(expiredISOTime); } catch (SOAPException e) { Response.serverError().build(); } try { timestamp.addChildElement(SOAPHeaderCreated); timestamp.addChildElement(SOAPHeaderExpires); Security.addChildElement(timestamp); } catch (SOAPException e) { Response.serverError().build(); } try { message.saveChanges(); } catch (SOAPException e) { Response.serverError().build(); } ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); try { message.writeTo(outputStream); } catch (IOException e) { Response.serverError().build(); } catch (SOAPException e) { Response.serverError().build(); } String messageString = null; try { messageString = new String(outputStream.toByteArray(), Constants.CertificateEnrollment.UTF_8); } catch (UnsupportedEncodingException e) { Response.serverError().build(); } Map<String, List<String>> headers = (Map<String, List<String>>) context .get(MessageContext.HTTP_REQUEST_HEADERS); headers = new HashMap<String, List<String>>(); headers.put(Constants.CertificateEnrollment.CONTENT_LENGTH, Arrays.asList(String.valueOf(messageString.length()))); context.put(MessageContext.HTTP_REQUEST_HEADERS, headers); } return true; }
From source file:test.integ.be.agiv.security.Axis2Test.java
@Test public void testWSSecurityHandler() throws Exception { // setup// www. j a va 2s . c o m WSSecurityHandler testedInstance = new WSSecurityHandler(); SOAPMessageContext mockContext = EasyMock.createMock(SOAPMessageContext.class); EasyMock.expect(mockContext.get("javax.xml.ws.handler.message.outbound")).andStubReturn(Boolean.TRUE); EasyMock.expect(mockContext.get("be.agiv.security.handler.WSSecurityHandler.token")).andStubReturn(null); String testUsername = "username-" + UUID.randomUUID().toString(); EasyMock.expect(mockContext.get("be.agiv.security.handler.WSSecurityHandler.username")) .andStubReturn(testUsername); EasyMock.expect(mockContext.get("be.agiv.security.handler.WSSecurityHandler.password")) .andStubReturn("password"); EasyMock.expect(mockContext.get("be.agiv.security.handler.WSSecurityHandler.key")).andStubReturn(null); EasyMock.expect(mockContext.get("be.agiv.security.handler.WSSecurityHandler.certificate")) .andStubReturn(null); SOAPMessage soapMessage = MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL).createMessage(null, new ByteArrayInputStream( "<Envelope xmlns=\"http://schemas.xmlsoap.org/soap/envelope/\"><Body>test</Body></Envelope>" .getBytes())); LOG.debug("SOAP message: " + toString(soapMessage.getSOAPPart())); EasyMock.expect(mockContext.getMessage()).andStubReturn(soapMessage); // prepare EasyMock.replay(mockContext); // operate testedInstance.handleMessage(mockContext); // verify EasyMock.verify(mockContext); LOG.debug("SOAP message after handleMessage: " + toString(soapMessage.getSOAPPart())); }
From source file:test.integ.be.fedict.hsm.ws.WSS4JTestSOAPHandler.java
private void handleOutboundMessage(SOAPMessageContext context) throws WSSecurityException, ConfigurationException, MarshallingException { SOAPMessage soapMessage = context.getMessage(); SOAPPart soapPart = soapMessage.getSOAPPart(); WSSecHeader wsSecHeader = new WSSecHeader(); wsSecHeader.insertSecurityHeader(soapPart); WSSecTimestamp wsSecTimeStamp = new WSSecTimestamp(); wsSecTimeStamp.setTimeToLive(60);/*from w w w . ja va2 s. c om*/ wsSecTimeStamp.build(soapPart, wsSecHeader); WSSecSAMLToken wsSecSAMLToken = new WSSecSAMLToken(); Assertion assertion = buildObject(Assertion.DEFAULT_ELEMENT_NAME, Assertion.class); assertion.setID("assertion-" + UUID.randomUUID().toString()); Marshaller marshaller = Configuration.getMarshallerFactory().getMarshaller(assertion); marshaller.marshall(assertion); AssertionWrapper assertionWrapper = new AssertionWrapper(assertion); wsSecSAMLToken.build(soapPart, assertionWrapper, wsSecHeader); }
From source file:test.integ.be.fedict.hsm.ws.WSSecurityTestSOAPHandler.java
private void handleOutboundMessage(SOAPMessageContext context) throws SOAPException, DatatypeConfigurationException, CertificateEncodingException, DOMException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, MarshalException, XMLSignatureException, NoSuchProviderException { SOAPMessage soapMessage = context.getMessage(); SOAPPart soapPart = soapMessage.getSOAPPart(); Element soapEnvelopeElement = soapPart.getDocumentElement(); String soapPrefix = soapEnvelopeElement.getPrefix(); LOG.debug("SOAP prefix: " + soapPrefix); Element soapHeaderElement = soapPart.createElementNS(SOAP_NAMESPACE, soapPrefix + ":Header"); Element soapBodyElement = (Element) soapEnvelopeElement.getFirstChild(); soapBodyElement.setAttributeNS(XMLNS_NS, "xmlns:wsu", WSU_NAMESPACE); soapBodyElement.setAttributeNS(WSU_NAMESPACE, "wsu:Id", "Body"); soapEnvelopeElement.insertBefore(soapHeaderElement, soapBodyElement); LOG.debug("adding WS-Security SOAP header"); Element wsSecurityHeaderElement = soapPart.createElementNS(WSSE_NAMESPACE, "wsse:Security"); soapHeaderElement.appendChild(wsSecurityHeaderElement); wsSecurityHeaderElement.setAttributeNS(XMLNS_NS, "xmlns:wsse", WSSE_NAMESPACE); wsSecurityHeaderElement.setAttributeNS(XMLNS_NS, "xmlns:wsu", WSU_NAMESPACE); wsSecurityHeaderElement.setAttributeNS(SOAP_NAMESPACE, soapPrefix + ":mustUnderstand", "true"); Element tsElement = addTimestamp(wsSecurityHeaderElement); addBinarySecurityToken(wsSecurityHeaderElement); addSignature(wsSecurityHeaderElement, tsElement, soapBodyElement); }
From source file:test.integ.be.fedict.trust.WSSecurityTest.java
@Test public void testWSSecurity() throws Exception { // Setup// w w w . j a va 2 s. c o m KeyPair keyPair = TestUtils.generateKeyPair(); X509Certificate certificate = TestUtils.generateSelfSignedCertificate(keyPair, "CN=Test"); KeyPair fooKeyPair = TestUtils.generateKeyPair(); X509Certificate fooCertificate = TestUtils.generateSelfSignedCertificate(fooKeyPair, "CN=F00"); this.wsSecurityClientHandler.setServerCertificate(certificate); KeyStoreType keyStoreType = KeyStoreType.PKCS12; String keyStorePassword = "secret"; String keyEntryPassword = "secret"; String alias = "alias"; File tmpP12File = File.createTempFile("keystore-", ".p12"); tmpP12File.deleteOnExit(); TestUtils.persistInKeyStore(tmpP12File, "pkcs12", keyPair.getPrivate(), certificate, keyStorePassword, keyEntryPassword, alias); String keyStorePath = tmpP12File.getAbsolutePath(); MessageFactory messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL); InputStream testSoapMessageInputStream = WSSecurityTest.class.getResourceAsStream("/test-soap-message.xml"); assertNotNull(testSoapMessageInputStream); SOAPMessage message = messageFactory.createMessage(null, testSoapMessageInputStream); SOAPMessageContext soapMessageContext = new TestSOAPMessageContext(message, true); soapMessageContext.put(MessageContext.SERVLET_CONTEXT, this.mockServletContext); // Expectations expect(this.mockServletContext.getAttribute(TrustService.class.getName())).andReturn(mockTrustService); expect(this.mockTrustService.getWsSecurityConfig()).andReturn(new WSSecurityConfigEntity("test", true, keyStoreType, keyStorePath, keyStorePassword, keyEntryPassword, alias)); // Replay replay(this.mockObjects); // Operate : Let WSSecurityServerHandler sign the SOAP message assertTrue(this.wsSecurityServerHandler.handleMessage(soapMessageContext)); // Verify message is signed verify(this.mockObjects); SOAPMessage resultMessage = soapMessageContext.getMessage(); SOAPPart resultSoapPart = resultMessage.getSOAPPart(); LOG.debug("signed SOAP part:" + TestUtils.domToString(resultSoapPart)); Element nsElement = resultSoapPart.createElement("nsElement"); nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:soap", "http://schemas.xmlsoap.org/soap/envelope/"); nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:wsse", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"); nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:ds", "http://www.w3.org/2000/09/xmldsig#"); nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:wsu", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"); Node resultNode = XPathAPI.selectSingleNode(resultSoapPart, "/soap:Envelope/soap:Header/wsse:Security[@soap:mustUnderstand = '1']", nsElement); assertNotNull(resultNode); assertNotNull("missing WS-Security timestamp", XPathAPI.selectSingleNode(resultSoapPart, "/soap:Envelope/soap:Header/wsse:Security/wsu:Timestamp/wsu:Created", nsElement)); assertEquals(2.0, XPathAPI.eval(resultSoapPart, "count(//ds:Reference)", nsElement).num()); // Setup soapMessageContext.put(MessageContext.MESSAGE_OUTBOUND_PROPERTY, false); // Operate : pass on signed message to WSSecurityClientHandler for // validation assertTrue(this.wsSecurityClientHandler.handleMessage(soapMessageContext)); // Operate : pass on signed message to WSSecurityClient handler // configured with wrong server certificate this.wsSecurityClientHandler.setServerCertificate(fooCertificate); try { this.wsSecurityClientHandler.handleMessage(soapMessageContext); fail(); } catch (SOAPFaultException e) { // expected LOG.debug("SOAPFaultException: " + e.getMessage()); } }
From source file:test.unit.be.agiv.security.handler.WSSecurityHandlerTest.java
@Test public void testVerifyTimestampExpired() throws Exception { // setup// w w w . ja va 2 s .co m SOAPMessageContext mockContext = EasyMock.createMock(SOAPMessageContext.class); EasyMock.expect(mockContext.get("javax.xml.ws.handler.message.outbound")).andStubReturn(Boolean.FALSE); InputStream requestInputStream = WSSecurityHandlerTest.class.getResourceAsStream("/ip-sts-response.xml"); SOAPMessage soapMessage = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL).createMessage(null, requestInputStream); EasyMock.expect(mockContext.getMessage()).andStubReturn(soapMessage); // prepare EasyMock.replay(mockContext); // operate try { this.testedInstance.handleMessage(mockContext); fail(); } catch (ProtocolException e) { // verify EasyMock.verify(mockContext); } }
From source file:test.unit.be.agiv.security.handler.WSSecurityHandlerTest.java
@Test public void testVerifyTimestamp() throws Exception { // setup/*from w w w .jav a2 s .c o m*/ SOAPMessageContext mockContext = EasyMock.createMock(SOAPMessageContext.class); EasyMock.expect(mockContext.get("javax.xml.ws.handler.message.outbound")).andStubReturn(Boolean.FALSE); SOAPMessage soapMessage = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL).createMessage(); SOAPBody soapBody = soapMessage.getSOAPBody(); soapBody.addBodyElement(new QName("test")); SOAPPart soapPart = soapMessage.getSOAPPart(); WSSecHeader secHeader = new WSSecHeader(); secHeader.insertSecurityHeader(soapPart); WSSecTimestamp timestamp = new WSSecTimestamp(); timestamp.build(soapPart, secHeader); LOG.debug("SOAP message: " + toString(soapMessage.getSOAPPart())); EasyMock.expect(mockContext.getMessage()).andStubReturn(soapMessage); // prepare EasyMock.replay(mockContext); // operate boolean result = this.testedInstance.handleMessage(mockContext); // verify EasyMock.verify(mockContext); assertTrue(result); }