Search in sources :

Example 36 with AuthorizationPolicy

use of org.apache.cxf.configuration.security.AuthorizationPolicy in project testcases by coheigea.

the class SyncopeBasicAuthInterceptor method handleMessage.

public void handleMessage(Message message) throws Fault {
    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 error = "No user credentials are available";
        LOG.warning(error + " " + "for name: " + name);
        throw new SecurityException(error);
    }
    try {
        UsernameToken token = convertPolicyToToken(policy);
        Credential credential = new Credential();
        credential.setUsernametoken(token);
        RequestData data = new RequestData();
        data.setMsgContext(message);
        credential = validator.validate(credential, data);
        // Create a Principal/SecurityContext
        Principal p = null;
        if (credential != null && credential.getPrincipal() != null) {
            p = credential.getPrincipal();
        } else {
            p = new WSUsernameTokenPrincipalImpl(policy.getUserName(), false);
            ((WSUsernameTokenPrincipalImpl) p).setPassword(policy.getPassword());
        }
        message.put(SecurityContext.class, createSecurityContext(p));
    } catch (Exception ex) {
        throw new Fault(ex);
    }
}
Also used : AuthorizationPolicy(org.apache.cxf.configuration.security.AuthorizationPolicy) Credential(org.apache.wss4j.dom.validate.Credential) RequestData(org.apache.wss4j.dom.handler.RequestData) UsernameToken(org.apache.wss4j.dom.message.token.UsernameToken) Fault(org.apache.cxf.interceptor.Fault) Principal(java.security.Principal) WSUsernameTokenPrincipalImpl(org.apache.wss4j.common.principal.WSUsernameTokenPrincipalImpl)

Example 37 with AuthorizationPolicy

use of org.apache.cxf.configuration.security.AuthorizationPolicy in project tomee by apache.

the class AbstractHTTPDestination method setupMessage.

protected void setupMessage(final Message inMessage, final ServletConfig config, final ServletContext context, final HttpServletRequest req, final HttpServletResponse resp) throws IOException {
    setupContinuation(inMessage, req, resp);
    final Exchange exchange = inMessage.getExchange();
    DelegatingInputStream in = new DelegatingInputStream(req.getInputStream()) {

        public void cacheInput() {
            if (!cached && (exchange.isOneWay() || isWSAddressingReplyToSpecified(exchange))) {
                // For one-ways and WS-Addressing invocations with ReplyTo address,
                // we need to cache the values of the HttpServletRequest
                // so they can be queried later for things like paths and schemes
                // and such like that.
                // Please note, exchange used to always get the "current" message
                exchange.getInMessage().put(HTTP_REQUEST, new HttpServletRequestSnapshot(req));
            }
            super.cacheInput();
        }

        private boolean isWSAddressingReplyToSpecified(Exchange ex) {
            AddressingProperties map = ContextUtils.retrieveMAPs(ex.getInMessage(), false, false, false);
            return map != null && !ContextUtils.isGenericAddress(map.getReplyTo());
        }
    };
    inMessage.setContent(DelegatingInputStream.class, in);
    inMessage.setContent(InputStream.class, in);
    inMessage.put(HTTP_REQUEST, req);
    inMessage.put(HTTP_RESPONSE, resp);
    inMessage.put(HTTP_CONTEXT, context);
    inMessage.put(HTTP_CONFIG, config);
    inMessage.put(HTTP_CONTEXT_MATCH_STRATEGY, contextMatchStrategy);
    inMessage.put(Message.HTTP_REQUEST_METHOD, req.getMethod());
    String requestURI = req.getRequestURI();
    inMessage.put(Message.REQUEST_URI, requestURI);
    String requestURL = req.getRequestURL().toString();
    inMessage.put(Message.REQUEST_URL, requestURL);
    String contextPath = req.getContextPath();
    if (contextPath == null) {
        contextPath = "";
    }
    String servletPath = req.getServletPath();
    if (servletPath == null) {
        servletPath = "";
    }
    String contextServletPath = contextPath + servletPath;
    String pathInfo = req.getPathInfo();
    if (pathInfo != null) {
        inMessage.put(Message.PATH_INFO, contextServletPath + pathInfo);
    } else {
        inMessage.put(Message.PATH_INFO, requestURI);
    }
    if (!StringUtils.isEmpty(requestURI)) {
        int index = requestURL.indexOf(requestURI);
        if (index > 0) {
            // Can be useful for referencing resources with URIs not covered by CXFServlet.
            // For example, if we a have web application name 'app' and CXFServlet listening
            // on "/services/*" then having HTTP_BASE_PATH pointing to say
            // http://localhost:8080/app will make it easy to refer to non CXF resources
            String schemaInfo = requestURL.substring(0, index);
            String basePathWithContextOnly = schemaInfo + contextPath;
            inMessage.put(HTTP_BASE_PATH, basePathWithContextOnly);
        }
    } else if (!StringUtils.isEmpty(servletPath) && requestURL.endsWith(servletPath)) {
        int index = requestURL.lastIndexOf(servletPath);
        if (index > 0) {
            inMessage.put(HTTP_BASE_PATH, requestURL.substring(0, index));
        }
    }
    String contentType = req.getContentType();
    inMessage.put(Message.CONTENT_TYPE, contentType);
    setEncoding(inMessage, req, contentType);
    inMessage.put(Message.QUERY_STRING, req.getQueryString());
    inMessage.put(Message.ACCEPT_CONTENT_TYPE, req.getHeader("Accept"));
    String basePath = getBasePath(contextServletPath);
    if (!StringUtils.isEmpty(basePath)) {
        inMessage.put(Message.BASE_PATH, basePath);
    }
    inMessage.put(Message.FIXED_PARAMETER_ORDER, isFixedParameterOrder());
    inMessage.put(Message.ASYNC_POST_RESPONSE_DISPATCH, Boolean.TRUE);
    SecurityContext httpSecurityContext = new SecurityContext() {

        public Principal getUserPrincipal() {
            return req.getUserPrincipal();
        }

        public boolean isUserInRole(String role) {
            return req.isUserInRole(role);
        }
    };
    inMessage.put(SecurityContext.class, httpSecurityContext);
    Headers headers = new Headers(inMessage);
    headers.copyFromRequest(req);
    String credentials = headers.getAuthorization();
    AuthorizationPolicy authPolicy = getAuthorizationPolicyFromMessage(credentials, httpSecurityContext);
    inMessage.put(AuthorizationPolicy.class, authPolicy);
    propogateSecureSession(req, inMessage);
    inMessage.put(CertConstraints.class.getName(), certConstraints);
    inMessage.put(Message.IN_INTERCEPTORS, Arrays.asList(new Interceptor[] { CertConstraintsInterceptor.INSTANCE }));
}
Also used : Exchange(org.apache.cxf.message.Exchange) AuthorizationPolicy(org.apache.cxf.configuration.security.AuthorizationPolicy) DelegatingInputStream(org.apache.cxf.io.DelegatingInputStream) SecurityContext(org.apache.cxf.security.SecurityContext) CertConstraints(org.apache.cxf.transport.https.CertConstraints) AddressingProperties(org.apache.cxf.ws.addressing.AddressingProperties) CertConstraintsInterceptor(org.apache.cxf.transport.https.CertConstraintsInterceptor) Interceptor(org.apache.cxf.interceptor.Interceptor)

Example 38 with AuthorizationPolicy

use of org.apache.cxf.configuration.security.AuthorizationPolicy in project tomee by apache.

the class HTTPConduit method getEffectiveAuthPolicy.

/**
 * Determines effective auth policy from message, conduit and empty default
 * with priority from first to last
 *
 * @param message
 * @return effective AthorizationPolicy
 */
public AuthorizationPolicy getEffectiveAuthPolicy(Message message) {
    AuthorizationPolicy authPolicy = getAuthorization();
    AuthorizationPolicy newPolicy = message.get(AuthorizationPolicy.class);
    AuthorizationPolicy effectivePolicy = newPolicy;
    if (effectivePolicy == null) {
        effectivePolicy = authPolicy;
    }
    if (effectivePolicy == null) {
        effectivePolicy = new AuthorizationPolicy();
    }
    return effectivePolicy;
}
Also used : ProxyAuthorizationPolicy(org.apache.cxf.configuration.security.ProxyAuthorizationPolicy) AuthorizationPolicy(org.apache.cxf.configuration.security.AuthorizationPolicy)

Example 39 with AuthorizationPolicy

use of org.apache.cxf.configuration.security.AuthorizationPolicy in project tomee by apache.

the class HTTPConduit method prepare.

/**
 * Prepare to send an outbound HTTP message over this http conduit to a
 * particular endpoint.
 * <P>
 * If the Message.PATH_INFO property is set it gets appended
 * to the Conduit's endpoint URL. If the Message.QUERY_STRING
 * property is set, it gets appended to the resultant URL following
 * a "?".
 * <P>
 * If the Message.HTTP_REQUEST_METHOD property is NOT set, the
 * Http request method defaults to "POST".
 * <P>
 * If the Message.PROTOCOL_HEADERS is not set on the message, it is
 * initialized to an empty map.
 * <P>
 * This call creates the OutputStream for the content of the message.
 * It also assigns the created Http(s)URLConnection to the Message
 * Map.
 *
 * @param message The message to be sent.
 */
public void prepare(Message message) throws IOException {
    // This call can possibly change the conduit endpoint address and
    // protocol from the default set in EndpointInfo that is associated
    // with the Conduit.
    Address currentAddress;
    try {
        currentAddress = setupAddress(message);
    } catch (URISyntaxException e) {
        throw new IOException(e);
    }
    // The need to cache the request is off by default
    boolean needToCacheRequest = false;
    HTTPClientPolicy csPolicy = getClient(message);
    setupConnection(message, currentAddress, csPolicy);
    // If the HTTP_REQUEST_METHOD is not set, the default is "POST".
    String httpRequestMethod = (String) message.get(Message.HTTP_REQUEST_METHOD);
    if (httpRequestMethod == null) {
        httpRequestMethod = "POST";
        message.put(Message.HTTP_REQUEST_METHOD, "POST");
    }
    boolean isChunking = false;
    int chunkThreshold = 0;
    final AuthorizationPolicy effectiveAuthPolicy = getEffectiveAuthPolicy(message);
    if (this.authSupplier == null) {
        this.authSupplier = createAuthSupplier(effectiveAuthPolicy);
    }
    if (this.proxyAuthSupplier == null) {
        this.proxyAuthSupplier = createAuthSupplier(proxyAuthorizationPolicy);
    }
    if (this.authSupplier.requiresRequestCaching()) {
        needToCacheRequest = true;
        isChunking = false;
        LOG.log(Level.FINE, "Auth Supplier, but no Preemptive User Pass or Digest auth (nonce may be stale)" + " We must cache request.");
    }
    if (csPolicy.isAutoRedirect()) {
        needToCacheRequest = true;
        LOG.log(Level.FINE, "AutoRedirect is turned on.");
    }
    if (csPolicy.getMaxRetransmits() > 0) {
        needToCacheRequest = true;
        LOG.log(Level.FINE, "MaxRetransmits is set > 0.");
    }
    // TODO : ensure chunking can be enabled for non-empty PUTs - if requested
    if (csPolicy.isAllowChunking() && isChunkingSupported(message, httpRequestMethod)) {
        // TODO: The chunking mode be configured or at least some
        // documented client constant.
        // use -1 and allow the URL connection to pick a default value
        isChunking = true;
        chunkThreshold = csPolicy.getChunkingThreshold();
    }
    cookies.writeToMessageHeaders(message);
    if (certConstraints != null) {
        message.put(CertConstraints.class.getName(), certConstraints);
        message.getInterceptorChain().add(CertConstraintsInterceptor.INSTANCE);
    }
    setHeadersByAuthorizationPolicy(message, currentAddress.getURI());
    new Headers(message).setFromClientPolicy(getClient(message));
    // set the OutputStream on the ProxyOutputStream
    ProxyOutputStream pos = message.getContent(ProxyOutputStream.class);
    if (pos != null && message.getContent(OutputStream.class) != null) {
        pos.setWrappedOutputStream(createOutputStream(message, needToCacheRequest, isChunking, chunkThreshold));
    } else {
        message.setContent(OutputStream.class, createOutputStream(message, needToCacheRequest, isChunking, chunkThreshold));
    }
// We are now "ready" to "send" the message.
}
Also used : ProxyAuthorizationPolicy(org.apache.cxf.configuration.security.ProxyAuthorizationPolicy) AuthorizationPolicy(org.apache.cxf.configuration.security.AuthorizationPolicy) HTTPClientPolicy(org.apache.cxf.transports.http.configuration.HTTPClientPolicy) CertConstraints(org.apache.cxf.transport.https.CertConstraints) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) Endpoint(org.apache.cxf.endpoint.Endpoint)

Example 40 with AuthorizationPolicy

use of org.apache.cxf.configuration.security.AuthorizationPolicy in project cxf by apache.

the class ClientFactoryBean method applyProperties.

protected void applyProperties(Endpoint ep) {
    // Apply the AuthorizationPolicy to the endpointInfo
    Map<String, Object> props = this.getProperties();
    if (props != null && props.get(AuthorizationPolicy.class.getName()) != null) {
        AuthorizationPolicy ap = (AuthorizationPolicy) props.get(AuthorizationPolicy.class.getName());
        ep.getEndpointInfo().addExtensor(ap);
    }
}
Also used : AuthorizationPolicy(org.apache.cxf.configuration.security.AuthorizationPolicy)

Aggregations

AuthorizationPolicy (org.apache.cxf.configuration.security.AuthorizationPolicy)82 Message (org.apache.cxf.message.Message)25 Test (org.junit.Test)22 IOException (java.io.IOException)15 HTTPConduit (org.apache.cxf.transport.http.HTTPConduit)15 ArrayList (java.util.ArrayList)10 Client (org.apache.cxf.endpoint.Client)10 List (java.util.List)8 HTTPClientPolicy (org.apache.cxf.transports.http.configuration.HTTPClientPolicy)8 URL (java.net.URL)7 HashMap (java.util.HashMap)7 ProxyAuthorizationPolicy (org.apache.cxf.configuration.security.ProxyAuthorizationPolicy)7 Map (java.util.Map)6 SecurityContext (org.apache.cxf.security.SecurityContext)6 Bus (org.apache.cxf.Bus)5 WebClient (org.apache.cxf.jaxrs.client.WebClient)5 MessageImpl (org.apache.cxf.message.MessageImpl)5 EndpointInfo (org.apache.cxf.service.model.EndpointInfo)5 Principal (java.security.Principal)4 Endpoint (org.apache.cxf.endpoint.Endpoint)4