Exemplo n.º 1
0
  protected void processToken(SoapMessage message) {
    Header h = findSecurityHeader(message, false);
    if (h == null) {
      return;
    }
    boolean utWithCallbacks =
        MessageUtils.getContextualBoolean(message, SecurityConstants.VALIDATE_TOKEN, true);

    Element el = (Element) h.getObject();
    Element child = DOMUtils.getFirstElement(el);
    while (child != null) {
      if (SPConstants.USERNAME_TOKEN.equals(child.getLocalName())
          && WSConstants.WSSE_NS.equals(child.getNamespaceURI())) {
        try {
          Principal principal = null;
          Subject subject = null;
          if (utWithCallbacks) {
            final WSSecurityEngineResult result = validateToken(child, message);
            principal = (Principal) result.get(WSSecurityEngineResult.TAG_PRINCIPAL);
            subject = (Subject) result.get(WSSecurityEngineResult.TAG_SUBJECT);
          } else {
            boolean bspCompliant = isWsiBSPCompliant(message);
            principal = parseTokenAndCreatePrincipal(child, bspCompliant);
            WSS4JTokenConverter.convertToken(message, principal);
          }

          SecurityContext sc = message.get(SecurityContext.class);
          if (sc == null || sc.getUserPrincipal() == null) {
            if (subject != null && principal != null) {
              message.put(SecurityContext.class, createSecurityContext(principal, subject));
            } else if (principal instanceof UsernameTokenPrincipal) {
              UsernameTokenPrincipal utPrincipal = (UsernameTokenPrincipal) principal;
              String nonce = null;
              if (utPrincipal.getNonce() != null) {
                nonce = Base64.encode(utPrincipal.getNonce());
              }
              subject =
                  createSubject(
                      utPrincipal.getName(),
                      utPrincipal.getPassword(),
                      utPrincipal.isPasswordDigest(),
                      nonce,
                      utPrincipal.getCreatedTime());
              message.put(SecurityContext.class, createSecurityContext(utPrincipal, subject));
            }
          }

          if (principal instanceof UsernameTokenPrincipal) {
            storeResults((UsernameTokenPrincipal) principal, message);
          }
        } catch (WSSecurityException ex) {
          throw new Fault(ex);
        } catch (Base64DecodingException ex) {
          throw new Fault(ex);
        }
      }
      child = DOMUtils.getNextElement(child);
    }
  }
  public String parseSecret(SoapMessage soapMessage) {
    Header header = soapMessage.getHeader(HEADER_TYPE);

    if (header != null) {
      // parse header. consider iterating through w3c DOM tree directly as an optimalization
      try {
        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();

        BankRequestHeader bankRequestHeader =
            (BankRequestHeader) unmarshaller.unmarshal((Node) header.getObject());

        return bankRequestHeader.getSecret();
      } catch (JAXBException e) {
        logger.warn("Unable to unmarshall header", e);
      }
    }
    return null;
  }
Exemplo n.º 3
0
 /**
  * <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> <soap:Header> <authInfo>
  * <username>admin</username> <password>123</password> </authInfo> </soap:Header> <soap:Body>
  * <ns2:sayHello xmlns:ns2="http://service.cxf.itsource.cn/"> <arg0>小明</arg0> </ns2:sayHello>
  * </soap:Body> </soap:Envelope>
  */
 @Override
 public void handleMessage(SoapMessage message) throws Fault {
   // 1、 获取header
   List<Header> headers = message.getHeaders();
   // 2、 验证header
   if (headers == null || headers.isEmpty() || headers.get(0) == null) {
     throw new Fault(new IllegalArgumentException("认证信息不能为空!!"));
   }
   Header header = headers.get(0);
   Element authInfoEl = (Element) header.getObject();
   // 3、 取出认证信息
   String username = authInfoEl.getElementsByTagName("username").item(0).getTextContent();
   String password = authInfoEl.getElementsByTagName("password").item(0).getTextContent();
   // 4、 验证
   if (!"admin".equals(username) || !"0".equals(password)) {
     throw new Fault(new IllegalArgumentException("用户名或密码错误!!"));
   }
 }
Exemplo n.º 4
0
  protected void addToken(SoapMessage message) {
    UsernameToken tok = assertTokens(message);

    Header h = findSecurityHeader(message, true);
    WSSecUsernameToken utBuilder = addUsernameToken(message, tok);
    if (utBuilder == null) {
      AssertionInfoMap aim = message.get(AssertionInfoMap.class);
      Collection<AssertionInfo> ais = getAllAssertionsByLocalname(aim, SPConstants.USERNAME_TOKEN);
      for (AssertionInfo ai : ais) {
        if (ai.isAsserted()) {
          ai.setAsserted(false);
        }
      }
      return;
    }
    Element el = (Element) h.getObject();
    utBuilder.prepare(el.getOwnerDocument());
    el.appendChild(utBuilder.getUsernameTokenElement());
  }
  public void handleMessage(Message m) throws Fault {
    if (!(m instanceof SoapMessage)) {
      return;
    }

    SoapMessage message = (SoapMessage) m;
    if (!message.hasHeaders()) {
      return;
    }
    Header mule_header = message.getHeader(MULE_HEADER_Q);
    if (mule_header == null) {
      return;
    }
    Object obj = mule_header.getObject();
    if (!(obj instanceof Element)) {
      // Error? We can't work with it at any rate.
      return;
    }

    Element header_element = (Element) obj;
    NodeList mule_headers = header_element.getChildNodes();
    int idx = 0;
    Node child;
    while ((child = mule_headers.item(idx++)) != null) {
      if (child.getNodeType() != Node.ELEMENT_NODE) {
        continue;
      }
      Element child_el = (Element) child;
      if (child_el.getNamespaceURI() == null || !child_el.getNamespaceURI().equals(MULE_NS_URI)) {
        continue;
      }

      if (SUPPORTED_HEADERS.contains(child_el.getLocalName())) {
        message.put(child_el.getLocalName(), collectTextFrom(child_el));
      }
    }

    MuleMessage reqMsg =
        ((MuleEvent) message.getExchange().get(CxfConstants.MULE_EVENT)).getMessage();

    // Copy correlation headers nto message
    String replyTo = (String) message.get(MuleProperties.MULE_REPLY_TO_PROPERTY);
    if (replyTo != null) {
      reqMsg.setReplyTo(replyTo);
    }

    String corId = (String) message.get(MuleProperties.MULE_CORRELATION_ID_PROPERTY);
    if (corId != null) {
      reqMsg.setCorrelationId(corId);
    }

    String corGroupSize = (String) message.get(MuleProperties.MULE_CORRELATION_GROUP_SIZE_PROPERTY);
    if (corGroupSize != null) {
      reqMsg.setCorrelationGroupSize(Integer.valueOf(corGroupSize));
    }

    String corSeq = (String) message.get(MuleProperties.MULE_CORRELATION_SEQUENCE_PROPERTY);
    if (corSeq != null) {
      reqMsg.setCorrelationSequence(Integer.valueOf(corSeq));
    }
  }
Exemplo n.º 6
0
  @SuppressWarnings("unchecked")
  protected void propagateHeadersFromCamelToCxf(
      Exchange camelExchange,
      Map<String, Object> camelHeaders,
      org.apache.cxf.message.Exchange cxfExchange,
      Map<String, Object> cxfContext) {

    // get cxf transport headers (if any) from camel exchange
    // use a treemap to keep ordering and ignore key case
    Map<String, List<String>> transportHeaders =
        new TreeMap<String, List<String>>(String.CASE_INSENSITIVE_ORDER);
    if (camelExchange != null) {
      Map<String, List<String>> h =
          CastUtils.cast((Map<?, ?>) camelExchange.getProperty(Message.PROTOCOL_HEADERS));
      if (h != null) {
        transportHeaders.putAll(h);
      }
    }
    Map<String, List<String>> headers =
        CastUtils.cast((Map<?, ?>) camelHeaders.get(Message.PROTOCOL_HEADERS));
    if (headers != null) {
      transportHeaders.putAll(headers);
    }

    DataFormat dataFormat =
        camelExchange.getProperty(CxfConstants.DATA_FORMAT_PROPERTY, DataFormat.class);

    for (Map.Entry<String, Object> entry : camelHeaders.entrySet()) {
      // put response code in request context so it will be copied to CXF message's property
      if (Message.RESPONSE_CODE.equals(entry.getKey())
          || Exchange.HTTP_RESPONSE_CODE.equals(entry.getKey())) {
        LOG.debug("Propagate to CXF header: {} value: {}", Message.RESPONSE_CODE, entry.getValue());
        cxfContext.put(Message.RESPONSE_CODE, entry.getValue());
        continue;
      }

      // We need to copy the content-type if the dataformat is RAW
      if (Message.CONTENT_TYPE.equalsIgnoreCase(entry.getKey())
          && dataFormat.equals(DataFormat.RAW)) {
        LOG.debug("Propagate to CXF header: {} value: {}", Message.CONTENT_TYPE, entry.getValue());
        cxfContext.put(Message.CONTENT_TYPE, entry.getValue().toString());
        continue;
      }

      // need to filter the User-Agent ignore the case, as CXF just check the header with
      // "User-Agent"
      if (entry.getKey().equalsIgnoreCase("User-Agent")) {
        List<String> listValue = new ArrayList<String>();
        listValue.add(entry.getValue().toString());
        transportHeaders.put("User-Agent", listValue);
      }

      // this header should be filtered, continue to the next header
      if (headerFilterStrategy.applyFilterToCamelHeaders(
          entry.getKey(), entry.getValue(), camelExchange)) {
        continue;
      }

      LOG.debug("Propagate to CXF header: {} value: {}", entry.getKey(), entry.getValue());

      // put SOAP/protocol header list in exchange
      if (Header.HEADER_LIST.equals(entry.getKey())) {
        List<Header> headerList = (List<Header>) entry.getValue();
        for (Header header : headerList) {
          header.setDirection(Header.Direction.DIRECTION_OUT);
          LOG.trace(
              "Propagate SOAP/protocol header: {} : {}", header.getName(), header.getObject());
        }

        // cxfExchange.put(Header.HEADER_LIST, headerList);
        cxfContext.put(entry.getKey(), headerList);
        continue;
      }

      // things that are not filtered and not specifically copied will be put in transport headers
      if (entry.getValue() instanceof List) {
        transportHeaders.put(entry.getKey(), (List<String>) entry.getValue());
      } else {
        List<String> listValue = new ArrayList<String>();
        listValue.add(entry.getValue().toString());
        transportHeaders.put(entry.getKey(), listValue);
      }
    }

    if (transportHeaders.size() > 0) {
      cxfContext.put(Message.PROTOCOL_HEADERS, transportHeaders);
    } else {
      // no propagated transport headers does really mean no headers, not the ones
      // from the previous request or response propagated with the invocation context
      cxfContext.remove(Message.PROTOCOL_HEADERS);
    }
  }