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

The following examples show how to use org.apache.cxf.message.Message#get() . 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: XmlSecOutInterceptor.java    From cxf with Apache License 2.0 6 votes vote down vote up
public void handleMessage(Message mc) throws Fault {
    try {
        XMLStreamWriter xtw = mc.getContent(XMLStreamWriter.class);
        if (xtw != null) {
            xtw.writeEndDocument();
            xtw.flush();
            xtw.close();
        }

        OutputStream os = (OutputStream) mc.get(OUTPUT_STREAM_HOLDER);
        if (os != null) {
            mc.setContent(OutputStream.class, os);
        }
        mc.removeContent(XMLStreamWriter.class);
    } catch (XMLStreamException e) {
        throw new Fault(e);
    }
}
 
Example 2
Source File: HttpsTokenInterceptorProvider.java    From steady with Apache License 2.0 6 votes vote down vote up
public void handleMessage(Message message) throws Fault {
    AssertionInfoMap aim = message.get(AssertionInfoMap.class);
    // extract Assertion information
    if (aim != null) {
        Collection<AssertionInfo> ais = aim.get(SP12Constants.HTTPS_TOKEN);
        if (ais == null) {
            return;
        }
        if (isRequestor(message)) {
            assertHttps(ais, message);
        } else {
            //server side should be checked on the way in
            for (AssertionInfo ai : ais) {
                ai.setAsserted(true);
            }                    
        }
    }
}
 
Example 3
Source File: AbstractSecurityContextInInterceptor.java    From cxf with Apache License 2.0 6 votes vote down vote up
public void handleMessage(Message message) {
    SecurityToken token = message.get(SecurityToken.class);
    if (token == null) {
        reportSecurityException("Security Token is not available on the current message");
    }

    SecurityContext context = message.get(SecurityContext.class);
    if (context == null || context.getUserPrincipal() == null) {
        reportSecurityException("User Principal is not available on the current message");
    }

    Subject subject = null;
    try {
        subject = createSubject(token);
    } catch (Exception ex) {
        reportSecurityException("Failed Authentication : Subject has not been created, "
                                + ex.getMessage());
    }
    if (subject == null || subject.getPrincipals().isEmpty()) {
        reportSecurityException("Failed Authentication : Invalid Subject");
    }

    Principal principal = getPrincipal(context.getUserPrincipal(), subject);
    SecurityContext sc = createSecurityContext(principal, subject);
    message.put(SecurityContext.class, sc);
}
 
Example 4
Source File: NioReadEntity.java    From cxf with Apache License 2.0 6 votes vote down vote up
public NioReadEntity(NioReadHandler reader, NioReadCompletionHandler completion, NioErrorHandler error) {
    this.reader = reader;
    this.completion = completion;
    this.error = error;
    
    final Message m = JAXRSUtils.getCurrentMessage();
    try {
        if (m.get(AsyncResponse.class) == null) {
            throw new IllegalStateException("AsyncResponse is not available");
        }
        final HttpServletRequest request = (HttpServletRequest)m.get(AbstractHTTPDestination.HTTP_REQUEST);
        request.getInputStream().setReadListener(new NioReadListenerImpl(this, request.getInputStream()));
    } catch (final Throwable ex) {
        throw new RuntimeException("Unable to initialize NIO entity", ex);
    }
    
}
 
Example 5
Source File: BasicAuthHandler.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
public boolean canHandle(Message message, ClassResourceInfo classResourceInfo) {
    // check the "Authorization" header and if "Basic" is there, can be handled.

    // get the map of protocol headers
    Map protocolHeaders = (TreeMap) message.get(Message.PROTOCOL_HEADERS);
    // get the value for Authorization Header
    List authzHeaders = (ArrayList) protocolHeaders
            .get(SCIMConstants.AUTHORIZATION_HEADER);
    if (authzHeaders != null) {
        // get the authorization header value, if provided
        String authzHeader = (String) authzHeaders.get(0);
        if (authzHeader != null && authzHeader.contains(BASIC_AUTH_HEADER)) {
            return true;
        }
    }
    return false;
}
 
Example 6
Source File: JAXWSMethodInvokerTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testFaultHeadersCopy() throws Throwable {
    ExceptionService serviceObject = new ExceptionService();
    Method serviceMethod = ExceptionService.class.getMethod("invoke", new Class[]{});

    Exchange ex = new ExchangeImpl();
    prepareInMessage(ex, true);
    Message msg = new MessageImpl();
    SoapMessage outMessage = new SoapMessage(msg);
    ex.setOutMessage(outMessage);

    JAXWSMethodInvoker jaxwsMethodInvoker = prepareJAXWSMethodInvoker(ex, serviceObject, serviceMethod);

    try {
        jaxwsMethodInvoker.invoke(ex, new MessageContentsList(new Object[]{}));
        fail("Expected fault");
    } catch (Fault fault) {
        Message outMsg = ex.getOutMessage();
        assertNotNull(outMsg);
        @SuppressWarnings("unchecked")
        List<Header> headers = (List<Header>)outMsg.get(Header.HEADER_LIST);
        assertEquals(1, headers.size());
        assertEquals(TEST_HEADER_NAME, headers.get(0).getName());
    }
}
 
Example 7
Source File: ReceivedTokenCallbackHandler.java    From steady with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
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();
            
            if (message != null 
                && message.get(PhaseInterceptorChain.PREVIOUS_MESSAGE) != null) {
                WeakReference<SoapMessage> wr = 
                    (WeakReference<SoapMessage>)
                        message.get(PhaseInterceptorChain.PREVIOUS_MESSAGE);
                SoapMessage previousSoapMessage = wr.get();
                Element token = getTokenFromMessage(previousSoapMessage);
                if (token != null) {
                    callback.setToken(token);
                }
            }
            
        } else {
            throw new UnsupportedCallbackException(callbacks[i], "Unrecognized Callback");
        }
    }
}
 
Example 8
Source File: JAXRSInvoker.java    From cxf with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
protected MultivaluedMap<String, String> getTemplateValues(Message msg) {
    MultivaluedMap<String, String> values = new MetadataMap<>();
    MultivaluedMap<String, String> oldValues =
        (MultivaluedMap<String, String>)msg.get(URITemplate.TEMPLATE_PARAMETERS);
    if (oldValues != null) {
        values.putAll(oldValues);
    }
    return values;
}
 
Example 9
Source File: BraveClientStopInterceptor.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
public void handleMessage(Message message) throws Fault {
    @SuppressWarnings("unchecked")
    final TraceScopeHolder<TraceScope> holder =
        (TraceScopeHolder<TraceScope>)message.getExchange().get(TRACE_SPAN);

    Integer responseCode = (Integer)message.get(Message.RESPONSE_CODE);
    if (responseCode == null) {
        responseCode = 200;
    }

    super.stopTraceSpan(holder, responseCode);
}
 
Example 10
Source File: CallbackHandlerTlsCert.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
public CallbackHandler create(Message message) {
    TLSSessionInfo tlsSession = message.get(TLSSessionInfo.class);
    if (tlsSession == null) {
        return null;
    }
    Certificate cert = getCertificate(message);
    String name = certMapper.getUserName(cert);
    String password = nameToPasswordMapper.getPassword(name);
    return new NamePasswordCallbackHandler(name, password);
}
 
Example 11
Source File: ServiceUtils.java    From cxf with Apache License 2.0 5 votes vote down vote up
private static SchemaValidationType getOverrideSchemaValidationType(Message message) {
    Object obj = message.get(Message.SCHEMA_VALIDATION_ENABLED);
    if (obj == null && message.getExchange() != null) {
        obj = message.getExchange().get(Message.SCHEMA_VALIDATION_ENABLED);
    }
    if (obj != null) {
        // this method will transform the legacy enabled as well
        return getSchemaValidationType(obj);
    }
    return null;
}
 
Example 12
Source File: JMSDestinationTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testRoundTripDestination() throws Exception {
    Message msg = testRoundTripDestination(true);
    SecurityContext securityContext = msg.get(SecurityContext.class);

    assertNotNull("SecurityContext should be set in message received by JMSDestination", securityContext);
    assertEquals("Principal in SecurityContext should be", "testUser",
            securityContext.getUserPrincipal().getName());
}
 
Example 13
Source File: WSS4JBasicAuthValidator.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected void validate(Message message) throws WSSecurityException {

        AuthorizationPolicy policy = message.get(AuthorizationPolicy.class);
        if (policy == null || policy.getUserName() == null || policy.getPassword() == null) {
            String name = null;
            if (policy != null) {
                name = policy.getUserName();
            }
            String errorMsg = "No user name and/or password is available, name: " + name;
            LOG.warning(errorMsg);
            throw new SecurityException(errorMsg);
        }

        UsernameToken token = convertPolicyToToken(policy);
        Credential credential = new Credential();
        credential.setUsernametoken(token);

        RequestData data = new RequestData();
        data.setMsgContext(message);
        data.setCallbackHandler(callbackHandler);
        credential = getValidator().validate(credential, data);

        // Create a Principal/SecurityContext
        SecurityContext sc = null;
        if (credential != null && credential.getPrincipal() != null) {
            sc = createSecurityContext(message, credential);
        } else {
            Principal p = new WSUsernameTokenPrincipalImpl(policy.getUserName(), false);
            ((WSUsernameTokenPrincipalImpl)p).setPassword(policy.getPassword());
            sc = createSecurityContext(p);
        }

        message.put(SecurityContext.class, sc);
    }
 
Example 14
Source File: AbstractHTTPDestination.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected void invokeComplete(final ServletContext context,
                              final HttpServletRequest req,
                              final HttpServletResponse resp,
                              Message m) throws IOException {
    ContinuationProvider p = m.get(ContinuationProvider.class);
    if (p != null) {
        p.complete();
    }
}
 
Example 15
Source File: PreAuthenticationInterceptor.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Override
public void handleMessage(Message message) throws Fault {
    String path = (String) message.get(Message.PATH_INFO);
    if (path.contains(APIConstants.RestApiConstants.REST_API_OLD_VERSION)) {
        path = path.replace("/" + APIConstants.RestApiConstants.REST_API_OLD_VERSION, "");
    }
    String httpMethod = (String) message.get(Message.HTTP_REQUEST_METHOD);
    Dictionary<URITemplate,List<String>> whiteListedResourcePathsMap;

    //If Authorization headers are present anonymous URI check will be skipped
    ArrayList authHeaders = (ArrayList) ((TreeMap) (message.get(Message.PROTOCOL_HEADERS)))
            .get(RestApiConstants.AUTH_HEADER_NAME);
    if (authHeaders != null)
        return;

    //Check if the accessing URI is white-listed and then authorization is skipped
    try {
        whiteListedResourcePathsMap = RestApiUtil.getWhiteListedURIsToMethodsMap();
        Enumeration<URITemplate> uriTemplateSet = whiteListedResourcePathsMap.keys();

        while (uriTemplateSet.hasMoreElements()) {
            URITemplate uriTemplate = uriTemplateSet.nextElement();
            if (uriTemplate.matches(path, new HashMap<String, String>())) {
                List<String> whiteListedVerbs = whiteListedResourcePathsMap.get(uriTemplate);
                if (whiteListedVerbs.contains(httpMethod)) {
                    message.put(RestApiConstants.AUTHENTICATION_REQUIRED, false);
                    PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
                    carbonContext.setUsername(CarbonConstants.REGISTRY_ANONNYMOUS_USERNAME);
                    carbonContext.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
                    carbonContext.setTenantId(MultitenantConstants.SUPER_TENANT_ID);
                    return;
                }
            }
        }
    } catch (APIManagementException e) {
        RestApiUtil
                .handleInternalServerError("Unable to retrieve/process white-listed URIs for REST API", e, logger);
    }
}
 
Example 16
Source File: HTTPConduit.java    From cxf with Apache License 2.0 5 votes vote down vote up
/**
 * This function sets up a URL based on ENDPOINT_ADDRESS, PATH_INFO,
 * and QUERY_STRING properties in the Message. The QUERY_STRING gets
 * added with a "?" after the PATH_INFO. If the ENDPOINT_ADDRESS is not
 * set on the Message, the endpoint address is taken from the
 * "defaultEndpointURL".
 * <p>
 * The PATH_INFO is only added to the endpoint address string should
 * the PATH_INFO not equal the end of the endpoint address string.
 *
 * @param message The message holds the addressing information.
 *
 * @return The full URL specifying the HTTP request to the endpoint.
 *
 * @throws MalformedURLException
 * @throws URISyntaxException
 */
private Address setupAddress(Message message) throws URISyntaxException {
    String result = (String)message.get(Message.ENDPOINT_ADDRESS);
    String pathInfo = (String)message.get(Message.PATH_INFO);
    String queryString = (String)message.get(Message.QUERY_STRING);
    setAndGetDefaultAddress();
    if (result == null) {
        if (pathInfo == null && queryString == null) {
            if (defaultAddress != null) {
                message.put(Message.ENDPOINT_ADDRESS, defaultAddress.getString());
            }
            return defaultAddress;
        }
        if (defaultAddress != null) {
            result = defaultAddress.getString();
            message.put(Message.ENDPOINT_ADDRESS, result);
        }
    }

    // REVISIT: is this really correct?
    if (null != pathInfo && !result.endsWith(pathInfo)) {
        result = result + pathInfo;
    }
    if (queryString != null) {
        result = result + "?" + queryString;
    }
    if (defaultAddress == null) {
        return setAndGetDefaultAddress(result);
    }
    return result.equals(defaultAddress.getString()) ? defaultAddress : new Address(result);
}
 
Example 17
Source File: ClientProxyImpl.java    From cxf with Apache License 2.0 4 votes vote down vote up
@Override
protected void doWriteBody(Message outMessage,
                           Object body,
                           Type bodyType,
                           Annotation[] customAnns,
                           OutputStream os) throws Fault {


    OperationResourceInfo ori = outMessage.getContent(OperationResourceInfo.class);
    if (ori == null) {
        return;
    }

    Method method = ori.getMethodToInvoke();
    int bodyIndex = (Integer)outMessage.get(PROXY_METHOD_PARAM_BODY_INDEX);

    Annotation[] anns = customAnns != null ? customAnns
        : getMethodAnnotations(ori.getAnnotatedMethod(), bodyIndex);
    try {
        if (bodyIndex != -1) {
            Class<?> paramClass = method.getParameterTypes()[bodyIndex];
            Class<?> bodyClass =
                paramClass.isAssignableFrom(body.getClass()) ? paramClass : body.getClass();
            Type genericType = method.getGenericParameterTypes()[bodyIndex];
            if (bodyType != null) {
                genericType = bodyType;
            }
            genericType = InjectionUtils.processGenericTypeIfNeeded(
                ori.getClassResourceInfo().getServiceClass(), bodyClass, genericType);
            bodyClass = InjectionUtils.updateParamClassToTypeIfNeeded(bodyClass, genericType);
            writeBody(body, outMessage, bodyClass, genericType, anns, os);
        } else {
            Type paramType = body.getClass();
            if (bodyType != null) {
                paramType = bodyType;
            }
            writeBody(body, outMessage, body.getClass(), paramType,
                      anns, os);
        }
    } catch (Exception ex) {
        throw new Fault(ex);
    }

}
 
Example 18
Source File: SakaiLogin.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
/**
 * Actual login method
 * @param id
 * @param pw
 * @return
 */
private java.lang.String login(java.lang.String id, java.lang.String pw) {

    Message message = PhaseInterceptorChain.getCurrentMessage();
    HttpServletRequest request = (HttpServletRequest) message.get(AbstractHTTPDestination.HTTP_REQUEST);
    String ipAddress = request.getRemoteAddr();

    boolean allowLogin = serverConfigurationService.getBoolean("webservices.allowlogin", false);

    if (!allowLogin) {
        throw new RuntimeException("Web Services Login Disabled");
    }

    try {
        if ("GET".equals(request.getMethod())) {
            log.info("This endpoint {} should use POST instead of GET, GET will be deprecated in a future release", request.getRequestURI());
        }

        Evidence e = new IdPwEvidence(id, pw, ipAddress);
        Authentication a = authenticationManager.authenticate(e);

        Session s = sessionManager.startSession();
        sessionManager.setCurrentSession(s);

        if (s == null) {
            log.warn("Web Services Login failed to establish session for id=" + id + " ip=" + ipAddress);
            throw new RuntimeException("Unable to establish session");
        } else {
            // We do not care too much on the off-chance that this fails - folks simply won't show up in presense
            // and events won't be trackable back to people / IP Addresses - but if it fails - there is nothing
            // we can do anyways.

            usageSessionService.login(a.getUid(), id, ipAddress, "SakaiLogin", UsageSessionService.EVENT_LOGIN_WS);

            log.debug("Sakai Web Services Login id={} ip={} session={}", id, ipAddress, s.getId());

            // retrieve the configured cookie name, if any
            if (System.getProperty(RequestFilter.SAKAI_COOKIE_PROP) != null) {
                cookieName = System.getProperty(RequestFilter.SAKAI_COOKIE_PROP);
            }

            // retrieve the configured cookie domain, if any

            // compute the session cookie suffix, based on this configured server id
            String suffix = System.getProperty(RequestFilter.SAKAI_SERVERID);
            if (StringUtils.isEmpty(suffix)) {
                if (m_displayModJkWarning) {
                    log.warn("no sakai.serverId system property set - mod_jk load balancing will not function properly");
                }
                m_displayModJkWarning = false;
                suffix = "sakai";
            }

            Cookie c = new Cookie(cookieName, s.getId() + "." + suffix);
            c.setPath("/");
            c.setMaxAge(-1);
            if (System.getProperty(RequestFilter.SAKAI_COOKIE_DOMAIN) != null) {
                c.setDomain(System.getProperty(RequestFilter.SAKAI_COOKIE_DOMAIN));
            }
            if (request.isSecure() == true) {
                c.setSecure(true);
            }

            HttpServletResponse res = (HttpServletResponse) message.get(AbstractHTTPDestination.HTTP_RESPONSE);

            if (res != null) {
                res.addCookie(c);
            }

            log.debug("Sakai Web Services Login id={} ip={} session={}", id, ipAddress, s.getId());
            return s.getId();
        }
    } catch (AuthenticationException ex) {
        log.warn("Failed Web Services Login id=" + id + " ip=" + ipAddress + ": " + ex.getMessage());
    }

    throw new RuntimeException("Unable to login");
}
 
Example 19
Source File: SamlTokenTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
/**
 * This test creates a SAML2 Assertion and sends it in the security header to the provider.
 * An single attribute is created for the roles but multiple attribute value elements.
 */
@Test
public void testSaml2TokenWithRoles() throws Exception {
    Map<String, Object> outProperties = new HashMap<>();
    outProperties.put(ConfigurationConstants.ACTION, ConfigurationConstants.SAML_TOKEN_UNSIGNED);
    outProperties.put(ConfigurationConstants.SIG_KEY_ID, "DirectReference");
    outProperties.put(ConfigurationConstants.USER, "alice");
    outProperties.put("password", "password");
    outProperties.put(ConfigurationConstants.SIG_PROP_FILE, "alice.properties");
    SAML2CallbackHandler callbackHandler = new SAML2CallbackHandler();
    callbackHandler.setConfirmationMethod(SAML2Constants.CONF_HOLDER_KEY);
    callbackHandler.setSignAssertion(true);
    callbackHandler.setStatement(Statement.ATTR);
    callbackHandler.setConfirmationMethod(SAML2Constants.CONF_BEARER);

    outProperties.put(ConfigurationConstants.SAML_CALLBACK_REF, callbackHandler);

    Map<String, Object> inProperties = new HashMap<>();
    inProperties.put(
        ConfigurationConstants.ACTION, ConfigurationConstants.SAML_TOKEN_SIGNED
    );
    inProperties.put(ConfigurationConstants.SIG_VER_PROP_FILE, "insecurity.properties");
    final Map<QName, Object> customMap = new HashMap<>();
    CustomSamlValidator validator = new CustomSamlValidator();
    validator.setRequireSAML1Assertion(false);
    validator.setRequireSenderVouches(false);
    validator.setRequireBearer(true);
    customMap.put(WSConstants.SAML_TOKEN, validator);
    customMap.put(WSConstants.SAML2_TOKEN, validator);
    inProperties.put(WSS4JInInterceptor.VALIDATOR_MAP, customMap);

    List<String> xpaths = new ArrayList<>();
    xpaths.add("//wsse:Security");
    xpaths.add("//wsse:Security/saml2:Assertion");

    Map<String, String> inMessageProperties = new HashMap<>();
    inMessageProperties.put(SecurityConstants.VALIDATE_SAML_SUBJECT_CONFIRMATION, "false");
    Message message = makeInvocation(outProperties, xpaths, inProperties, inMessageProperties);

    final List<WSHandlerResult> handlerResults =
        CastUtils.cast((List<?>)message.get(WSHandlerConstants.RECV_RESULTS));

    SecurityContext sc = message.get(SecurityContext.class);
    assertNotNull(sc);
    assertTrue(sc.isUserInRole("user"));
    assertTrue(sc.isUserInRole("admin"));

    WSSecurityEngineResult actionResult =
        handlerResults.get(0).getActionResults().get(WSConstants.ST_SIGNED).get(0);
    SamlAssertionWrapper receivedAssertion =
        (SamlAssertionWrapper) actionResult.get(WSSecurityEngineResult.TAG_SAML_ASSERTION);
    assertTrue(receivedAssertion != null && receivedAssertion.getSaml2() != null);
    assertTrue(receivedAssertion.isSigned());
}
 
Example 20
Source File: Server.java    From cxf with Apache License 2.0 4 votes vote down vote up
protected Server() throws Exception {
    System.out.println("Starting Server");

    customers.put("Tom", new Customer.PremiumCustomer("Tom"));
    customers.put("Rob", new Customer.PreferredCustomer("Rob"));
    customers.put("Vince", new Customer.RegularCustomer("Vince"));
    customers.put("Malcolm", new Customer.CheapCustomer("Malcolm"));
    customers.put("Jonas", new Customer.TrialCustomer("Jonas"));

    Map<String, Object> properties = new HashMap<>();
    properties.put("bus.jmx.usePlatformMBeanServer", Boolean.TRUE);
    properties.put("bus.jmx.enabled", Boolean.TRUE);
    Bus b = new CXFBusFactory().createBus(null, properties);
    MetricRegistry registry = new MetricRegistry();
    CodahaleMetricsProvider.setupJMXReporter(b, registry);
    b.setExtension(registry, MetricRegistry.class);

    ThrottlingManager manager = new ThrottlingManager() {
        @Override
        public ThrottleResponse getThrottleResponse(String phase, Message m) {
            ThrottleResponse r = new ThrottleResponse();
            if (m.get("THROTTLED") != null) {
                return null;
            }
            m.put("THROTTLED", true);
            Customer c = m.getExchange().get(Customer.class);
            c.throttle(r);
            return r;
        }

        @Override
        public List<String> getDecisionPhases() {
            return Collections.singletonList(Phase.PRE_STREAM);
        }

    };
    b.getInInterceptors().add(new CustomerMetricsInterceptor(registry, customers));

    Object implementor = new GreeterImpl();
    String address = "http://localhost:9001/SoapContext/SoapPort";
    Endpoint.publish(address, implementor,
                     new MetricsFeature(),
                     new ThrottlingFeature(manager));
}