Search in sources :

Example 61 with AuthorizationPolicy

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

the class ClientServerWebSocketTest method testBasicAuth.

@Test
public void testBasicAuth() throws Exception {
    URL wsdl = getClass().getResource("/wsdl/hello_world.wsdl");
    assertNotNull(wsdl);
    SOAPService service = new SOAPService(wsdl, serviceName);
    Greeter greeter = service.getPort(portName, Greeter.class);
    updateGreeterAddress(greeter, PORT);
    try {
        // try the jaxws way
        BindingProvider bp = (BindingProvider) greeter;
        bp.getRequestContext().put(BindingProvider.USERNAME_PROPERTY, "BJ");
        bp.getRequestContext().put(BindingProvider.PASSWORD_PROPERTY, "pswd");
        String s = greeter.greetMe("secure");
        assertEquals("Hello BJ", s);
        bp.getRequestContext().remove(BindingProvider.USERNAME_PROPERTY);
        bp.getRequestContext().remove(BindingProvider.PASSWORD_PROPERTY);
        ((Closeable) greeter).close();
        greeter = service.getPort(portName, Greeter.class);
        updateGreeterAddress(greeter, PORT);
        // try setting on the conduit directly
        Client client = ClientProxy.getClient(greeter);
        HTTPConduit httpConduit = (HTTPConduit) client.getConduit();
        AuthorizationPolicy policy = new AuthorizationPolicy();
        policy.setUserName("BJ2");
        policy.setPassword("pswd");
        httpConduit.setAuthorization(policy);
        s = greeter.greetMe("secure");
        ((Closeable) greeter).close();
        assertEquals("Hello BJ2", s);
    } catch (UndeclaredThrowableException ex) {
        throw (Exception) ex.getCause();
    }
}
Also used : SOAPService(org.apache.hello_world_soap_http.SOAPService) HTTPConduit(org.apache.cxf.transport.http.HTTPConduit) AuthorizationPolicy(org.apache.cxf.configuration.security.AuthorizationPolicy) Greeter(org.apache.hello_world_soap_http.Greeter) Closeable(java.io.Closeable) UndeclaredThrowableException(java.lang.reflect.UndeclaredThrowableException) BindingProvider(javax.xml.ws.BindingProvider) Client(org.apache.cxf.endpoint.Client) URL(java.net.URL) Test(org.junit.Test)

Example 62 with AuthorizationPolicy

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

the class HTTPSConduitTest method testHttpsBasicConnection.

/**
 * This methods tests a basic https connection to Bethal.
 * It supplies an authorization policy with premetive user/pass
 * to avoid the 401.
 */
@Test
public void testHttpsBasicConnection() throws Exception {
    startServer("Bethal");
    URL wsdl = getClass().getResource("greeting.wsdl");
    assertNotNull("WSDL is null", wsdl);
    SOAPService service = new SOAPService(wsdl, serviceName);
    assertNotNull("Service is null", service);
    Greeter bethal = service.getPort(bethalQ, Greeter.class);
    assertNotNull("Port is null", bethal);
    updateAddressPort(bethal, getPort("PORT4"));
    // Okay, I'm sick of configuration files.
    // This also tests dynamic configuration of the conduit.
    Client client = ClientProxy.getClient(bethal);
    HTTPConduit http = (HTTPConduit) client.getConduit();
    HTTPClientPolicy httpClientPolicy = new HTTPClientPolicy();
    httpClientPolicy.setAutoRedirect(false);
    // If we set any name, but Edward, Mary, or George,
    // and a password of "password" we will get through
    // Bethal.
    AuthorizationPolicy authPolicy = new AuthorizationPolicy();
    authPolicy.setUserName("Betty");
    authPolicy.setPassword("password");
    http.setClient(httpClientPolicy);
    http.setTlsClientParameters(tlsClientParameters);
    http.setAuthorization(authPolicy);
    configureProxy(client);
    String answer = bethal.sayHi();
    assertTrue("Unexpected answer: " + answer, "Bonjour from Bethal".equals(answer));
    assertProxyRequestCount(0);
}
Also used : SOAPService(org.apache.hello_world.services.SOAPService) HTTPConduit(org.apache.cxf.transport.http.HTTPConduit) AuthorizationPolicy(org.apache.cxf.configuration.security.AuthorizationPolicy) Greeter(org.apache.hello_world.Greeter) HTTPClientPolicy(org.apache.cxf.transports.http.configuration.HTTPClientPolicy) Client(org.apache.cxf.endpoint.Client) URL(java.net.URL) Test(org.junit.Test)

Example 63 with AuthorizationPolicy

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

the class HTTPSConduitTest method testHttpsTrustRedirect.

@Test
public void testHttpsTrustRedirect() throws Exception {
    startServer("Tarpin");
    startServer("Gordy");
    startServer("Bethal");
    URL wsdl = getClass().getResource("greeting.wsdl");
    assertNotNull("WSDL is null", wsdl);
    SOAPService service = new SOAPService(wsdl, serviceName);
    assertNotNull("Service is null", service);
    Greeter tarpin = service.getPort(tarpinQ, Greeter.class);
    assertNotNull("Port is null", tarpin);
    updateAddressPort(tarpin, getPort("PORT1"));
    // Okay, I'm sick of configuration files.
    // This also tests dynamic configuration of the conduit.
    Client client = ClientProxy.getClient(tarpin);
    HTTPConduit http = (HTTPConduit) client.getConduit();
    HTTPClientPolicy httpClientPolicy = new HTTPClientPolicy();
    httpClientPolicy.setAutoRedirect(true);
    // If we set any name, but Edward, Mary, or George,
    // and a password of "password" we will get through
    // Bethal.
    AuthorizationPolicy authPolicy = new AuthorizationPolicy();
    authPolicy.setUserName("Betty");
    authPolicy.setPassword("password");
    http.setClient(httpClientPolicy);
    http.setTlsClientParameters(tlsClientParameters);
    http.setAuthorization(authPolicy);
    // We get redirected from Tarpin, to Gordy, to Bethal.
    MyHttpsTrustDecider trustDecider = new MyHttpsTrustDecider(new String[] { "Tarpin", "Gordy", "Bethal" });
    http.setTrustDecider(trustDecider);
    // We actually get our answer from Bethal at the end of the
    // redirects.
    configureProxy(ClientProxy.getClient(tarpin));
    String answer = tarpin.sayHi();
    assertProxyRequestCount(0);
    assertTrue("Trust Decider wasn't called correctly", 3 == trustDecider.wasCalled());
    assertTrue("Unexpected answer: " + answer, "Bonjour from Bethal".equals(answer));
    // Limit the redirects to 1, since there are two, this should fail.
    http.getClient().setMaxRetransmits(1);
    try {
        answer = tarpin.sayHi();
        fail("Unexpected answer from Tarpin: " + answer);
    } catch (Exception e) {
    // e.printStackTrace();
    }
    assertProxyRequestCount(0);
    // Set back to unlimited.
    http.getClient().setMaxRetransmits(-1);
    // Effectively we will not trust Gordy in the middle.
    trustDecider = new MyHttpsTrustDecider(new String[] { "Tarpin", "Bethal" });
    http.setTrustDecider(trustDecider);
    try {
        answer = tarpin.sayHi();
        fail("Unexpected answer from Tarpin: " + answer);
    } catch (Exception e) {
        // e.printStackTrace();
        assertTrue("Trust Decider wasn't called correctly", 2 == trustDecider.wasCalled());
    }
    assertProxyRequestCount(0);
}
Also used : SOAPService(org.apache.hello_world.services.SOAPService) HTTPConduit(org.apache.cxf.transport.http.HTTPConduit) AuthorizationPolicy(org.apache.cxf.configuration.security.AuthorizationPolicy) Greeter(org.apache.hello_world.Greeter) HTTPClientPolicy(org.apache.cxf.transports.http.configuration.HTTPClientPolicy) Client(org.apache.cxf.endpoint.Client) URL(java.net.URL) GeneralSecurityException(java.security.GeneralSecurityException) UntrustedURLConnectionIOException(org.apache.cxf.transport.http.UntrustedURLConnectionIOException) IOException(java.io.IOException) Test(org.junit.Test)

Example 64 with AuthorizationPolicy

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

the class CxfEndpoint method setupClientFactoryBean.

protected void setupClientFactoryBean(ClientFactoryBean factoryBean, Class<?> cls) {
    if (cls != null) {
        factoryBean.setServiceClass(cls);
    }
    factoryBean.setInInterceptors(in);
    factoryBean.setOutInterceptors(out);
    factoryBean.setOutFaultInterceptors(outFault);
    factoryBean.setInFaultInterceptors(inFault);
    factoryBean.setFeatures(features);
    factoryBean.setTransportId(transportId);
    factoryBean.setBindingId(bindingId);
    if (bindingConfig != null) {
        factoryBean.setBindingConfig(bindingConfig);
    }
    if (dataBinding != null) {
        factoryBean.setDataBinding(dataBinding);
    }
    if (serviceFactoryBean != null) {
        setServiceFactory(factoryBean, serviceFactoryBean);
    }
    // address
    factoryBean.setAddress(getAddress());
    // wsdl url
    if (getWsdlURL() != null) {
        factoryBean.setWsdlURL(getWsdlURL());
    }
    // service name qname
    if (getServiceName() != null) {
        factoryBean.setServiceName(getServiceName());
    }
    // port name qname
    if (getPortName() != null) {
        factoryBean.setEndpointName(getPortName());
    }
    // apply feature here
    if (getDataFormat().dealias() == DataFormat.RAW) {
        RAWDataFormatFeature feature = new RAWDataFormatFeature();
        feature.addInIntercepters(getInInterceptors());
        feature.addOutInterceptors(getOutInterceptors());
        factoryBean.getFeatures().add(feature);
    } else if (getDataFormat().dealias() == DataFormat.CXF_MESSAGE) {
        factoryBean.getFeatures().add(new CXFMessageDataFormatFeature());
        factoryBean.setDataBinding(new SourceDataBinding());
    } else if (getDataFormat() == DataFormat.PAYLOAD) {
        factoryBean.getFeatures().add(new PayLoadDataFormatFeature(allowStreaming));
        factoryBean.setDataBinding(new HybridSourceDataBinding());
    }
    if (isLoggingFeatureEnabled()) {
        if (getLoggingSizeLimit() != 0) {
            factoryBean.getFeatures().add(new LoggingFeature(getLoggingSizeLimit()));
        } else {
            factoryBean.getFeatures().add(new LoggingFeature());
        }
    }
    // set the document-literal wrapped style
    if (getWrappedStyle() != null) {
        setWrapped(factoryBean, getWrappedStyle());
    }
    // any optional properties
    if (getProperties() != null) {
        if (factoryBean.getProperties() != null) {
            // add to existing properties
            factoryBean.getProperties().putAll(getProperties());
        } else {
            factoryBean.setProperties(getProperties());
        }
        LOG.debug("ClientFactoryBean: {} added properties: {}", factoryBean, getProperties());
    }
    // setup the basic authentication property
    if (ObjectHelper.isNotEmpty(username)) {
        AuthorizationPolicy authPolicy = new AuthorizationPolicy();
        authPolicy.setUserName(username);
        authPolicy.setPassword(password);
        if (factoryBean.getProperties() == null) {
            factoryBean.setProperties(new HashMap<String, Object>());
        }
        factoryBean.getProperties().put(AuthorizationPolicy.class.getName(), authPolicy);
    }
    if (this.isSkipPayloadMessagePartCheck()) {
        if (factoryBean.getProperties() == null) {
            factoryBean.setProperties(new HashMap<String, Object>());
        }
        factoryBean.getProperties().put("soap.no.validate.parts", Boolean.TRUE);
    }
    if (this.isSkipFaultLogging()) {
        if (factoryBean.getProperties() == null) {
            factoryBean.setProperties(new HashMap<String, Object>());
        }
        factoryBean.getProperties().put(FaultListener.class.getName(), new NullFaultListener());
    }
    factoryBean.setBus(getBus());
    getNullSafeCxfEndpointConfigurer().configure(factoryBean);
}
Also used : AuthorizationPolicy(org.apache.cxf.configuration.security.AuthorizationPolicy) RAWDataFormatFeature(org.apache.camel.component.cxf.feature.RAWDataFormatFeature) LoggingFeature(org.apache.cxf.feature.LoggingFeature) PayLoadDataFormatFeature(org.apache.camel.component.cxf.feature.PayLoadDataFormatFeature) FaultListener(org.apache.cxf.logging.FaultListener) CXFMessageDataFormatFeature(org.apache.camel.component.cxf.feature.CXFMessageDataFormatFeature) SourceDataBinding(org.apache.cxf.databinding.source.SourceDataBinding)

Example 65 with AuthorizationPolicy

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

the class AbstractAuthFilter method handleOAuthRequest.

/**
 * Authenticates the third-party consumer and returns
 * {@link OAuthInfo} bean capturing the information about the request.
 * @param req http request
 * @return OAuth info
 * @see OAuthInfo
 * @throws Exception
 * @throws OAuthProblemException
 */
protected OAuthInfo handleOAuthRequest(HttpServletRequest req) throws Exception, OAuthProblemException {
    if (LOG.isLoggable(Level.FINE)) {
        LOG.log(Level.FINE, "OAuth security filter for url: {0}", req.getRequestURL());
    }
    AccessToken accessToken = null;
    Client client = null;
    OAuthMessage oAuthMessage = OAuthServlet.getMessage(new CustomHttpServletWrapper(req), OAuthServlet.getRequestURL(req));
    if (oAuthMessage.getParameter(OAuth.OAUTH_TOKEN) != null) {
        oAuthMessage.requireParameters(REQUIRED_PARAMETERS);
        accessToken = dataProvider.getAccessToken(oAuthMessage.getToken());
        // check if access token is not null
        if (accessToken == null) {
            LOG.warning("Access token is unavailable");
            throw new OAuthProblemException(OAuth.Problems.TOKEN_REJECTED);
        }
        client = accessToken.getClient();
        OAuthUtils.validateMessage(oAuthMessage, client, accessToken, dataProvider, validator);
    } else {
        String consumerKey = null;
        String consumerSecret = null;
        String authHeader = oAuthMessage.getHeader("Authorization");
        if (authHeader != null) {
            if (authHeader.startsWith("OAuth")) {
                consumerKey = oAuthMessage.getParameter(OAuth.OAUTH_CONSUMER_KEY);
                consumerSecret = oAuthMessage.getParameter(OAuthConstants.OAUTH_CONSUMER_SECRET);
            } else if (authHeader.startsWith("Basic")) {
                AuthorizationPolicy policy = getAuthorizationPolicy(authHeader);
                if (policy != null) {
                    consumerKey = policy.getUserName();
                    consumerSecret = policy.getPassword();
                }
            }
        }
        if (consumerKey != null) {
            client = dataProvider.getClient(consumerKey);
        }
        if (client == null) {
            LOG.warning("Client is invalid");
            throw new OAuthProblemException(OAuth.Problems.CONSUMER_KEY_UNKNOWN);
        }
        if (consumerSecret != null && !consumerSecret.equals(client.getSecretKey())) {
            LOG.warning("Client secret is invalid");
            throw new OAuthProblemException(OAuth.Problems.CONSUMER_KEY_UNKNOWN);
        }
        OAuthUtils.validateMessage(oAuthMessage, client, null, dataProvider, validator);
        accessToken = client.getPreAuthorizedToken();
        if (accessToken == null || !accessToken.isPreAuthorized()) {
            LOG.warning("Preauthorized access token is unavailable");
            throw new OAuthProblemException(OAuth.Problems.TOKEN_REJECTED);
        }
    }
    List<OAuthPermission> permissions = accessToken.getScopes();
    List<OAuthPermission> matchingPermissions = new ArrayList<>();
    for (OAuthPermission perm : permissions) {
        boolean uriOK = checkRequestURI(req, perm.getUris());
        boolean verbOK = checkHttpVerb(req, perm.getHttpVerbs());
        if (uriOK && verbOK) {
            matchingPermissions.add(perm);
        }
    }
    if (!permissions.isEmpty() && matchingPermissions.isEmpty()) {
        String message = "Client has no valid permissions";
        LOG.warning(message);
        throw new OAuthProblemException(message);
    }
    return new OAuthInfo(accessToken, matchingPermissions);
}
Also used : OAuthProblemException(net.oauth.OAuthProblemException) AuthorizationPolicy(org.apache.cxf.configuration.security.AuthorizationPolicy) OAuthPermission(org.apache.cxf.rs.security.oauth.data.OAuthPermission) OAuthMessage(net.oauth.OAuthMessage) AccessToken(org.apache.cxf.rs.security.oauth.data.AccessToken) ArrayList(java.util.ArrayList) Client(org.apache.cxf.rs.security.oauth.data.Client)

Aggregations

AuthorizationPolicy (org.apache.cxf.configuration.security.AuthorizationPolicy)86 Message (org.apache.cxf.message.Message)25 Test (org.junit.Test)22 HTTPConduit (org.apache.cxf.transport.http.HTTPConduit)16 IOException (java.io.IOException)15 ArrayList (java.util.ArrayList)11 Client (org.apache.cxf.endpoint.Client)11 List (java.util.List)9 HTTPClientPolicy (org.apache.cxf.transports.http.configuration.HTTPClientPolicy)9 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 TLSClientParameters (org.apache.cxf.configuration.jsse.TLSClientParameters)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