Java Code Examples for org.apache.cxf.message.MessageUtils#getContextualBoolean()

The following examples show how to use org.apache.cxf.message.MessageUtils#getContextualBoolean() . 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: RequestPreprocessor.java    From cxf with Apache License 2.0 6 votes vote down vote up
private void handleMethod(Message m,
                          MultivaluedMap<String, String> queries,
                          HttpHeaders headers) {
    if (MessageUtils.getContextualBoolean(m, ALLOW_HTTP_METHOD_OVERRIDE, false)) {
        String method = queries.getFirst(METHOD_QUERY);
        if (method == null) {
            List<String> list = headers.getRequestHeader(METHOD_HEADER);
            if (list != null && list.size() == 1) {
                method = list.get(0);
            }
        }
        if (method != null) {
            m.put(Message.HTTP_REQUEST_METHOD, method);
        }
    }
}
 
Example 2
Source File: STSUtils.java    From steady with Apache License 2.0 6 votes vote down vote up
public static STSClient getClient(Message message, String type, IssuedToken itok) {
    STSClient client = (STSClient)message
        .getContextualProperty(SecurityConstants.STS_CLIENT);
    if (client == null) {
        if (type == null) {
            type = "";
        } else {
            type = "." + type + "-client";
        }
        client = new STSClient(message.getExchange().get(Bus.class));
        Endpoint ep = message.getExchange().get(Endpoint.class);
        client.setEndpointName(ep.getEndpointInfo().getName().toString() + type);
        client.setBeanName(ep.getEndpointInfo().getName().toString() + type);
        if (MessageUtils.getContextualBoolean(message, SecurityConstants.STS_CLIENT_SOAP12_BINDING, false)) {
            client.setSoap12();
        }
        if ((itok != null) && (itok.getIssuerEpr() != null)) {
            //configure via mex
            boolean useEPRWSAAddrAsMEXLocation = !Boolean.valueOf(
                    (String)message.getContextualProperty(
                     SecurityConstants.DISABLE_STS_CLIENT_WSMEX_CALL_USING_EPR_ADDRESS));
            client.configureViaEPR(itok.getIssuerEpr(), useEPRWSAAddrAsMEXLocation);
        }
    }
    return client;
}
 
Example 3
Source File: Headers.java    From cxf with Apache License 2.0 6 votes vote down vote up
/**
 * This procedure sets the URLConnection request properties
 * from the PROTOCOL_HEADERS in the message.
 */
private void transferProtocolHeadersToURLConnection(URLConnection connection) {
    boolean addHeaders = MessageUtils.getContextualBoolean(message, ADD_HEADERS_PROPERTY, false);
    for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
        String header = entry.getKey();
        if (HttpHeaderHelper.CONTENT_TYPE.equalsIgnoreCase(header)) {
            continue;
        }

        List<String> headerList = entry.getValue();
        if (addHeaders || HttpHeaderHelper.COOKIE.equalsIgnoreCase(header)) {
            headerList.forEach(s -> connection.addRequestProperty(header, s));
        } else {
            connection.setRequestProperty(header, String.join(",", headerList));
        }
    }
    // make sure we don't add more than one User-Agent header
    if (connection.getRequestProperty("User-Agent") == null) {
        connection.addRequestProperty("User-Agent", USER_AGENT);
    }
}
 
Example 4
Source File: STSUtils.java    From steady with Apache License 2.0 6 votes vote down vote up
public static STSClient getClient(Message message, String type, IssuedToken itok) {
    STSClient client = (STSClient)message
        .getContextualProperty(SecurityConstants.STS_CLIENT);
    if (client == null) {
        if (type == null) {
            type = "";
        } else {
            type = "." + type + "-client";
        }
        client = new STSClient(message.getExchange().get(Bus.class));
        Endpoint ep = message.getExchange().get(Endpoint.class);
        client.setEndpointName(ep.getEndpointInfo().getName().toString() + type);
        client.setBeanName(ep.getEndpointInfo().getName().toString() + type);
        if (MessageUtils.getContextualBoolean(message, SecurityConstants.STS_CLIENT_SOAP12_BINDING, false)) {
            client.setSoap12();
        }
        if ((itok != null) && (itok.getIssuerEpr() != null)) {
            //configure via mex
            boolean useEPRWSAAddrAsMEXLocation = !Boolean.valueOf(
                    (String)message.getContextualProperty(
                     SecurityConstants.DISABLE_STS_CLIENT_WSMEX_CALL_USING_EPR_ADDRESS));
            client.configureViaEPR(itok.getIssuerEpr(), useEPRWSAAddrAsMEXLocation);
        }
    }
    return client;
}
 
Example 5
Source File: JwkUtils.java    From cxf with Apache License 2.0 6 votes vote down vote up
public static JsonWebKey loadJsonWebKey(Message m, Properties props, KeyOperation keyOper, String inHeaderKid) {
    PrivateKeyPasswordProvider cb = KeyManagementUtils.loadPasswordProvider(m, props, keyOper);
    JsonWebKeys jwkSet = loadJwkSet(m, props, cb);
    String kid = null;
    if (inHeaderKid != null
        && MessageUtils.getContextualBoolean(m, JoseConstants.RSSEC_ACCEPT_PUBLIC_KEY, false)) {
        kid = inHeaderKid;
    } else {
        kid = KeyManagementUtils.getKeyId(m, props, JoseConstants.RSSEC_KEY_STORE_ALIAS, keyOper);
    }
    if (kid != null) {
        return jwkSet.getKey(kid);
    } else if (keyOper != null) {
        List<JsonWebKey> keys = jwkSet.getKeyOperationMap().get(keyOper);
        if (keys != null && keys.size() == 1) {
            return keys.get(0);
        }
    }
    return null;
}
 
Example 6
Source File: STSUtils.java    From steady with Apache License 2.0 6 votes vote down vote up
public static STSClient getClient(Message message, String type, IssuedToken itok) {
    STSClient client = (STSClient)message
        .getContextualProperty(SecurityConstants.STS_CLIENT);
    if (client == null) {
        if (type == null) {
            type = "";
        } else {
            type = "." + type + "-client";
        }
        client = new STSClient(message.getExchange().get(Bus.class));
        Endpoint ep = message.getExchange().get(Endpoint.class);
        client.setEndpointName(ep.getEndpointInfo().getName().toString() + type);
        client.setBeanName(ep.getEndpointInfo().getName().toString() + type);
        if (MessageUtils.getContextualBoolean(message, SecurityConstants.STS_CLIENT_SOAP12_BINDING, false)) {
            client.setSoap12();
        }
        if ((itok != null) && (itok.getIssuerEpr() != null)) {
            //configure via mex
            boolean useEPRWSAAddrAsMEXLocation = !Boolean.valueOf(
                    (String)message.getContextualProperty(
                     SecurityConstants.DISABLE_STS_CLIENT_WSMEX_CALL_USING_EPR_ADDRESS));
            client.configureViaEPR(itok.getIssuerEpr(), useEPRWSAAddrAsMEXLocation);
        }
    }
    return client;
}
 
Example 7
Source File: AsyncHTTPConduit.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected void setProtocolHeaders() throws IOException {
    Headers h = new Headers(outMessage);
    basicEntity.setContentType(h.determineContentType());
    boolean addHeaders = MessageUtils.getContextualBoolean(outMessage, Headers.ADD_HEADERS_PROPERTY, false);

    for (Map.Entry<String, List<String>> header : h.headerMap().entrySet()) {
        if (HttpHeaderHelper.CONTENT_TYPE.equalsIgnoreCase(header.getKey())) {
            continue;
        }
        if (addHeaders || HttpHeaderHelper.COOKIE.equalsIgnoreCase(header.getKey())) {
            for (String s : header.getValue()) {
                entity.addHeader(HttpHeaderHelper.COOKIE, s);
            }
        } else if (!"Content-Length".equalsIgnoreCase(header.getKey())) {
            StringBuilder b = new StringBuilder();
            for (int i = 0; i < header.getValue().size(); i++) {
                b.append(header.getValue().get(i));
                if (i + 1 < header.getValue().size()) {
                    b.append(',');
                }
            }
            entity.setHeader(header.getKey(), b.toString());
        }
        if (!entity.containsHeader("User-Agent")) {
            entity.setHeader("User-Agent", Version.getCompleteVersionString());
        }
    }
}
 
Example 8
Source File: SoapActionInInterceptor.java    From cxf with Apache License 2.0 5 votes vote down vote up
private static boolean isActionMatch(SoapMessage message, BindingOperationInfo boi, String action) {
    SoapOperationInfo soi = boi.getExtensor(SoapOperationInfo.class);
    if (soi == null) {
        return false;
    }
    boolean allowNoMatchingToDefault = MessageUtils.getContextualBoolean(message,
                                                                ALLOW_NON_MATCHING_TO_DEFAULT,
                                                                false);
    return action.equals(soi.getAction())
           || (allowNoMatchingToDefault && StringUtils.isEmpty(soi.getAction())
           || (message.getVersion() instanceof Soap12) && StringUtils.isEmpty(soi.getAction()));
}
 
Example 9
Source File: LocalConduit.java    From cxf with Apache License 2.0 5 votes vote down vote up
public void prepare(final Message message) throws IOException {
    if (!MessageUtils.getContextualBoolean(message, DIRECT_DISPATCH)) {
        dispatchViaPipe(message);
    } else {
        // prepare the stream here
        CachedOutputStream stream = new CachedOutputStream();
        message.setContent(OutputStream.class, stream);
        //save the original stream
        message.put(CachedOutputStream.class, stream);
        stream.holdTempFile();
    }
}
 
Example 10
Source File: RMInInterceptor.java    From cxf with Apache License 2.0 5 votes vote down vote up
private boolean isRedeliveryEnabled(Message message) {
    // deprecated redelivery mode check
    if (MessageUtils.getContextualBoolean(message, "org.apache.cxf.ws.rm.destination.redeliver", false)) {
        LOG.warning("Use RetryPolicy to enable the redelivery mode");
        return true;
    }
    return getManager().getDestinationPolicy() != null
        && getManager().getDestinationPolicy().getRetryPolicy() != null;
}
 
Example 11
Source File: InternalContextUtils.java    From cxf with Apache License 2.0 4 votes vote down vote up
/**
 * Rebase response on replyTo
 *
 * @param reference the replyTo reference
 * @param inMAPs the inbound MAPs
 * @param inMessage the current message
 */
//CHECKSTYLE:OFF Max executable statement count limitation
public static void rebaseResponse(EndpointReferenceType reference,
                                  AddressingProperties inMAPs,
                                  final Message inMessage) {

    String namespaceURI = inMAPs.getNamespaceURI();
    if (!ContextUtils.retrievePartialResponseSent(inMessage)) {
        ContextUtils.storePartialResponseSent(inMessage);
        Exchange exchange = inMessage.getExchange();
        Message fullResponse = exchange.getOutMessage();
        Message partialResponse = ContextUtils.createMessage(exchange);
        ensurePartialResponseMAPs(partialResponse, namespaceURI);

        // ensure the inbound MAPs are available in the partial response
        // message (used to determine relatesTo etc.)
        ContextUtils.propogateReceivedMAPs(inMAPs, partialResponse);
        Destination target = inMessage.getDestination();
        if (target == null) {
            return;
        }

        try {
            if (reference == null) {
                reference = ContextUtils.getNoneEndpointReference();
            }
            Conduit backChannel = target.getBackChannel(inMessage);
            if (backChannel != null) {
                partialResponse.put(Message.PARTIAL_RESPONSE_MESSAGE, Boolean.TRUE);
                partialResponse.put(Message.EMPTY_PARTIAL_RESPONSE_MESSAGE, Boolean.TRUE);
                boolean robust = MessageUtils.getContextualBoolean(inMessage, Message.ROBUST_ONEWAY, false);

                if (robust) {
                    BindingOperationInfo boi = exchange.getBindingOperationInfo();
                    // insert the executor in the exchange to fool the OneWayProcessorInterceptor
                    exchange.put(Executor.class, getExecutor(inMessage));
                    // pause dispatch on current thread and resume...
                    inMessage.getInterceptorChain().pause();
                    inMessage.getInterceptorChain().resume();
                    // restore the BOI for the partial response handling
                    exchange.put(BindingOperationInfo.class, boi);
                }


                // set up interceptor chains and send message
                InterceptorChain chain =
                    fullResponse != null
                    ? fullResponse.getInterceptorChain()
                    : OutgoingChainInterceptor.getOutInterceptorChain(exchange);
                exchange.setOutMessage(partialResponse);
                partialResponse.setInterceptorChain(chain);
                exchange.put(ConduitSelector.class,
                             new PreexistingConduitSelector(backChannel,
                                                            exchange.getEndpoint()));

                if (chain != null && !chain.doIntercept(partialResponse)
                    && partialResponse.getContent(Exception.class) != null) {
                    if (partialResponse.getContent(Exception.class) instanceof Fault) {
                        throw (Fault)partialResponse.getContent(Exception.class);
                    }
                    throw new Fault(partialResponse.getContent(Exception.class));
                }
                if (chain != null) {
                    chain.reset();
                }
                exchange.put(ConduitSelector.class, new NullConduitSelector());

                if (fullResponse == null) {
                    fullResponse = ContextUtils.createMessage(exchange);
                }
                exchange.setOutMessage(fullResponse);

                Destination destination = createDecoupledDestination(
                    exchange,
                    reference);
                exchange.setDestination(destination);

            }
        } catch (Exception e) {
            LOG.log(Level.WARNING, "SERVER_TRANSPORT_REBASE_FAILURE_MSG", e);
        }
    }
}
 
Example 12
Source File: AbstractStaxBindingHandler.java    From cxf with Apache License 2.0 4 votes vote down vote up
protected void configureSignature(
    AbstractToken token, boolean attached
) throws WSSecurityException {

    if (token instanceof X509Token) {
        X509Token x509Token = (X509Token) token;
        TokenType tokenType = x509Token.getTokenType();
        if (tokenType == TokenType.WssX509PkiPathV1Token10
            || tokenType == TokenType.WssX509PkiPathV1Token11) {
            properties.setUseSingleCert(false);
        }
    }

    properties.setSignatureKeyIdentifier(getKeyIdentifierType(token));

    // Find out do we also need to include the token as per the Inclusion requirement
    properties.setIncludeSignatureToken(false);
    for (SecurityTokenConstants.KeyIdentifier keyIdentifier : properties.getSignatureKeyIdentifiers()) {
        if (token instanceof X509Token
            && isTokenRequired(token.getIncludeTokenType())
            && (WSSecurityTokenConstants.KeyIdentifier_IssuerSerial.equals(keyIdentifier)
                || WSSecurityTokenConstants.KEYIDENTIFIER_THUMBPRINT_IDENTIFIER.equals(keyIdentifier)
                || WSSecurityTokenConstants.KEYIDENTIFIER_SECURITY_TOKEN_DIRECT_REFERENCE.equals(
                    keyIdentifier))) {
            properties.setIncludeSignatureToken(true);
        }
    }

    String userNameKey = SecurityConstants.SIGNATURE_USERNAME;
    if (binding instanceof SymmetricBinding) {
        userNameKey = SecurityConstants.ENCRYPT_USERNAME;
        properties.setSignatureAlgorithm(
                   binding.getAlgorithmSuite().getAlgorithmSuiteType().getSymmetricSignature());
    } else {
        properties.setSignatureAlgorithm(
                   binding.getAlgorithmSuite().getAlgorithmSuiteType().getAsymmetricSignature());
    }
    properties.setSignatureCanonicalizationAlgorithm(
                   binding.getAlgorithmSuite().getC14n().getValue());
    String sigUser = (String)SecurityUtils.getSecurityPropertyValue(userNameKey, message);
    if (sigUser == null) {
        sigUser = (String)SecurityUtils.getSecurityPropertyValue(SecurityConstants.USERNAME, message);
    }
    if (sigUser != null && properties.getSignatureUser() == null) {
        properties.setSignatureUser(sigUser);
    }

    AlgorithmSuiteType algType = binding.getAlgorithmSuite().getAlgorithmSuiteType();
    properties.setSignatureDigestAlgorithm(algType.getDigest());
    // sig.setSigCanonicalization(binding.getAlgorithmSuite().getC14n().getValue());

    boolean includePrefixes =
        MessageUtils.getContextualBoolean(
            message, SecurityConstants.ADD_INCLUSIVE_PREFIXES, true
        );
    properties.setAddExcC14NInclusivePrefixes(includePrefixes);
}
 
Example 13
Source File: PhaseInterceptorChain.java    From cxf with Apache License 2.0 4 votes vote down vote up
private boolean isRobustOneWay(Message message) {
    return MessageUtils.getContextualBoolean(message, Message.ROBUST_ONEWAY, false);
}
 
Example 14
Source File: DestinationSequence.java    From cxf with Apache License 2.0 4 votes vote down vote up
public void acknowledge(Message message) throws SequenceFault {
    RMProperties rmps = RMContextUtils.retrieveRMProperties(message, false);
    SequenceType st = rmps.getSequence();
    long messageNumber = st.getMessageNumber();
    LOG.fine("Acknowledging message: " + messageNumber);
    if (0L != lastMessageNumber && messageNumber > lastMessageNumber) {
        RMConstants consts = getProtocol().getConstants();
        SequenceFaultFactory sff = new SequenceFaultFactory(consts);
        throw sff.createSequenceTerminatedFault(st.getIdentifier(), false);
    }

    monitor.acknowledgeMessage();
    boolean updated = false;

    synchronized (this) {
        boolean done = false;
        int i = 0;
        for (; i < acknowledgement.getAcknowledgementRange().size(); i++) {
            AcknowledgementRange r = acknowledgement.getAcknowledgementRange().get(i);
            if (r.getLower().compareTo(messageNumber) <= 0
                && r.getUpper().compareTo(messageNumber) >= 0) {
                done = true;
                break;
            }
            long diff = r.getLower() - messageNumber;
            if (diff == 1L) {
                r.setLower(messageNumber);
                updated = true;
                done = true;
            } else if (diff > 0L) {
                break;
            } else if (messageNumber - r.getUpper() == 1L) {
                r.setUpper(messageNumber);
                updated = true;
                done = true;
                break;
            }
        }

        if (!done) {

            // need new acknowledgement range
            AcknowledgementRange range = new AcknowledgementRange();
            range.setLower(messageNumber);
            range.setUpper(messageNumber);
            updated = true;
            acknowledgement.getAcknowledgementRange().add(i, range);
            if (acknowledgement.getAcknowledgementRange().size() > 1) {

                // acknowledge out-of-order at first opportunity
                scheduleImmediateAcknowledgement();

            }
        }
        mergeRanges();
    }

    if (updated) {
        RMStore store = destination.getManager().getStore();
        if (null != store && !MessageUtils.getContextualBoolean(message, Message.ROBUST_ONEWAY)) {
            try {
                RMMessage msg = new RMMessage();
                CachedOutputStream cos = (CachedOutputStream)message
                    .get(RMMessageConstants.SAVED_CONTENT);
                msg.setMessageNumber(st.getMessageNumber());
                msg.setCreatedTime(rmps.getCreatedTime());
                // in case no attachments are available, cos can be saved directly
                if (message.getAttachments() == null) {
                    msg.setContent(cos);
                    msg.setContentType((String)message.get(Message.CONTENT_TYPE));
                } else {
                    InputStream is = cos.getInputStream();
                    PersistenceUtils.encodeRMContent(msg, message, is);
                }
                store.persistIncoming(this, msg);
            } catch (IOException e) {
                throw new Fault(e);
            }
        }
    }
    deliveringMessageNumbers.add(messageNumber);

    RMEndpoint reliableEndpoint = destination.getReliableEndpoint();
    RMConfiguration cfg = reliableEndpoint.getConfiguration();

    if (null == rmps.getCloseSequence()) {
        scheduleAcknowledgement(cfg.getAcknowledgementIntervalTime());
    }
    long inactivityTimeout = cfg.getInactivityTimeoutTime();
    scheduleSequenceTermination(inactivityTimeout);
}
 
Example 15
Source File: KerberosUtils.java    From cxf with Apache License 2.0 4 votes vote down vote up
public static KerberosClient getClient(Message message, String type) throws WSSecurityException {
    KerberosClient client = (KerberosClient)message
        .getContextualProperty(SecurityConstants.KERBEROS_CLIENT);
    if (client == null) {
        client = new KerberosClient();

        String jaasContext =
            (String)message.getContextualProperty(SecurityConstants.KERBEROS_JAAS_CONTEXT_NAME);
        String kerberosSpn =
            (String)message.getContextualProperty(SecurityConstants.KERBEROS_SPN);
        try {
            CallbackHandler callbackHandler =
                SecurityUtils.getCallbackHandler(
                    SecurityUtils.getSecurityPropertyValue(SecurityConstants.CALLBACK_HANDLER, message)
                );
            client.setCallbackHandler(callbackHandler);
        } catch (Exception ex) {
            throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, ex);
        }
        boolean useCredentialDelegation =
            MessageUtils.getContextualBoolean(message,
                                          SecurityConstants.KERBEROS_USE_CREDENTIAL_DELEGATION,
                                          false);

        boolean isInServiceNameForm =
            MessageUtils.getContextualBoolean(message,
                                          SecurityConstants.KERBEROS_IS_USERNAME_IN_SERVICENAME_FORM,
                                          false);

        boolean requestCredentialDelegation =
            MessageUtils.getContextualBoolean(message,
                                          SecurityConstants.KERBEROS_REQUEST_CREDENTIAL_DELEGATION,
                                          false);

        client.setContextName(jaasContext);
        client.setServiceName(kerberosSpn);
        client.setUseDelegatedCredential(useCredentialDelegation);
        client.setUsernameServiceNameForm(isInServiceNameForm);
        client.setRequestCredentialDelegation(requestCredentialDelegation);
    }
    return client;
}
 
Example 16
Source File: UsernameTokenInterceptor.java    From steady with Apache License 2.0 4 votes vote down vote up
protected WSUsernameTokenPrincipal getPrincipal(Element tokenElement, final SoapMessage message)
    throws WSSecurityException {
    
    boolean bspCompliant = isWsiBSPCompliant(message);
    boolean utWithCallbacks = 
        MessageUtils.getContextualBoolean(message, SecurityConstants.VALIDATE_TOKEN, true);
    if (utWithCallbacks) {
        UsernameTokenProcessor p = new UsernameTokenProcessor();
        WSDocInfo wsDocInfo = new WSDocInfo(tokenElement.getOwnerDocument());
        RequestData data = new RequestData() {
            public CallbackHandler getCallbackHandler() {
                return getCallback(message);
            }
            public Validator getValidator(QName qName) throws WSSecurityException {
                Object validator = 
                    message.getContextualProperty(SecurityConstants.USERNAME_TOKEN_VALIDATOR);
                if (validator == null) {
                    return super.getValidator(qName);
                }
                return (Validator)validator;
            }
        };
        
        // Configure replay caching
        ReplayCache nonceCache = 
            WSS4JUtils.getReplayCache(
                message, SecurityConstants.ENABLE_NONCE_CACHE, SecurityConstants.NONCE_CACHE_INSTANCE
            );
        data.setNonceReplayCache(nonceCache);
        
        WSSConfig config = WSSConfig.getNewInstance();
        config.setWsiBSPCompliant(bspCompliant);
        data.setWssConfig(config);
        List<WSSecurityEngineResult> results = 
            p.handleToken(tokenElement, data, wsDocInfo);
        return (WSUsernameTokenPrincipal)results.get(0).get(WSSecurityEngineResult.TAG_PRINCIPAL);
    } else {
        WSUsernameTokenPrincipal principal = parseTokenAndCreatePrincipal(tokenElement, bspCompliant);
        WSS4JTokenConverter.convertToken(message, principal);
        return principal;
    }
}
 
Example 17
Source File: JMSMessageUtils.java    From cxf with Apache License 2.0 4 votes vote down vote up
public static boolean isMtomEnabled(final org.apache.cxf.message.Message message) {
    return MessageUtils.getContextualBoolean(message, org.apache.cxf.message.Message.MTOM_ENABLED);
}
 
Example 18
Source File: AbstractWSS4JStaxInterceptor.java    From cxf with Apache License 2.0 4 votes vote down vote up
protected void translateProperties(SoapMessage msg, WSSSecurityProperties securityProperties) {
    String bspCompliant = (String)msg.getContextualProperty(SecurityConstants.IS_BSP_COMPLIANT);
    if (bspCompliant != null) {
        securityProperties.setDisableBSPEnforcement(!Boolean.valueOf(bspCompliant));
    }

    String futureTTL =
        (String)msg.getContextualProperty(SecurityConstants.TIMESTAMP_FUTURE_TTL);
    if (futureTTL != null) {
        securityProperties.setTimeStampFutureTTL(Integer.parseInt(futureTTL));
    }

    String ttl =
        (String)msg.getContextualProperty(SecurityConstants.TIMESTAMP_TTL);
    if (ttl != null) {
        securityProperties.setTimestampTTL(Integer.parseInt(ttl));
    }

    String utFutureTTL =
        (String)msg.getContextualProperty(SecurityConstants.USERNAMETOKEN_FUTURE_TTL);
    if (utFutureTTL != null) {
        securityProperties.setUtFutureTTL(Integer.parseInt(utFutureTTL));
    }

    String utTTL =
        (String)msg.getContextualProperty(SecurityConstants.USERNAMETOKEN_TTL);
    if (utTTL != null) {
        securityProperties.setUtTTL(Integer.parseInt(utTTL));
    }

    String certConstraints =
        (String)SecurityUtils.getSecurityPropertyValue(SecurityConstants.SUBJECT_CERT_CONSTRAINTS, msg);
    if (certConstraints != null && !"".equals(certConstraints)) {
        String certConstraintsSeparator =
            (String)SecurityUtils.getSecurityPropertyValue(SecurityConstants.CERT_CONSTRAINTS_SEPARATOR, msg);
        if (certConstraintsSeparator == null || certConstraintsSeparator.isEmpty()) {
            certConstraintsSeparator = ",";
        }
        securityProperties.setSubjectCertConstraints(
            convertCertConstraints(certConstraints, certConstraintsSeparator));
    }

    // Now set SAML SenderVouches + Holder Of Key requirements
    String validateSAMLSubjectConf =
        (String)SecurityUtils.getSecurityPropertyValue(SecurityConstants.VALIDATE_SAML_SUBJECT_CONFIRMATION,
                                                       msg);
    if (validateSAMLSubjectConf != null) {
        securityProperties.setValidateSamlSubjectConfirmation(Boolean.valueOf(validateSAMLSubjectConf));
    }

    String actor = (String)msg.getContextualProperty(SecurityConstants.ACTOR);
    if (actor != null) {
        securityProperties.setActor(actor);
    }

    boolean mustUnderstand =
        MessageUtils.getContextualBoolean(msg, SecurityConstants.MUST_UNDERSTAND, true);
    securityProperties.setMustUnderstand(mustUnderstand);

    boolean validateSchemas =
        MessageUtils.getContextualBoolean(msg, "schema-validation-enabled", false);
    securityProperties.setDisableSchemaValidation(!validateSchemas);

    securityProperties.setSoap12(WSSConstants.NS_SOAP12.equals(msg.getVersion().getNamespace()));
}
 
Example 19
Source File: StaxOutInterceptor.java    From cxf with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("resource")
public void handleMessage(Message message) {
    OutputStream os = message.getContent(OutputStream.class);
    XMLStreamWriter xwriter = message.getContent(XMLStreamWriter.class);
    Writer writer = null;
    if (os == null) {
        writer = message.getContent(Writer.class);
    }
    if ((os == null && writer == null) || xwriter != null) {
        return;
    }

    String encoding = getEncoding(message);

    try {
        XMLOutputFactory factory = getXMLOutputFactory(message);
        if (factory == null) {
            if (writer == null) {
                os = setupOutputStream(os);
                xwriter = StaxUtils.createXMLStreamWriter(os, encoding);
            } else {
                xwriter = StaxUtils.createXMLStreamWriter(writer);
            }
        } else {
            if (PropertyUtils.isTrue(message.getContextualProperty(Message.THREAD_SAFE_STAX_FACTORIES))) {
                if (writer == null) {
                    os = setupOutputStream(os);
                    xwriter = factory.createXMLStreamWriter(os, encoding);
                } else {
                    xwriter = factory.createXMLStreamWriter(writer);
                }
            } else {
                synchronized (factory) {
                    if (writer == null) {
                        os = setupOutputStream(os);
                        xwriter = factory.createXMLStreamWriter(os, encoding);
                    } else {
                        xwriter = factory.createXMLStreamWriter(writer);
                    }
                }
            }
        }
        if (MessageUtils.getContextualBoolean(message, FORCE_START_DOCUMENT, false)) {
            xwriter.writeStartDocument(encoding, "1.0");
            message.removeContent(OutputStream.class);
            message.put(OUTPUT_STREAM_HOLDER, os);
            message.removeContent(Writer.class);
            message.put(WRITER_HOLDER, writer);
        }
    } catch (XMLStreamException e) {
        throw new Fault(new org.apache.cxf.common.i18n.Message("STREAM_CREATE_EXC", BUNDLE), e);
    }
    message.setContent(XMLStreamWriter.class, xwriter);

    // Add a final interceptor to write end elements
    message.getInterceptorChain().add(ENDING);
}
 
Example 20
Source File: UsernameTokenInterceptor.java    From steady with Apache License 2.0 4 votes vote down vote up
protected WSUsernameTokenPrincipal getPrincipal(Element tokenElement, final SoapMessage message)
    throws WSSecurityException {
    
    boolean bspCompliant = isWsiBSPCompliant(message);
    boolean utWithCallbacks = 
        MessageUtils.getContextualBoolean(message, SecurityConstants.VALIDATE_TOKEN, true);
    if (utWithCallbacks) {
        UsernameTokenProcessor p = new UsernameTokenProcessor();
        WSDocInfo wsDocInfo = new WSDocInfo(tokenElement.getOwnerDocument());
        RequestData data = new RequestData() {
            public CallbackHandler getCallbackHandler() {
                return getCallback(message);
            }
            public Validator getValidator(QName qName) throws WSSecurityException {
                Object validator = 
                    message.getContextualProperty(SecurityConstants.USERNAME_TOKEN_VALIDATOR);
                if (validator == null) {
                    return super.getValidator(qName);
                }
                return (Validator)validator;
            }
        };
        
        // Configure replay caching
        ReplayCache nonceCache = 
            WSS4JUtils.getReplayCache(
                message, SecurityConstants.ENABLE_NONCE_CACHE, SecurityConstants.NONCE_CACHE_INSTANCE
            );
        data.setNonceReplayCache(nonceCache);
        
        WSSConfig config = WSSConfig.getNewInstance();
        config.setWsiBSPCompliant(bspCompliant);
        data.setWssConfig(config);
        List<WSSecurityEngineResult> results = 
            p.handleToken(tokenElement, data, wsDocInfo);
        return (WSUsernameTokenPrincipal)results.get(0).get(WSSecurityEngineResult.TAG_PRINCIPAL);
    } else {
        WSUsernameTokenPrincipal principal = parseTokenAndCreatePrincipal(tokenElement, bspCompliant);
        WSS4JTokenConverter.convertToken(message, principal);
        return principal;
    }
}