List of usage examples for javax.xml.ws.handler.soap SOAPMessageContext get
V get(Object key);
From source file:be.agiv.security.handler.AuthenticationHandler.java
private void handleOutboundMessage(SOAPMessageContext context) { String serviceRealm;//from w ww . ja va2 s.c om if (null != this.serviceRealm) { serviceRealm = this.serviceRealm; } else { String location = (String) context.get(BindingProvider.ENDPOINT_ADDRESS_PROPERTY); serviceRealm = location; } LOG.debug("service realm: " + serviceRealm); SecurityToken securityToken = this.securityTokenProvider.getSecurityToken(serviceRealm); this.wsSecurityHandler.setKey(securityToken.getKey(), securityToken.getAttachedReference(), securityToken.getToken(), true); }
From source file:be.e_contract.mycarenet.xkms2.KeyBindingAuthenticationSignatureSOAPHandler.java
@Override public boolean handleMessage(SOAPMessageContext context) { Boolean outboundProperty = (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY); if (false == outboundProperty) { return true; }/*from ww w .ja va2 s. com*/ LOG.debug("adding key binding authentication signature"); SOAPMessage soapMessage = context.getMessage(); SOAPPart soapPart = soapMessage.getSOAPPart(); String requestElementName; if (null != this.prototypeKeyBindingId) { requestElementName = "RegisterRequest"; this.referenceUri = "#" + this.prototypeKeyBindingId; } else if (null != this.revokeKeyBindingId) { requestElementName = "RevokeRequest"; this.referenceUri = "#" + this.revokeKeyBindingId; } else { LOG.error("missing key binding id"); return false; } NodeList requestNodeList = soapPart.getElementsByTagNameNS(XKMS2ServiceFactory.XKMS2_NAMESPACE, requestElementName); Element requestElement = (Element) requestNodeList.item(0); if (null == requestElement) { LOG.error("request element not present"); return false; } Document xkmsDocument; try { xkmsDocument = copyDocument(requestElement); } catch (ParserConfigurationException e) { LOG.error("error copying XKMS request: " + e.getMessage(), e); return false; } NodeList keyBindingAuthenticationNodeList = xkmsDocument .getElementsByTagNameNS(XKMS2ServiceFactory.XKMS2_NAMESPACE, "KeyBindingAuthentication"); Element keyBindingAuthenticationElement = (Element) keyBindingAuthenticationNodeList.item(0); try { prepareDocument(xkmsDocument); addSignature(keyBindingAuthenticationElement); } catch (Exception e) { LOG.error("error adding authn signature: " + e.getMessage(), e); return false; } Node signatureNode = soapPart.importNode(keyBindingAuthenticationElement.getFirstChild(), true); keyBindingAuthenticationNodeList = soapPart.getElementsByTagNameNS(XKMS2ServiceFactory.XKMS2_NAMESPACE, "KeyBindingAuthentication"); keyBindingAuthenticationElement = (Element) keyBindingAuthenticationNodeList.item(0); keyBindingAuthenticationElement.appendChild(signatureNode); return true; }
From source file:eu.payzen.webservices.sdk.handler.soap.HeaderHandler.java
/** * Takes the outgoing SOAP message and modifies it adding the header * information//from w ww . ja va 2 s .co m * * @param smc SOAP message context * @return boolean indicating outbound property */ public boolean handleMessage(SOAPMessageContext smc) { Boolean outboundProperty = (Boolean) smc.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY); if (Boolean.TRUE.equals(outboundProperty)) { SOAPMessage message = smc.getMessage(); try { SOAPEnvelope envelope = message.getSOAPPart().getEnvelope(); //Creates header into SOAP envelope SOAPHeader header = envelope.getHeader(); if (header == null) { header = envelope.addHeader(); } // Add shopId addHeaderField(header, "shopId", this.shopId); // Add User name if (wsUser != null) { addHeaderField(header, "wsUser", this.wsUser); } // Add return url if (returnUrl != null) { addHeaderField(header, "returnUrl", this.returnUrl); } // Add ecsPaymentId if (ecsPaymentId != null) { addHeaderField(header, "ecsPaymentId", this.ecsPaymentId); } // Add remoteId if (remoteId != null) { addHeaderField(header, "remoteId", this.remoteId); } //DynamicHeaders if (dynamicHeaders != null) { for (String key : dynamicHeaders.keySet()) { String value = dynamicHeaders.get(key); if (value != null) { addHeaderField(header, key, value); } } } // Timestamp TimeZone tz = TimeZone.getTimeZone("UTC"); DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); df.setTimeZone(tz); String nowAsISO = df.format(new Date()); addHeaderField(header, "timestamp", nowAsISO); // Mode addHeaderField(header, "mode", this.mode); // Add requestId String requestId = UUID.randomUUID().toString(); addHeaderField(header, "requestId", requestId); // Authentication token String tokenString = requestId + nowAsISO; addHeaderField(header, "authToken", sign(tokenString, shopKey)); } catch (SOAPException e) { logger.error("Error sending header", e); } } return outboundProperty; }
From source file:com.hiperium.integration.access.control.SoapSessionHandler.java
@SuppressWarnings("unchecked") @Override/* w w w . j a v a2 s. co m*/ public boolean handleMessage(SOAPMessageContext context) { LOGGER.debug("handleMessage - BEGIN"); // Only message arriving from the client. Not processing responses. Boolean outbound = (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY); if (!outbound) { Map<String, List<String>> map = (Map<String, List<String>>) context .get(MessageContext.HTTP_REQUEST_HEADERS); List<String> sessionHeader = this.getHTTPHeader(map, CommonsUtil.SESSIONID); if (sessionHeader == null) { SOAPMessage msg = context.getMessage(); this.generateFault(msg, Resources.getResourceBundle(EnumI18N.SECURITY, Locale.getDefault()) .getString("ilegalAccessResource")); } // Get the sessionId from the entire HTTP Message StringBuffer sessionIdBuffer = new StringBuffer(); for (String session : sessionHeader) { sessionIdBuffer.append(session); } // Validate that the session ID is valid if (StringUtils.isNotBlank(sessionIdBuffer.toString()) && !this.securityBusinessDelegate .getSessionManagerBO().findIfHomeLoggedIn(sessionIdBuffer.toString())) { SOAPMessage msg = context.getMessage(); this.generateFault(msg, Resources.getResourceBundle(EnumI18N.SECURITY, Locale.getDefault()) .getString("ilegalAccessResource")); } } LOGGER.debug("handleMessage - END"); return true; //continue other handler chain }
From source file:com.qubit.solution.fenixedu.bennu.webservices.services.server.BennuWebServiceHandler.java
@Override public boolean handleMessage(SOAPMessageContext context) { Boolean isRequest = (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY); //for response message only, true for outbound messages, false for inbound if (!isRequest) { try {/*from www. ja v a 2 s . c o m*/ WebServiceServerConfiguration configuration = getWebServiceServerConfiguration( ((com.sun.xml.ws.api.server.WSEndpoint) context.get("com.sun.xml.ws.api.server.WSEndpoint")) .getImplementationClass().getName()); SOAPMessage soapMsg = context.getMessage(); SOAPEnvelope soapEnv = soapMsg.getSOAPPart().getEnvelope(); SOAPHeader soapHeader = soapEnv.getHeader(); if (!configuration.isActive()) { generateSOAPErrorMessage(soapMsg, "Sorry webservice is disabled at application level!"); } if (configuration.isAuthenticatioNeeded()) { if (configuration.isUsingWSSecurity()) { if (soapHeader == null) { generateSOAPErrorMessage(soapMsg, "No header in message, unabled to validate security credentials"); } String username = null; String password = null; String nonce = null; String created = null; Iterator<SOAPElement> childElements = soapHeader.getChildElements(QNAME_WSSE_SECURITY); if (childElements.hasNext()) { SOAPElement securityElement = childElements.next(); Iterator<SOAPElement> usernameTokens = securityElement .getChildElements(QNAME_WSSE_USERNAME_TOKEN); if (usernameTokens.hasNext()) { SOAPElement usernameToken = usernameTokens.next(); username = ((SOAPElement) usernameToken.getChildElements(QNAME_WSSE_USERNAME) .next()).getValue(); password = ((SOAPElement) usernameToken.getChildElements(QNAME_WSSE_PASSWORD) .next()).getValue(); nonce = ((SOAPElement) usernameToken.getChildElements(QNAME_WSSE_NONCE).next()) .getValue(); created = ((SOAPElement) usernameToken.getChildElements(QNAME_WSSE_CREATED).next()) .getValue(); } } if (username == null || password == null || nonce == null || created == null) { generateSOAPErrorMessage(soapMsg, "Missing information, unabled to validate security credentials"); } SecurityHeader securityHeader = new SecurityHeader(configuration, username, password, nonce, created); if (!securityHeader.isValid()) { generateSOAPErrorMessage(soapMsg, "Invalid credentials"); } else { context.put(BennuWebService.SECURITY_HEADER, securityHeader); context.setScope(BennuWebService.SECURITY_HEADER, Scope.APPLICATION); } } else { com.sun.xml.ws.transport.Headers httpHeader = (Headers) context .get(MessageContext.HTTP_REQUEST_HEADERS); String username = null; String password = null; List<String> list = httpHeader.get("authorization"); if (list != null) { for (String value : list) { if (value.startsWith("Basic")) { String[] split = value.split(" "); try { String decoded = new String(Base64.decodeBase64(split[1]), "UTF-8"); String[] split2 = decoded.split(":"); if (split2.length == 2) { username = split2[0]; password = split2[1]; } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } } } if (username == null || password == null) { generateSOAPErrorMessage(soapMsg, "Missing information, unabled to validate security credentials"); } if (!configuration.validate(username, password)) { generateSOAPErrorMessage(soapMsg, "Invalid credentials"); } } } } catch (SOAPException e) { System.err.println(e); } } //continue other handler chain return true; }
From source file:com.vmware.identity.sts.ws.handlers.LogContextHandler.java
@Override public boolean handleMessage(SOAPMessageContext context) { Validate.notNull(context, "SOAPMessageContext should not be null."); Boolean outbound = (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY); if (outbound != null && outbound.equals(Boolean.TRUE)) { return true; } else {//from w w w. jav a 2 s.c om String tenant = null; String correlationId = null; // http://docs.oracle.com/javase/7/docs/api/javax/xml/ws/handler/MessageContext.html : // static final String HTTP_REQUEST_HEADERS // Standard property: HTTP request headers. // Type: java.util.Map<java.lang.String, java.util.List<java.lang.String>> // // static final String SERVLET_REQUEST // Standard property: servlet request object. // Type: javax.servlet.http.HttpServletRequest HttpServletRequest request = (HttpServletRequest) (context.get(MessageContext.SERVLET_REQUEST)); Validate.notNull(request, "HttpServletRequest should not be null."); @SuppressWarnings("unchecked") Map<String, List<String>> headers = (Map<String, List<String>>) (context .get(MessageContext.HTTP_REQUEST_HEADERS)); if (headers != null) { List<String> correlationIds = headers.get(WsConstants.ACTIVITY_CORRELATION_ID_CUSTOM_HEADER); if ((correlationIds != null) && (correlationIds.size() > 1)) { correlationId = correlationIds.get(0); correlationId = LogContextHandler.removeNewline(correlationId); correlationId = LogContextHandler.truncate(correlationId, 200); } } if ((correlationId == null) || (correlationId.isEmpty())) { correlationId = UUID.randomUUID().toString(); logger.debug("unable to extract correlation id from request. generated new correllation id [{}]", correlationId); } else { logger.debug("extracted correlation id [{}] from the request", correlationId); } try { tenant = TenantExtractor.extractTenantName(request.getPathInfo()); tenant = LogContextHandler.removeNewline(tenant); tenant = LogContextHandler.truncate(tenant, 200); logger.debug("extracted tenant [{}] from the request", tenant); } catch (NoSuchIdPException ex) { logger.error("failed to extract tenant from the request", ex); } if ((tenant == null) || (tenant.isEmpty())) { tenant = WsConstants.DEFAULT_TENANT; logger.debug( "unable to extract explicit tenant name from request. Using default tenant marker [{}].", tenant); } else { logger.debug("extracted tenant name [{}] from the request", tenant); } this._diagCtxt = DiagnosticsContextFactory.createContext(correlationId, tenant); } return true; }
From source file:de.drv.dsrv.spoc.web.webservice.jax.ExtraSchemaValidationHandler.java
@Override public boolean handleMessage(final SOAPMessageContext context) { // Nur fuer den Eingang final Boolean isOutBound = (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY); if (isOutBound) { return true; }//from www.j a v a2s .c o m // Servlet-Context speichern final ServletContext servletContext = (ServletContext) context.get(MessageContext.SERVLET_CONTEXT); SOAPBody soapBody = getSoapBody(context); try { // Pruefe SOAP-Body if (soapBody == null) { try { // Erstelle neue SOAP-Message mit SOAP-Body final SOAPMessage soapMessage = MessageFactory.newInstance().createMessage(); soapBody = soapMessage.getSOAPBody(); context.setMessage(soapMessage); } catch (final SOAPException e) { LOG.error("Exception beim Erstellen einer SOAP-Message.", e); } // Request ungueltig - z.B. ungueltiges XML throw new InvalidExtraRequestException(resourceBundle.getString(Messages.ERROR_REQUEST_NO_EXTRA)); } // Hole Transport-Element final Node transportNode = getTransportElement(soapBody); if (transportNode == null) { // kein 'Transport'-Element, Request ungueltig throw new InvalidExtraRequestException(resourceBundle.getString(Messages.ERROR_REQUEST_NO_EXTRA)); } // Validiere Request-XML gegen eXTra-Schema validateExtraRequest(transportNode, servletContext); } catch (final InvalidExtraRequestException e) { return handleException(soapBody, e.getMessage(), ExtraErrorReasonType.INVALID_REQUEST); } catch (final Exception e) { LOG.error("Unbekannter Fehler beim Request-Validierung.", e); return handleException(soapBody, resourceBundle.getString(Messages.ERROR_REQUEST_VALIDATION_UNKNOWN), ExtraErrorReasonType.UNSPECIFIED); } return true; }
From source file:be.fedict.trust.xkms2.WSSecurityServerHandler.java
/** * {@inheritDoc}//from ww w . ja v a2 s . co m */ public boolean handleMessage(SOAPMessageContext soapMessageContext) { LOG.debug("handle message"); Boolean outboundProperty = (Boolean) soapMessageContext.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY); SOAPMessage soapMessage = soapMessageContext.getMessage(); SOAPPart soapPart = soapMessage.getSOAPPart(); if (true == outboundProperty.booleanValue()) { handleOutboundDocument(soapPart, soapMessageContext); } else { handleInboundDocument(soapPart, soapMessageContext); } return true; }
From source file:be.agiv.security.handler.WSSecurityHandler.java
public boolean handleMessage(SOAPMessageContext context) { Boolean outboundProperty = (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY); if (true == outboundProperty.booleanValue()) { try {//from ww w .j ava 2 s .c om handleOutboundMessage(context); } catch (Exception e) { LOG.error("outbound exception: " + e.getMessage(), e); throw new ProtocolException(e); } } else { try { handleInboundMessage(context); } catch (Exception e) { throw new ProtocolException(e); } } return true; }
From source file:com.hiperium.integration.access.control.SoapSignatureHandler.java
@SuppressWarnings("unchecked") @Override//from w ww. jav a2s . c o m public boolean handleMessage(SOAPMessageContext context) { LOGGER.debug("handleMessage - BEGIN"); // Only message arriving from the client. Not processing responses. Boolean outbound = (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY); if (!outbound) { // Get the sessionId from the entire HTTP Message StringBuffer sessionIdBuffer = new StringBuffer(); Map<String, List<String>> map = (Map<String, List<String>>) context .get(MessageContext.HTTP_REQUEST_HEADERS); for (String session : this.getHTTPHeader(map, CommonsUtil.SESSIONID)) { sessionIdBuffer.append(session); } // Try to get SOAP header values from the SOAP message try { SOAPMessage msg = context.getMessage(); if (LOGGER.isDebugEnabled()) { System.out.println("REQUEST:"); msg.writeTo(System.out); System.out.println(); } Node node = msg.getSOAPHeader().getFirstChild(); // Header values NodeList nodeList = node.getChildNodes(); // Name, TimeStamp, Signature. if (nodeList.getLength() < 3) { this.generateFault(msg, "Too few header nodes!"); } // Extract the required attributes. Long homeId = Long.valueOf(nodeList.item(0).getFirstChild().getNodeValue()); String signature = nodeList.item(1).getFirstChild().getNodeValue(); String timestamp = nodeList.item(2).getFirstChild().getNodeValue(); if (StringUtils.isBlank(timestamp) || StringUtils.isBlank(signature)) { this.generateFault(msg, "Missing header key/value pairs!"); } // Validates that the user Token exists in the DB for valid registered external Application. String token = this.securityBusinessDelegate.getHomeGatewayBO().findTokenInSession(homeId, sessionIdBuffer.toString()); if (StringUtils.isBlank(token)) { this.generateFault(msg, homeId.toString().concat(" not registered!")); } // Generate comparison signature and compare against what's sent. byte[] secretBytes = Signature.getBytes(token); String localSignature = Signature.createSignature(homeId, timestamp, secretBytes); if (!this.verify(signature, localSignature)) { this.generateFault(msg, "HMAC signatures do not match."); } } catch (Exception e) { throw new RuntimeException("SOAPException thrown.", e); } } LOGGER.debug("handleMessage - END"); return true; //continue other handler chain }