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

The following examples show how to use org.apache.cxf.message.message#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: STSTokenValidator.java    From steady with Apache License 2.0 6 votes vote down vote up
static final TokenStore getTokenStore(Message message) {
    EndpointInfo info = message.getExchange().get(Endpoint.class).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);
        }
        if (tokenStore == null) {
            TokenStoreFactory tokenStoreFactory = TokenStoreFactory.newInstance();
            String cacheKey = SecurityConstants.TOKEN_STORE_CACHE_INSTANCE;
            if (info.getName() != null) {
                cacheKey += "-" + info.getName().toString().hashCode();
            }
            tokenStore = tokenStoreFactory.newTokenStore(cacheKey, message);
            info.setProperty(SecurityConstants.TOKEN_STORE_CACHE_INSTANCE, tokenStore);
        }
        return tokenStore;
    }
}
 
Example 2
Source File: KerberosTokenInterceptorProvider.java    From steady with Apache License 2.0 6 votes vote down vote up
static final TokenStore getTokenStore(Message message) {
    EndpointInfo info = message.getExchange().get(Endpoint.class).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);
        }
        if (tokenStore == null) {
            TokenStoreFactory tokenStoreFactory = TokenStoreFactory.newInstance();
            String cacheKey = SecurityConstants.TOKEN_STORE_CACHE_INSTANCE;
            if (info.getName() != null) {
                cacheKey += "-" + info.getName().toString().hashCode();
            }
            tokenStore = tokenStoreFactory.newTokenStore(cacheKey, message);
            info.setProperty(SecurityConstants.TOKEN_STORE_CACHE_INSTANCE, tokenStore);
        }
        return tokenStore;
    }
}
 
Example 3
Source File: WSSUsernameCallbackHandler.java    From steady with Apache License 2.0 6 votes vote down vote up
public void handle(Callback[] callbacks)
    throws IOException, UnsupportedCallbackException {
    for (int i = 0; i < callbacks.length; i++) {
        if (callbacks[i] instanceof DelegationCallback) {
            DelegationCallback callback = (DelegationCallback) callbacks[i];
            Message message = callback.getCurrentMessage();
            
            String username = 
                (String)message.getContextualProperty(SecurityConstants.USERNAME);
            if (username != null) {
                Node contentNode = message.getContent(Node.class);
                Document doc = null;
                if (contentNode != null) {
                    doc = contentNode.getOwnerDocument();
                } else {
                    doc = DOMUtils.createDocument();
                }
                UsernameToken usernameToken = createWSSEUsernameToken(username, doc);
                callback.setToken(usernameToken.getElement());
            }
        } else {
            throw new UnsupportedCallbackException(callbacks[i], "Unrecognized Callback");
        }
    }
}
 
Example 4
Source File: STSTokenValidator.java    From steady with Apache License 2.0 6 votes vote down vote up
static final TokenStore getTokenStore(Message message) {
    EndpointInfo info = message.getExchange().get(Endpoint.class).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);
        }
        if (tokenStore == null) {
            TokenStoreFactory tokenStoreFactory = TokenStoreFactory.newInstance();
            String cacheKey = SecurityConstants.TOKEN_STORE_CACHE_INSTANCE;
            if (info.getName() != null) {
                cacheKey += "-" + info.getName().toString().hashCode();
            }
            tokenStore = tokenStoreFactory.newTokenStore(cacheKey, message);
            info.setProperty(SecurityConstants.TOKEN_STORE_CACHE_INSTANCE, tokenStore);
        }
        return tokenStore;
    }
}
 
Example 5
Source File: NetworkAddressValidatingInterceptor.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
@Override
public void handleMessage(Message message) throws Fault {
    // JAX-RS
    Method method = getTargetMethod(message);
    HttpServletRequest request = (HttpServletRequest) message.getContextualProperty("HTTP.REQUEST");
    if (!hasAnnotation(method) && (request == null || !remoteHostMatcher.isAllowed(request))) {
        // This is to prevent a full stack trace getting logged for a denied request
        message.put(FaultListener.class.getName(), new NoOpFaultListener());
        Fault fault = new Fault(
                new org.apache.cxf.common.i18n.Message("Not permitted", (ResourceBundle) null),
                Fault.FAULT_CODE_CLIENT
        );
        fault.setStatusCode(HttpServletResponse.SC_FORBIDDEN);
        throw fault;
    }
}
 
Example 6
Source File: WSSUsernameCallbackHandler.java    From steady with Apache License 2.0 6 votes vote down vote up
public void handle(Callback[] callbacks)
    throws IOException, UnsupportedCallbackException {
    for (int i = 0; i < callbacks.length; i++) {
        if (callbacks[i] instanceof DelegationCallback) {
            DelegationCallback callback = (DelegationCallback) callbacks[i];
            Message message = callback.getCurrentMessage();
            
            String username = 
                (String)message.getContextualProperty(SecurityConstants.USERNAME);
            if (username != null) {
                Node contentNode = message.getContent(Node.class);
                Document doc = null;
                if (contentNode != null) {
                    doc = contentNode.getOwnerDocument();
                } else {
                    doc = DOMUtils.createDocument();
                }
                UsernameToken usernameToken = createWSSEUsernameToken(username, doc);
                callback.setToken(usernameToken.getElement());
            }
        } else {
            throw new UnsupportedCallbackException(callbacks[i], "Unrecognized Callback");
        }
    }
}
 
Example 7
Source File: IssuedTokenInterceptorProvider.java    From steady with Apache License 2.0 6 votes vote down vote up
static final TokenStore createTokenStore(Message message) {
    EndpointInfo info = message.getExchange().get(Endpoint.class).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);
        }
        if (tokenStore == null) {
            TokenStoreFactory tokenStoreFactory = TokenStoreFactory.newInstance();
            String cacheKey = SecurityConstants.TOKEN_STORE_CACHE_INSTANCE;
            if (info.getName() != null) {
                cacheKey += "-" + info.getName().toString().hashCode();
            }
            tokenStore = tokenStoreFactory.newTokenStore(cacheKey, message);
            info.setProperty(SecurityConstants.TOKEN_STORE_CACHE_INSTANCE, tokenStore);
        }
        return tokenStore;
    }
}
 
Example 8
Source File: SpnegoContextTokenInInterceptor.java    From steady with Apache License 2.0 5 votes vote down vote up
private void unmapSecurityProps(Message message) {
    Exchange ex = message.getExchange();
    for (String s : SecurityConstants.ALL_PROPERTIES) {
        Object v = message.getContextualProperty(s);
        if (v != null) {
            ex.put(s, v);
        }
    }
}
 
Example 9
Source File: PropertyUtils.java    From cxf with Apache License 2.0 5 votes vote down vote up
public static Long getLong(Message message, String key) {
    Object o = message.getContextualProperty(key);
    if (o instanceof Long) {
        return (Long)o;
    } else if (o instanceof Number) {
        return ((Number)o).longValue();
    } else if (o instanceof String) {
        return Long.valueOf(o.toString());
    }
    return null;
}
 
Example 10
Source File: SpnegoContextTokenInInterceptor.java    From cxf with Apache License 2.0 5 votes vote down vote up
private SpnegoTokenContext handleBinaryExchange(
    Element binaryExchange,
    Message message,
    String namespace
) throws Exception {
    if (binaryExchange == null) {
        throw new Exception("No BinaryExchange element received");
    }
    String encoding = binaryExchange.getAttributeNS(null, "EncodingType");
    if (!WSS4JConstants.BASE64_ENCODING.equals(encoding)) {
        throw new Exception("Unknown encoding type: " + encoding);
    }

    String valueType = binaryExchange.getAttributeNS(null, "ValueType");
    if (!(namespace + "/spnego").equals(valueType)) {
        throw new Exception("Unknown value type: " + valueType);
    }

    String content = DOMUtils.getContent(binaryExchange);
    byte[] decodedContent = XMLUtils.decode(content);

    String jaasContext =
        (String)message.getContextualProperty(SecurityConstants.KERBEROS_JAAS_CONTEXT_NAME);
    String kerberosSpn =
        (String)message.getContextualProperty(SecurityConstants.KERBEROS_SPN);
    CallbackHandler callbackHandler =
        SecurityUtils.getCallbackHandler(
            SecurityUtils.getSecurityPropertyValue(SecurityConstants.CALLBACK_HANDLER, message)
        );

    SpnegoTokenContext spnegoToken = new SpnegoTokenContext();
    spnegoToken.validateServiceTicket(
        jaasContext, callbackHandler, kerberosSpn, decodedContent
    );
    return spnegoToken;
}
 
Example 11
Source File: KeyManagementUtils.java    From cxf with Apache License 2.0 5 votes vote down vote up
public static String getKeyId(Message m, Properties props,
                              String preferredPropertyName,
                              KeyOperation keyOper) {
    String kid = null;
    String altPropertyName = null;
    if (keyOper != null && m != null) {
        if (keyOper == KeyOperation.ENCRYPT || keyOper == KeyOperation.DECRYPT) {
            altPropertyName = preferredPropertyName + ".jwe";
        } else if (keyOper == KeyOperation.SIGN || keyOper == KeyOperation.VERIFY) {
            altPropertyName = preferredPropertyName + ".jws";
        }
        String direction = m.getExchange().getOutMessage() == m ? ".out" : ".in";
        kid = (String)MessageUtils.getContextualProperty(m, preferredPropertyName, altPropertyName + direction);
        // Check whether the direction is not set for the altPropertyName
        if (kid == null && altPropertyName != null) {
            kid = (String)m.getContextualProperty(altPropertyName);
        }
    }

    if (kid == null) {
        kid = props.getProperty(preferredPropertyName);
    }
    if (kid == null && altPropertyName != null) {
        kid = props.getProperty(altPropertyName);
    }
    return kid;
}
 
Example 12
Source File: AbstractOutDatabindingInterceptor.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected boolean shouldBuffer(Message message) {
    Object en = message.getContextualProperty(OUT_BUFFERING);
    boolean allowBuffer = true;
    boolean buffer = false;
    if (en != null) {
        buffer = Boolean.TRUE.equals(en) || "true".equals(en);
        allowBuffer = !(Boolean.FALSE.equals(en) || "false".equals(en));
    }
    // need to cache the events in case validation fails or buffering is enabled
    return buffer || (allowBuffer && shouldValidate(message) && !isRequestor(message));
}
 
Example 13
Source File: TransformOutInterceptor.java    From cxf with Apache License 2.0 5 votes vote down vote up
public void handleMessage(Message message) {
    if (!isHttpVerbSupported(message)) {
        return;
    }

    if (contextPropertyName != null
        && !MessageUtils.getContextualBoolean(message.getExchange().getInMessage(),
                                           contextPropertyName,
                                           false)) {
        return;
    }

    if (skipOnFault && null != message.getContent(Exception.class)
        || MessageUtils.getContextualBoolean(message, TRANSFORM_SKIP, false)) {
        return;
    }

    XMLStreamWriter writer = message.getContent(XMLStreamWriter.class);
    OutputStream out = message.getContent(OutputStream.class);

    XMLStreamWriter transformWriter = createTransformWriterIfNeeded(writer, out);
    if (transformWriter != null) {
        message.setContent(XMLStreamWriter.class, transformWriter);
        if (message.getContextualProperty(DISABLE_OUTPUTSTREAM_OPTIMIZATION) == null) {
            message.put(DISABLE_OUTPUTSTREAM_OPTIMIZATION, Boolean.TRUE);
        }
        if (MessageUtils.isRequestor(message)) {
            message.removeContent(OutputStream.class);
            message.put(OUTPUT_STREAM_HOLDER, out);
            message.getInterceptorChain().add(ENDING);
        }
    }
}
 
Example 14
Source File: SecureConversationInInterceptor.java    From steady with Apache License 2.0 5 votes vote down vote up
private void unmapSecurityProps(Message message) {
    Exchange ex = message.getExchange();
    for (String s : SecurityConstants.ALL_PROPERTIES) {
        Object v = message.getContextualProperty(s + ".sct");
        if (v != null) {
            ex.put(s, v);
        }
    }
}
 
Example 15
Source File: IssuedTokenInterceptorProvider.java    From steady with Apache License 2.0 5 votes vote down vote up
static final TokenStore getTokenStore(Message message) {
    TokenStore tokenStore = (TokenStore)message.getContextualProperty(TokenStore.class.getName());
    if (tokenStore == null) {
        tokenStore = createTokenStore(message);
    }
    return tokenStore;
}
 
Example 16
Source File: SpnegoContextTokenInInterceptor.java    From steady with Apache License 2.0 5 votes vote down vote up
private SpnegoTokenContext handleBinaryExchange(
    Element binaryExchange,
    Message message,
    String namespace
) throws Exception {
    if (binaryExchange == null) {
        throw new Exception("No BinaryExchange element received");
    }
    String encoding = binaryExchange.getAttributeNS(null, "EncodingType");
    if (!BinarySecurity.BASE64_ENCODING.equals(encoding)) {
        throw new Exception("Unknown encoding type: " + encoding);
    }

    String valueType = binaryExchange.getAttributeNS(null, "ValueType");
    if (!(namespace + "/spnego").equals(valueType)) {
        throw new Exception("Unknown value type: " + valueType);
    }

    String content = DOMUtils.getContent(binaryExchange);
    byte[] decodedContent = Base64.decode(content);
    
    String jaasContext = 
        (String)message.getContextualProperty(SecurityConstants.KERBEROS_JAAS_CONTEXT_NAME);
    String kerberosSpn = 
        (String)message.getContextualProperty(SecurityConstants.KERBEROS_SPN);
    CallbackHandler callbackHandler = 
        NegotiationUtils.getCallbackHandler(
            message.getContextualProperty(SecurityConstants.CALLBACK_HANDLER), this.getClass()
        );

    SpnegoTokenContext spnegoToken = new SpnegoTokenContext();
    spnegoToken.validateServiceTicket(
        jaasContext, callbackHandler, kerberosSpn, decodedContent
    );
    return spnegoToken;
}
 
Example 17
Source File: JAXRSUtils.java    From cxf with Apache License 2.0 4 votes vote down vote up
private static Object processRequestBodyParameter(Class<?> parameterClass,
                                                  Type parameterType,
                                                  Annotation[] parameterAnns,
                                                  Message message,
                                                  OperationResourceInfo ori)
    throws IOException, WebApplicationException {

    if (parameterClass == AsyncResponse.class) {
        return new AsyncResponseImpl(message);
    }

    String contentType = (String)message.get(Message.CONTENT_TYPE);

    if (contentType == null) {
        String defaultCt = (String)message.getContextualProperty(DEFAULT_CONTENT_TYPE);
        contentType = defaultCt == null ? MediaType.APPLICATION_OCTET_STREAM : defaultCt;
    }

    MessageContext mc = new MessageContextImpl(message);
    MediaType mt = mc.getHttpHeaders().getMediaType();

    InputStream is;
    if (mt == null || mt.isCompatible(MediaType.APPLICATION_FORM_URLENCODED_TYPE)) {
        is = copyAndGetEntityStream(message);
    } else {
        is = message.getContent(InputStream.class);
    }

    if (is == null) {
        Reader reader = message.getContent(Reader.class);
        if (reader != null) {
            is = new ReaderInputStream(reader);
        }
    }

    return readFromMessageBody(parameterClass,
                               parameterType,
                               parameterAnns,
                               is,
                               toMediaType(contentType),
                               ori,
                               message);
}
 
Example 18
Source File: AbstractSpnegoAuthSupplier.java    From cxf with Apache License 2.0 4 votes vote down vote up
/**
 * Create and return a service ticket token for a given service principal
 * name
 *
 * @param authPolicy
 * @param spn
 * @return service ticket token
 * @throws GSSException
 * @throws LoginException
 */
private byte[] getToken(AuthorizationPolicy authPolicy,
                        String spn,
                        Oid oid,
                        Message message) throws GSSException,
    LoginException {

    GSSCredential delegatedCred =
        (GSSCredential)message.getContextualProperty(GSSCredential.class.getName());

    Subject subject = null;
    if (authPolicy != null && delegatedCred == null) {
        String contextName = authPolicy.getAuthorization();
        if (contextName == null) {
            contextName = "";
        }

        if (!(StringUtils.isEmpty(authPolicy.getUserName())
            && StringUtils.isEmpty(contextName) && loginConfig == null)) {
            CallbackHandler callbackHandler = getUsernamePasswordHandler(
                authPolicy.getUserName(), authPolicy.getPassword());
            LoginContext lc = new LoginContext(contextName, null, callbackHandler, loginConfig);
            lc.login();
            subject = lc.getSubject();
        }
    }

    GSSManager manager = GSSManager.getInstance();
    GSSName serverName = manager.createName(spn, serviceNameType);

    GSSContext context = manager
            .createContext(serverName.canonicalize(oid), oid, delegatedCred, GSSContext.DEFAULT_LIFETIME);

    context.requestCredDeleg(isCredDelegationRequired(message));

    // If the delegated cred is not null then we only need the context to
    // immediately return a ticket based on this credential without attempting
    // to log on again
    final byte[] token = new byte[0];
    if (delegatedCred != null) {
        return context.initSecContext(token, 0, token.length);
    }

    decorateSubject(subject);

    try {
        return Subject.doAs(subject, new CreateServiceTicketAction(context, token));
    } catch (PrivilegedActionException e) {
        if (e.getCause() instanceof GSSException) {
            throw (GSSException) e.getCause();
        }
        LOG.log(Level.SEVERE, "initSecContext", e);
        return null;
    }
}
 
Example 19
Source File: WSDLGetInterceptor.java    From cxf with Apache License 2.0 4 votes vote down vote up
public void handleMessage(Message message) throws Fault {
    String method = (String)message.get(Message.HTTP_REQUEST_METHOD);
    String query = (String)message.get(Message.QUERY_STRING);

    if (!"GET".equals(method) || StringUtils.isEmpty(query)) {
        return;
    }

    String baseUri = (String)message.get(Message.REQUEST_URL);
    String ctx = (String)message.get(Message.PATH_INFO);

    WSDLGetUtils utils = (WSDLGetUtils)message.getContextualProperty(WSDLGetUtils.class.getName());
    if (utils == null) {
        utils = new WSDLGetUtils();
        message.put(WSDLGetUtils.class, utils);
    }
    Map<String, String> map = UrlUtils.parseQueryString(query);
    if (isRecognizedQuery(map)) {
        Document doc = getDocument(utils, message, baseUri, map, ctx);

        Endpoint e = message.getExchange().getEndpoint();
        Message mout = new MessageImpl();
        mout.setExchange(message.getExchange());
        mout = e.getBinding().createMessage(mout);
        mout.setInterceptorChain(OutgoingChainInterceptor.getOutInterceptorChain(message.getExchange()));
        message.getExchange().setOutMessage(mout);

        mout.put(DOCUMENT_HOLDER, doc);
        mout.put(Message.CONTENT_TYPE, "text/xml");

        // just remove the interceptor which should not be used
        cleanUpOutInterceptors(mout);

        // notice this is being added after the purge above, don't swap the order!
        mout.getInterceptorChain().add(wsdlGetOutInterceptor);

        message.getExchange().put(TRANSFORM_SKIP, Boolean.TRUE);
        // skip the service executor and goto the end of the chain.
        message.getInterceptorChain().doInterceptStartingAt(
                message,
                OutgoingChainInterceptor.class.getName());
    }
}
 
Example 20
Source File: ExceptionUtils.java    From cxf with Apache License 2.0 3 votes vote down vote up
public static boolean propogateException(Message m) {

        Object value = m.getContextualProperty(PROPAGATE_EXCEPTION);

        if (value == null) {
            return true;
        }

        return Boolean.TRUE.equals(value) || "true".equalsIgnoreCase(value.toString());
    }