Java Code Examples for org.apache.cxf.binding.soap.SoapMessage#getContextualProperty()

The following examples show how to use org.apache.cxf.binding.soap.SoapMessage#getContextualProperty() . 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: SCTInInterceptor.java    From cxf with Apache License 2.0 6 votes vote down vote up
public void handleMessage(SoapMessage message) throws Fault {

        String s = (String)message.get(SoapBindingConstants.SOAP_ACTION);
        AddressingProperties inProps = (AddressingProperties)message
            .getContextualProperty(JAXWSAConstants.ADDRESSING_PROPERTIES_INBOUND);
        if (inProps != null && s == null) {
            //MS/WCF doesn't put a soap action out for this, must check the headers
            s = inProps.getAction().getValue();
        }

        if (s != null
            && s.contains("/RST/SCT")
            && (s.startsWith(STSUtils.WST_NS_05_02)
                || s.startsWith(STSUtils.WST_NS_05_12))) {
            message.put(org.apache.cxf.ws.addressing.MAPAggregator.ACTION_VERIFIED, Boolean.TRUE);
        }
    }
 
Example 2
Source File: WSS4JInInterceptor.java    From steady with Apache License 2.0 6 votes vote down vote up
/**
 * Do whatever is necessary to determine the action for the incoming message and 
 * do whatever other setup work is necessary.
 * 
 * @param msg
 * @param reqData
 */
protected void computeAction(SoapMessage msg, RequestData reqData) throws WSSecurityException {
    //
    // Try to get Crypto Provider from message context properties. 
    // It gives a possibility to use external Crypto Provider 
    //
    Crypto encCrypto = (Crypto)msg.getContextualProperty(SecurityConstants.ENCRYPT_CRYPTO);
    if (encCrypto != null) {
        reqData.setEncCrypto(encCrypto);
        reqData.setDecCrypto(encCrypto);
    }
    Crypto sigCrypto = (Crypto)msg.getContextualProperty(SecurityConstants.SIGNATURE_CRYPTO);
    if (sigCrypto != null) {
        reqData.setSigCrypto(sigCrypto);
    }
}
 
Example 3
Source File: PolicyBasedWSS4JInInterceptor.java    From cxf with Apache License 2.0 6 votes vote down vote up
/**
 * Set a WSS4J AlgorithmSuite object on the RequestData context, to restrict the
 * algorithms that are allowed for encryption, signature, etc.
 */
protected void setAlgorithmSuites(SoapMessage message, RequestData data) throws WSSecurityException {
    AlgorithmSuiteTranslater translater = new AlgorithmSuiteTranslater();
    translater.translateAlgorithmSuites(message.get(AssertionInfoMap.class), data);

    // Allow for setting non-standard signature algorithms
    boolean asymmAlgSet = false;
    String asymSignatureAlgorithm =
        (String)message.getContextualProperty(SecurityConstants.ASYMMETRIC_SIGNATURE_ALGORITHM);
    if (asymSignatureAlgorithm != null && data.getAlgorithmSuite() != null) {
        data.getAlgorithmSuite().getSignatureMethods().clear();
        data.getAlgorithmSuite().getSignatureMethods().add(asymSignatureAlgorithm);
        asymmAlgSet = true;
    }

    String symSignatureAlgorithm =
        (String)message.getContextualProperty(SecurityConstants.SYMMETRIC_SIGNATURE_ALGORITHM);
    if (symSignatureAlgorithm != null && data.getAlgorithmSuite() != null) {
        if (!asymmAlgSet) {
            data.getAlgorithmSuite().getSignatureMethods().clear();
        }
        data.getAlgorithmSuite().getSignatureMethods().add(symSignatureAlgorithm);
    }
}
 
Example 4
Source File: WSS4JInInterceptor.java    From steady with Apache License 2.0 6 votes vote down vote up
/**
 * Do whatever is necessary to determine the action for the incoming message and 
 * do whatever other setup work is necessary.
 * 
 * @param msg
 * @param reqData
 */
protected void computeAction(SoapMessage msg, RequestData reqData) throws WSSecurityException {
    //
    // Try to get Crypto Provider from message context properties. 
    // It gives a possibility to use external Crypto Provider 
    //
    Crypto encCrypto = (Crypto)msg.getContextualProperty(SecurityConstants.ENCRYPT_CRYPTO);
    if (encCrypto != null) {
        reqData.setEncCrypto(encCrypto);
        reqData.setDecCrypto(encCrypto);
    }
    Crypto sigCrypto = (Crypto)msg.getContextualProperty(SecurityConstants.SIGNATURE_CRYPTO);
    if (sigCrypto != null) {
        reqData.setSigCrypto(sigCrypto);
    }
}
 
Example 5
Source File: AbstractTokenInterceptor.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected TokenStore getTokenStore(SoapMessage message) {
    EndpointInfo info = message.getExchange().getEndpoint().getEndpointInfo();
    synchronized (info) {
        TokenStore tokenStore =
            (TokenStore)message.getContextualProperty(SecurityConstants.TOKEN_STORE_CACHE_INSTANCE);
        if (tokenStore == null) {
            tokenStore = (TokenStore)info.getProperty(SecurityConstants.TOKEN_STORE_CACHE_INSTANCE);
        }
        return tokenStore;
    }
}
 
Example 6
Source File: AuthenticationInInterceptor.java    From yes-cart with Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public void handleMessage(SoapMessage message) throws Fault {
    try {
        super.handleMessage(message);
        List<WSHandlerResult> result = (List<WSHandlerResult>) message.getContextualProperty(WSHandlerConstants.RECV_RESULTS);
        if (result != null && !result.isEmpty()) {
            for (WSHandlerResult res : result) {
                // loop through security engine results
                for (WSSecurityEngineResult securityResult :  res.getResults()) {
                    int action = (Integer) securityResult.get(WSSecurityEngineResult.TAG_ACTION);
                    // determine if the action was a username token
                    if ((action & WSConstants.UT) > 0) {
                        // get the principal object
                        final UsernameTokenPrincipal principal = (UsernameTokenPrincipal) securityResult.get(WSSecurityEngineResult.TAG_PRINCIPAL);
                        Authentication authentication = new UsernamePasswordAuthenticationToken(
                                principal.getName(),
                                principal.getPassword()==null ? "" : principal.getPassword()
                        );
                        LOG.debug("Receiving WS request from user {}", principal.getName());
                        authentication = authenticationManager.authenticate(authentication);
                        SecurityContextHolder.getContext().setAuthentication(authentication);
                    }
                }
            }
        }
    } catch (RuntimeException ex) {
        LOG.error("Failed to authenticate WS request: " + ex.getMessage(), ex);
        throw ex;
    }
}
 
Example 7
Source File: PolicyBasedWSS4JOutInterceptor.java    From steady with Apache License 2.0 5 votes vote down vote up
private void translateProperties(SoapMessage msg, WSSConfig config) {
    String bspCompliant = (String)msg.getContextualProperty(SecurityConstants.IS_BSP_COMPLIANT);
    if ("1".equals(bspCompliant) || "true".equals(bspCompliant)) {
        config.setWsiBSPCompliant(true);
    } else if ("0".equals(bspCompliant) || "false".equals(bspCompliant)) {
        config.setWsiBSPCompliant(false);
    }
}
 
Example 8
Source File: SoapPreProtocolOutInterceptor.java    From cxf with Apache License 2.0 5 votes vote down vote up
/**
 * Ensure the SOAP header is set for this message.
 *
 * @param message the current message
 */
private void ensureMimeHeaders(SoapMessage message) {
    if (message.get(MIME_HEADERS) == null) {
        message.put(MIME_HEADERS, new HashMap<String, List<String>>());
    }
    String cte = (String)message.getContextualProperty(Message.CONTENT_TRANSFER_ENCODING);
    if (cte != null) {
        //root part MUST be binary
        message.put(Message.CONTENT_TRANSFER_ENCODING, "binary");
        message.put("soap.attachement.content.transfer.encoding", cte);
    }
}
 
Example 9
Source File: PolicyBasedWSS4JOutInterceptor.java    From steady with Apache License 2.0 5 votes vote down vote up
private void translateProperties(SoapMessage msg, WSSConfig config) {
    String bspCompliant = (String)msg.getContextualProperty(SecurityConstants.IS_BSP_COMPLIANT);
    if ("1".equals(bspCompliant) || "true".equals(bspCompliant)) {
        config.setWsiBSPCompliant(true);
    } else if ("0".equals(bspCompliant) || "false".equals(bspCompliant)) {
        config.setWsiBSPCompliant(false);
    }
}
 
Example 10
Source File: PolicyBasedWSS4JOutInterceptor.java    From steady with Apache License 2.0 5 votes vote down vote up
private void translateProperties(SoapMessage msg, WSSConfig config) {
    String bspCompliant = (String)msg.getContextualProperty(SecurityConstants.IS_BSP_COMPLIANT);
    if ("1".equals(bspCompliant) || "true".equals(bspCompliant)) {
        config.setWsiBSPCompliant(true);
    } else if ("0".equals(bspCompliant) || "false".equals(bspCompliant)) {
        config.setWsiBSPCompliant(false);
    }
}
 
Example 11
Source File: PolicyBasedWSS4JStaxInInterceptor.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
protected void configureProperties(
    SoapMessage msg, WSSSecurityProperties securityProperties
) throws XMLSecurityException {
    AssertionInfoMap aim = msg.get(AssertionInfoMap.class);
    checkAsymmetricBinding(aim, msg, securityProperties);
    checkSymmetricBinding(aim, msg, securityProperties);
    checkTransportBinding(aim, msg, securityProperties);

    // Allow for setting non-standard signature algorithms
    String asymSignatureAlgorithm =
        (String)msg.getContextualProperty(SecurityConstants.ASYMMETRIC_SIGNATURE_ALGORITHM);
    String symSignatureAlgorithm =
        (String)msg.getContextualProperty(SecurityConstants.SYMMETRIC_SIGNATURE_ALGORITHM);
    if (asymSignatureAlgorithm != null || symSignatureAlgorithm != null) {
        Collection<AssertionInfo> algorithmSuites =
            aim.get(SP12Constants.ALGORITHM_SUITE);
        if (algorithmSuites != null && !algorithmSuites.isEmpty()) {
            for (AssertionInfo algorithmSuite : algorithmSuites) {
                AlgorithmSuite algSuite = (AlgorithmSuite)algorithmSuite.getAssertion();
                if (asymSignatureAlgorithm != null) {
                    algSuite.getAlgorithmSuiteType().setAsymmetricSignature(asymSignatureAlgorithm);
                }
                if (symSignatureAlgorithm != null) {
                    algSuite.getAlgorithmSuiteType().setSymmetricSignature(symSignatureAlgorithm);
                }
            }
        }
    }

    super.configureProperties(msg, securityProperties);
}
 
Example 12
Source File: SpnegoContextTokenInInterceptor.java    From steady with Apache License 2.0 4 votes vote down vote up
public void handleMessage(SoapMessage message) throws Fault {
    AssertionInfoMap aim = message.get(AssertionInfoMap.class);
    // extract Assertion information
    if (aim != null) {
        Collection<AssertionInfo> ais = aim.get(SP12Constants.SPNEGO_CONTEXT_TOKEN);
        if (ais == null || ais.isEmpty()) {
            return;
        }
        if (isRequestor(message)) {
            //client side should be checked on the way out
            for (AssertionInfo ai : ais) {
                ai.setAsserted(true);
            }      
            return;
        }
        String s = (String)message.get(SoapBindingConstants.SOAP_ACTION);
        AddressingProperties inProps = (AddressingProperties)message
            .getContextualProperty(JAXWSAConstants.SERVER_ADDRESSING_PROPERTIES_INBOUND);
        if (inProps != null && s == null) {
            //MS/WCF doesn't put a soap action out for this, must check the headers
            s = inProps.getAction().getValue();
        }

        if (s != null 
            && s.contains("/RST/Issue")
            && (s.startsWith(STSUtils.WST_NS_05_02)
                || s.startsWith(STSUtils.WST_NS_05_12))) {

            Policy p = new Policy();
            ExactlyOne ea = new ExactlyOne();
            p.addPolicyComponent(ea);
            All all = new All();
            Assertion ass = NegotiationUtils.getAddressingPolicy(aim, false);
            all.addPolicyComponent(ass);
            ea.addPolicyComponent(all);
            
            //setup endpoint and forward to it.
            unmapSecurityProps(message);
            String ns = STSUtils.WST_NS_05_12;
            if (s.startsWith(STSUtils.WST_NS_05_02)) {
                ns = STSUtils.WST_NS_05_02;
            }
            NegotiationUtils.recalcEffectivePolicy(message, ns, p, new SpnegoSTSInvoker(), false);
        } else {
            message.getInterceptorChain().add(SpnegoContextTokenFinderInterceptor.INSTANCE);
        }
    }
}
 
Example 13
Source File: StaxSecurityContextInInterceptor.java    From cxf with Apache License 2.0 4 votes vote down vote up
private void doResults(SoapMessage msg, List<SecurityEvent> incomingSecurityEventList) throws WSSecurityException {

        // Now go through the results in a certain order to set up a security context. Highest priority is first.

        List<Event> desiredSecurityEvents = new ArrayList<>();
        desiredSecurityEvents.add(WSSecurityEventConstants.SAML_TOKEN);
        desiredSecurityEvents.add(WSSecurityEventConstants.USERNAME_TOKEN);
        desiredSecurityEvents.add(WSSecurityEventConstants.KERBEROS_TOKEN);
        desiredSecurityEvents.add(WSSecurityEventConstants.X509Token);
        desiredSecurityEvents.add(WSSecurityEventConstants.KeyValueToken);

        for (Event desiredEvent : desiredSecurityEvents) {
            SubjectAndPrincipalSecurityToken token = null;
            try {
                token = getSubjectPrincipalToken(incomingSecurityEventList, desiredEvent, msg);
            } catch (XMLSecurityException ex) {
                // proceed
            }
            if (token != null) {
                Principal p = token.getPrincipal();
                Subject subject = token.getSubject();

                if (subject != null) {
                    String roleClassifier =
                        (String)msg.getContextualProperty(SecurityConstants.SUBJECT_ROLE_CLASSIFIER);
                    if (roleClassifier != null && !"".equals(roleClassifier)) {
                        String roleClassifierType =
                            (String)msg.getContextualProperty(SecurityConstants.SUBJECT_ROLE_CLASSIFIER_TYPE);
                        if (roleClassifierType == null || "".equals(roleClassifierType)) {
                            roleClassifierType = "prefix";
                        }
                        msg.put(
                            SecurityContext.class,
                            new RolePrefixSecurityContextImpl(subject, roleClassifier, roleClassifierType)
                        );
                    } else {
                        msg.put(SecurityContext.class, new DefaultSecurityContext(subject));
                    }
                    break;
                } else if (p != null) {

                    Object receivedAssertion = null;

                    if (desiredEvent == WSSecurityEventConstants.SAML_TOKEN) {
                        String roleAttributeName = (String)SecurityUtils.getSecurityPropertyValue(
                                SecurityConstants.SAML_ROLE_ATTRIBUTENAME, msg);
                        if (roleAttributeName == null || roleAttributeName.length() == 0) {
                            roleAttributeName = SAML_ROLE_ATTRIBUTENAME_DEFAULT;
                        }

                        receivedAssertion = ((SAMLTokenPrincipal)token.getPrincipal()).getToken();
                        if (receivedAssertion != null) {
                            ClaimCollection claims =
                                SAMLUtils.getClaims((SamlAssertionWrapper)receivedAssertion);
                            Set<Principal> roles =
                                SAMLUtils.parseRolesFromClaims(claims, roleAttributeName, null);

                            SAMLSecurityContext context =
                                new SAMLSecurityContext(p, roles, claims);

                            msg.put(SecurityContext.class, context);
                        }
                    } else {
                        msg.put(SecurityContext.class, createSecurityContext(p));
                    }
                    break;
                }
            }
        }
    }
 
Example 14
Source File: PolicyBasedWSS4JInInterceptor.java    From steady with Apache License 2.0 4 votes vote down vote up
private String checkAsymmetricBinding(
    AssertionInfoMap aim, String action, SoapMessage message
) throws WSSecurityException {
    Collection<AssertionInfo> ais = aim.get(SP12Constants.ASYMMETRIC_BINDING);
    if (ais == null || ais.isEmpty()) {
        return action;
    }
    
    action = addToAction(action, "Signature", true);
    action = addToAction(action, "Encrypt", true);
    Object s = message.getContextualProperty(SecurityConstants.SIGNATURE_CRYPTO);
    if (s == null) {
        s = message.getContextualProperty(SecurityConstants.SIGNATURE_PROPERTIES);
    }
    Object e = message.getContextualProperty(SecurityConstants.ENCRYPT_CRYPTO);
    if (e == null) {
        e = message.getContextualProperty(SecurityConstants.ENCRYPT_PROPERTIES);
    }
    
    Crypto encrCrypto = getEncryptionCrypto(e, message);
    Crypto signCrypto = null;
    if (e != null && e.equals(s)) {
        signCrypto = encrCrypto;
    } else {
        signCrypto = getSignatureCrypto(s, message);
    }
    
    if (signCrypto != null) {
        message.put(WSHandlerConstants.DEC_PROP_REF_ID, "RefId-" + signCrypto.hashCode());
        message.put("RefId-" + signCrypto.hashCode(), signCrypto);
    }
    
    if (encrCrypto != null) {
        message.put(WSHandlerConstants.SIG_PROP_REF_ID, "RefId-" + encrCrypto.hashCode());
        message.put("RefId-" + encrCrypto.hashCode(), (Crypto)encrCrypto);
    } else if (signCrypto != null) {
        message.put(WSHandlerConstants.SIG_PROP_REF_ID, "RefId-" + signCrypto.hashCode());
        message.put("RefId-" + signCrypto.hashCode(), (Crypto)signCrypto);
    }
 
    return action;
}
 
Example 15
Source File: WSS4JInInterceptor.java    From steady with Apache License 2.0 4 votes vote down vote up
protected void doResults(
    SoapMessage msg, 
    String actor,
    Element soapHeader,
    Element soapBody,
    List<WSSecurityEngineResult> wsResult, 
    boolean utWithCallbacks
) throws SOAPException, XMLStreamException, WSSecurityException {
    /*
     * All ok up to this point. Now construct and setup the security result
     * structure. The service may fetch this and check it.
     */
    List<WSHandlerResult> results = CastUtils.cast((List<?>)msg.get(WSHandlerConstants.RECV_RESULTS));
    if (results == null) {
        results = new ArrayList<WSHandlerResult>();
        msg.put(WSHandlerConstants.RECV_RESULTS, results);
    }
    WSHandlerResult rResult = new WSHandlerResult(actor, wsResult);
    results.add(0, rResult);

    for (WSSecurityEngineResult o : wsResult) {
        final Principal p = (Principal)o.get(WSSecurityEngineResult.TAG_PRINCIPAL);
        if (p != null && isSecurityContextPrincipal(p, wsResult)) {
            msg.put(PRINCIPAL_RESULT, p);
            if (!utWithCallbacks) {
                WSS4JTokenConverter.convertToken(msg, p);
            }
            Object receivedAssertion = null;
            
            List<String> roles = null;
            if (o.get(WSSecurityEngineResult.TAG_SAML_ASSERTION) != null) {
                String roleAttributeName = (String)msg.getContextualProperty(
                        SecurityConstants.SAML_ROLE_ATTRIBUTENAME);
                if (roleAttributeName == null || roleAttributeName.length() == 0) {
                    roleAttributeName = SAML_ROLE_ATTRIBUTENAME_DEFAULT;
                }
                receivedAssertion = o.get(WSSecurityEngineResult.TAG_SAML_ASSERTION);
                roles = SAMLUtils.parseRolesInAssertion(receivedAssertion, roleAttributeName);
                SAMLSecurityContext context = createSecurityContext(p, roles);
                context.setIssuer(SAMLUtils.getIssuer(receivedAssertion));
                context.setAssertionElement(SAMLUtils.getAssertionElement(receivedAssertion));
                msg.put(SecurityContext.class, context);
            } else {
                msg.put(SecurityContext.class, createSecurityContext(p));
            }
        }
    }
}
 
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: PolicyBasedWSS4JInInterceptor.java    From steady with Apache License 2.0 4 votes vote down vote up
private String checkTransportBinding(
    AssertionInfoMap aim, String action, SoapMessage message
) throws WSSecurityException {
    Collection<AssertionInfo> ais = aim.get(SP12Constants.TRANSPORT_BINDING);
    if (ais == null || ais.isEmpty()) {
        return action;
    }
    
    action = addToAction(action, "Signature", true);
    action = addToAction(action, "Encrypt", true);
    Object s = message.getContextualProperty(SecurityConstants.SIGNATURE_CRYPTO);
    if (s == null) {
        s = message.getContextualProperty(SecurityConstants.SIGNATURE_PROPERTIES);
    }
    Object e = message.getContextualProperty(SecurityConstants.ENCRYPT_CRYPTO);
    if (e == null) {
        e = message.getContextualProperty(SecurityConstants.ENCRYPT_PROPERTIES);
    }
    
    Crypto encrCrypto = getEncryptionCrypto(e, message);
    Crypto signCrypto = null;
    if (e != null && e.equals(s)) {
        signCrypto = encrCrypto;
    } else {
        signCrypto = getSignatureCrypto(s, message);
    }
    
    if (signCrypto != null) {
        message.put(WSHandlerConstants.DEC_PROP_REF_ID, "RefId-" + signCrypto.hashCode());
        message.put("RefId-" + signCrypto.hashCode(), signCrypto);
    }
    
    if (encrCrypto != null) {
        message.put(WSHandlerConstants.SIG_PROP_REF_ID, "RefId-" + encrCrypto.hashCode());
        message.put("RefId-" + encrCrypto.hashCode(), (Crypto)encrCrypto);
    } else if (signCrypto != null) {
        message.put(WSHandlerConstants.SIG_PROP_REF_ID, "RefId-" + signCrypto.hashCode());
        message.put("RefId-" + signCrypto.hashCode(), (Crypto)signCrypto);
    }

    return action;
}
 
Example 18
Source File: UsernameTokenInterceptor.java    From cxf with Apache License 2.0 4 votes vote down vote up
private boolean allowNamespaceQualifiedPWDTypes(final SoapMessage message) {
    String allow = (String)message
        .getContextualProperty(ConfigurationConstants.ALLOW_NAMESPACE_QUALIFIED_PASSWORD_TYPES);
    return "true".equals(allow) || "1".equals(allow);
}
 
Example 19
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 20
Source File: PolicyBasedWSS4JInInterceptor.java    From steady with Apache License 2.0 4 votes vote down vote up
private String checkAsymmetricBinding(
    AssertionInfoMap aim, String action, SoapMessage message
) throws WSSecurityException {
    Collection<AssertionInfo> ais = aim.get(SP12Constants.ASYMMETRIC_BINDING);
    if (ais == null || ais.isEmpty()) {
        return action;
    }
    
    action = addToAction(action, "Signature", true);
    action = addToAction(action, "Encrypt", true);
    Object s = message.getContextualProperty(SecurityConstants.SIGNATURE_CRYPTO);
    if (s == null) {
        s = message.getContextualProperty(SecurityConstants.SIGNATURE_PROPERTIES);
    }
    Object e = message.getContextualProperty(SecurityConstants.ENCRYPT_CRYPTO);
    if (e == null) {
        e = message.getContextualProperty(SecurityConstants.ENCRYPT_PROPERTIES);
    }
    
    Crypto encrCrypto = getEncryptionCrypto(e, message);
    Crypto signCrypto = null;
    if (e != null && e.equals(s)) {
        signCrypto = encrCrypto;
    } else {
        signCrypto = getSignatureCrypto(s, message);
    }
    
    if (signCrypto != null) {
        message.put(WSHandlerConstants.DEC_PROP_REF_ID, "RefId-" + signCrypto.hashCode());
        message.put("RefId-" + signCrypto.hashCode(), signCrypto);
    }
    
    if (encrCrypto != null) {
        message.put(WSHandlerConstants.SIG_PROP_REF_ID, "RefId-" + encrCrypto.hashCode());
        message.put("RefId-" + encrCrypto.hashCode(), (Crypto)encrCrypto);
    } else if (signCrypto != null) {
        message.put(WSHandlerConstants.SIG_PROP_REF_ID, "RefId-" + signCrypto.hashCode());
        message.put("RefId-" + signCrypto.hashCode(), (Crypto)signCrypto);
    }
 
    return action;
}