Java Code Examples for org.apache.cxf.phase.PhaseInterceptorChain#getCurrentMessage()

The following examples show how to use org.apache.cxf.phase.PhaseInterceptorChain#getCurrentMessage() . 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: JAXRSDataBinding.java    From cxf with Apache License 2.0 6 votes vote down vote up
public void write(Object obj, MessagePartInfo part, XMLStreamWriter output) {
    try {
        Message message = PhaseInterceptorChain.getCurrentMessage();
        Method method = MessageUtils.getTargetMethod(message).orElse(null);
        MultivaluedMap<String, Object> headers = getWriteHeaders(message);
        xmlWriter.writeTo(obj,
                         method.getReturnType(),
                         method.getGenericReturnType(),
                         method.getAnnotations(),
                         MediaType.APPLICATION_XML_TYPE,
                         headers,
                         null);
        message.put(Message.PROTOCOL_HEADERS, headers);
    } catch (Exception ex) {
        // ignore
    }
}
 
Example 2
Source File: MEXUtils.java    From cxf with Apache License 2.0 6 votes vote down vote up
public static List<Element> getSchemas(Server server, String id) {
    Message message = PhaseInterceptorChain.getCurrentMessage();

    String base = (String)message.get(Message.REQUEST_URL);
    String ctxUri = (String)message.get(Message.PATH_INFO);

    WSDLGetUtils utils = new WSDLGetUtils();
    EndpointInfo info = server.getEndpoint().getEndpointInfo();
    Map<String, String> locs = utils.getSchemaLocations(message,
                                                  base,
                                                  ctxUri,
                                                  info);
    List<Element> ret = new LinkedList<>();
    for (Map.Entry<String, String> xsd : locs.entrySet()) {

        if (StringUtils.isEmpty(id)
            || id.equals(xsd.getKey())) {
            String query = xsd.getValue().substring(xsd.getValue().indexOf('?') + 1);
            Map<String, String> params = UrlUtils.parseQueryString(query);

            ret.add(utils.getDocument(message, base, params, ctxUri, info).getDocumentElement());
        }
    }
    return ret;
}
 
Example 3
Source File: AbstractUsernameTokenAuthenticatingInterceptor.java    From steady with Apache License 2.0 5 votes vote down vote up
@Override
protected SecurityContext createSecurityContext(final Principal p) {
    Message msg = PhaseInterceptorChain.getCurrentMessage();
    if (msg == null) {
        throw new IllegalStateException("Current message is not available");
    }
    return doCreateSecurityContext(p, msg.get(Subject.class));
}
 
Example 4
Source File: BinaryDataProvider.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected boolean isRangeSupported() {
    Message message = PhaseInterceptorChain.getCurrentMessage();
    if (message != null) {
        return PropertyUtils.isTrue(message.get(HTTP_RANGE_PROPERTY));
    }
    return false;
}
 
Example 5
Source File: MediaTypeHeaderProvider.java    From cxf with Apache License 2.0 5 votes vote down vote up
private static MediaType handleMediaTypeWithoutSubtype(String mType) {
    if (mType.startsWith(MediaType.MEDIA_TYPE_WILDCARD)) {
        String mTypeNext = mType.length() == 1 ? "" : mType.substring(1).trim();
        boolean mTypeNextEmpty = StringUtils.isEmpty(mTypeNext);
        if (mTypeNextEmpty || mTypeNext.startsWith(";")) {
            if (!mTypeNextEmpty) {
                Map<String, String> parameters = new LinkedHashMap<>();
                StringTokenizer st = new StringTokenizer(mType.substring(2).trim(), ";");
                while (st.hasMoreTokens()) {
                    addParameter(parameters, st.nextToken());
                }
                return new MediaType(MediaType.MEDIA_TYPE_WILDCARD,
                                     MediaType.MEDIA_TYPE_WILDCARD,
                                     parameters);
            }
            return MediaType.WILDCARD_TYPE;

        }
    }
    Message message = PhaseInterceptorChain.getCurrentMessage();
    if (message != null
        && !MessageUtils.getContextualBoolean(message, STRICT_MEDIA_TYPE_CHECK, false)) {
        MediaType mt = null;
        if (mType.equals(MediaType.TEXT_PLAIN_TYPE.getType())) {
            mt = MediaType.TEXT_PLAIN_TYPE;
        } else if (mType.equals(MediaType.APPLICATION_XML_TYPE.getSubtype())) {
            mt = MediaType.APPLICATION_XML_TYPE;
        } else {
            mt = MediaType.WILDCARD_TYPE;
        }
        LOG.fine("Converting a malformed media type '" + mType + "' to '" + typeToString(mt) + "'");
        return mt;
    }
    throw new IllegalArgumentException("Media type separator is missing");
}
 
Example 6
Source File: JoseUtils.java    From cxf with Apache License 2.0 5 votes vote down vote up
public static void validateRequestContextProperty(JoseHeaders headers) {
    Message message = PhaseInterceptorChain.getCurrentMessage();
    Object requestContext = message.get(JoseConstants.JOSE_CONTEXT_PROPERTY);
    Object headerContext = headers.getHeader(JoseConstants.JOSE_CONTEXT_PROPERTY);
    if (!Objects.equals(requestContext, headerContext)) {
        LOG.warning("Invalid JOSE context property");
        throw new JoseException();
    }
}
 
Example 7
Source File: ResponseBuilderImpl.java    From cxf with Apache License 2.0 5 votes vote down vote up
public ResponseBuilder location(URI loc) {
    if (!loc.isAbsolute()) {
        Message currentMessage = PhaseInterceptorChain.getCurrentMessage();
        if (currentMessage != null) {

            UriInfo ui = new UriInfoImpl(currentMessage.getExchange().getInMessage(), null);
            loc = ui.getBaseUriBuilder()
                    .path(loc.getRawPath())
                    .replaceQuery(loc.getRawQuery())
                    .fragment(loc.getRawFragment()).buildFromEncoded();
        }
    }
    return setHeader(HttpHeaders.LOCATION, loc);
}
 
Example 8
Source File: KeyManagementUtils.java    From cxf with Apache License 2.0 5 votes vote down vote up
public static void validateCertificateChain(Properties storeProperties, List<X509Certificate> inCerts) {
    Message message = PhaseInterceptorChain.getCurrentMessage();
    KeyStore ks = loadPersistKeyStore(message, storeProperties);
    String enableRevocationProp = storeProperties.getProperty(RSSecurityConstants.RSSEC_ENABLE_REVOCATION);
    if (enableRevocationProp == null) {
        enableRevocationProp = (String)message.getContextualProperty(JoseConstants.RSSEC_ENABLE_REVOCATION);
    }
    boolean enableRevocation = enableRevocationProp != null && Boolean.parseBoolean(enableRevocationProp);
    validateCertificateChain(ks, inCerts, enableRevocation);
}
 
Example 9
Source File: ContextProducerBean.java    From cxf with Apache License 2.0 5 votes vote down vote up
private Object createContextValue() {
    Message currentMessage = PhaseInterceptorChain.getCurrentMessage();
    Type genericType = null;
    Class<?> contextType;
    if (type instanceof ParameterizedType) {
        ParameterizedType parameterizedType = (ParameterizedType)type;
        genericType = parameterizedType.getActualTypeArguments()[0];
        contextType = (Class<?>)parameterizedType.getRawType();
    } else {
        contextType = (Class<?>)type;
    }
    return JAXRSUtils.createContextValue(currentMessage, genericType, contextType);
}
 
Example 10
Source File: JoseUtils.java    From cxf with Apache License 2.0 5 votes vote down vote up
public static void setJoseContextProperty(JoseHeaders headers) {
    Message message = PhaseInterceptorChain.getCurrentMessage();
    String context = (String)message.get(JoseConstants.JOSE_CONTEXT_PROPERTY);
    if (context != null) {
        headers.setHeader(JoseConstants.JOSE_CONTEXT_PROPERTY, context);
    }
}
 
Example 11
Source File: BookCxfContinuationStore.java    From cxf with Apache License 2.0 5 votes vote down vote up
private Continuation getContinuation(String name) {

        ContinuationProvider provider =
            (ContinuationProvider)context.get(ContinuationProvider.class.getName());

        if (provider == null) {
            Message m = PhaseInterceptorChain.getCurrentMessage();
            UriInfo uriInfo = new UriInfoImpl(m);
            if (uriInfo.getAbsolutePath().toString().contains("/books/subresources/")) {
                // when we suspend a CXF continuation from a sub-resource, the invocation will
                // return directly to that object - and sub-resources do not have contexts supported
                // by default - so we just need to depend on PhaseInterceptorChain
                provider = (ContinuationProvider)m.get(ContinuationProvider.class.getName());
            }
        }
        if (provider == null) {
            throw new WebApplicationException(500);
        }

        synchronized (suspended) {
            Continuation suspendedCont = suspended.remove(name);
            if (suspendedCont != null) {
                return suspendedCont;
            }
        }

        return provider.getContinuation();
    }
 
Example 12
Source File: JweUtils.java    From cxf with Apache License 2.0 4 votes vote down vote up
public static Properties loadEncryptionProperties(String propertiesName, boolean required) {
    Message m = PhaseInterceptorChain.getCurrentMessage();
    return KeyManagementUtils.loadStoreProperties(m, required, propertiesName, null);
}
 
Example 13
Source File: JweUtils.java    From cxf with Apache License 2.0 4 votes vote down vote up
public static JweEncryptionProvider loadEncryptionProvider(Properties props, JweHeaders headers) {
    Message m = PhaseInterceptorChain.getCurrentMessage();
    return loadEncryptionProvider(props, m, headers);
}
 
Example 14
Source File: KeyManagementUtils.java    From cxf with Apache License 2.0 4 votes vote down vote up
public static Properties loadSignatureOutProperties() {
    Message m = PhaseInterceptorChain.getCurrentMessage();
    return loadStoreProperties(m, HTTPSignatureConstants.RSSEC_SIGNATURE_OUT_PROPS,
                               HTTPSignatureConstants.RSSEC_SIGNATURE_PROPS);
}
 
Example 15
Source File: SamlCallbackHandler.java    From cxf with Apache License 2.0 4 votes vote down vote up
public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
    Message m = PhaseInterceptorChain.getCurrentMessage();

    for (int i = 0; i < callbacks.length; i++) {
        if (callbacks[i] instanceof SAMLCallback) {
            SAMLCallback callback = (SAMLCallback) callbacks[i];
            if (saml2) {
                callback.setSamlVersion(Version.SAML_20);
            } else {
                callback.setSamlVersion(Version.SAML_11);
            }
            callback.setIssuer(issuer);

            String subject = m != null ? (String)m.getContextualProperty("saml.subject.name") : null;
            if (subject == null) {
                subject = subjectName;
            }
            String subjectQualifier = "www.mock-sts.com";
            SubjectBean subjectBean =
                new SubjectBean(
                    subject, subjectQualifier, confirmationMethod
                );
            callback.setSubject(subjectBean);

            ConditionsBean conditions = new ConditionsBean();

            AudienceRestrictionBean audienceRestriction = new AudienceRestrictionBean();
            audienceRestriction.setAudienceURIs(Collections.singletonList(audience));
            conditions.setAudienceRestrictions(Collections.singletonList(audienceRestriction));

            callback.setConditions(conditions);

            AuthDecisionStatementBean authDecBean = new AuthDecisionStatementBean();
            authDecBean.setDecision(Decision.INDETERMINATE);
            authDecBean.setResource("https://sp.example.com/SAML2");
            authDecBean.setSubject(subjectBean);

            ActionBean actionBean = new ActionBean();
            actionBean.setContents("Read");
            authDecBean.setActions(Collections.singletonList(actionBean));
            callback.setAuthDecisionStatementData(Collections.singletonList(authDecBean));

            AuthenticationStatementBean authBean = new AuthenticationStatementBean();
            authBean.setSubject(subjectBean);
            authBean.setAuthenticationInstant(new DateTime());
            authBean.setSessionIndex("123456");
            authBean.setSubject(subjectBean);

            // AuthnContextClassRef is not set
            authBean.setAuthenticationMethod(
                    "urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport");
            callback.setAuthenticationStatementData(
                Collections.singletonList(authBean));

            AttributeStatementBean attrBean = new AttributeStatementBean();
            attrBean.setSubject(subjectBean);

            List<String> roles = m != null
                ? CastUtils.<String>cast((List<?>)m.getContextualProperty("saml.roles")) : null;
            if (roles == null) {
                roles = Collections.singletonList("user");
            }
            List<AttributeBean> claims = new ArrayList<>();
            AttributeBean roleClaim = new AttributeBean();
            roleClaim.setSimpleName("subject-role");
            roleClaim.setQualifiedName(SAMLClaim.SAML_ROLE_ATTRIBUTENAME_DEFAULT);
            roleClaim.setNameFormat(SAML2Constants.ATTRNAME_FORMAT_UNSPECIFIED);
            roleClaim.setAttributeValues(new ArrayList<>(roles));
            claims.add(roleClaim);

            List<String> authMethods =
                m != null ? CastUtils.<String>cast((List<?>)m.getContextualProperty("saml.auth")) : null;
            if (authMethods == null) {
                authMethods = Collections.singletonList("password");
            }

            AttributeBean authClaim = new AttributeBean();
            authClaim.setSimpleName("http://claims/authentication");
            authClaim.setQualifiedName("http://claims/authentication");
            authClaim.setNameFormat("http://claims/authentication-format");
            authClaim.setAttributeValues(new ArrayList<>(authMethods));
            claims.add(authClaim);

            attrBean.setSamlAttributes(claims);
            callback.setAttributeStatementData(Collections.singletonList(attrBean));

            if (signAssertion) {
                try {
                    Crypto crypto = CryptoFactory.getInstance(cryptoPropertiesFile);
                    callback.setIssuerCrypto(crypto);
                    callback.setIssuerKeyName(issuerKeyName);
                    callback.setIssuerKeyPassword(issuerKeyPassword);
                    callback.setSignAssertion(true);
                } catch (WSSecurityException e) {
                    throw new IOException(e);
                }
            }
        }
    }
}
 
Example 16
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 17
Source File: KeyManagementUtils.java    From cxf with Apache License 2.0 4 votes vote down vote up
public static Properties loadSignatureInProperties() {
    Message m = PhaseInterceptorChain.getCurrentMessage();
    return loadStoreProperties(m, HTTPSignatureConstants.RSSEC_SIGNATURE_IN_PROPS,
                               HTTPSignatureConstants.RSSEC_SIGNATURE_PROPS);

}
 
Example 18
Source File: JwsUtils.java    From cxf with Apache License 2.0 4 votes vote down vote up
public static Properties loadSignatureProperties(String propertiesName, boolean required) {
    Message m = PhaseInterceptorChain.getCurrentMessage();
    return KeyManagementUtils.loadStoreProperties(m, required, propertiesName, null);

}
 
Example 19
Source File: SearchUtils.java    From cxf with Apache License 2.0 4 votes vote down vote up
private static boolean escapeUnderscoreChar() {
    Message m = PhaseInterceptorChain.getCurrentMessage();
    return MessageUtils.getContextualBoolean(m, ESCAPE_UNDERSCORE_CHAR, true);
}
 
Example 20
Source File: TomitribeSignatureCreator.java    From cxf with Apache License 2.0 4 votes vote down vote up
@Override
public String createSignature(Map<String, List<String>> messageHeaders, String uri, String method)
        throws IOException {
    if (messageHeaders == null) {
        throw new IllegalArgumentException("message headers cannot be null");
    }

    List<String> headers = null;
    // If we have explicit headers to sign then use these.
    // Otherwise sign all headers including "(request-target)" (if on an outbound service request)
    if (headersToSign.isEmpty()) {
        headers = messageHeaders.keySet().stream().map(String::toLowerCase).collect(Collectors.toList());
        Message m = PhaseInterceptorChain.getCurrentMessage();
        if (MessageUtils.isRequestor(m)) {
            headers.add(HTTPSignatureConstants.REQUEST_TARGET);
        }
    } else {
        headers = headersToSign.stream().map(String::toLowerCase).collect(Collectors.toList());
    }

    if (keyId == null) {
        throw new IllegalArgumentException("key id cannot be null");
    }

    final Signature signature = new Signature(keyId, signatureAlgorithmName, null, headers);
    final org.tomitribe.auth.signatures.Signer signer =
            new org.tomitribe.auth.signatures.Signer(keyProvider.getKey(keyId), signature);
    Signature outputSignature = signer.sign(method, uri, SignatureHeaderUtils.mapHeaders(messageHeaders));

    StringBuilder sb = new StringBuilder(128);
    sb.append("keyId=\"");
    sb.append(outputSignature.getKeyId());
    sb.append('"');
    sb.append(",algorithm=\"");
    sb.append(outputSignature.getAlgorithm());
    sb.append('"');
    sb.append(",headers=\"");
    sb.append(Join.join(" ", outputSignature.getHeaders()));
    sb.append('"');
    sb.append(",signature=\"");
    sb.append(outputSignature.getSignature());
    sb.append('"');
    return sb.toString();
}