Java Code Examples for org.apache.tomcat.util.descriptor.web.SecurityConstraint#addCollection()

The following examples show how to use org.apache.tomcat.util.descriptor.web.SecurityConstraint#addCollection() . 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: HttpsConfiguration.java    From nbp with Apache License 2.0 7 votes vote down vote up
@Bean
public ServletWebServerFactory servletContainer() {
    TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() {
        @Override
        protected void postProcessContext(Context context) {
            SecurityConstraint securityConstraint = new SecurityConstraint();
            securityConstraint.setUserConstraint("CONFIDENTIAL");
            SecurityCollection collection = new SecurityCollection();
            collection.addPattern("/*");
            securityConstraint.addCollection(collection);
            context.addConstraint(securityConstraint);
        }
    };
    tomcat.addAdditionalTomcatConnectors(redirectConnector());
    return tomcat;
}
 
Example 2
Source File: TomcatHttpConfig.java    From Java-API-Test-Examples with Apache License 2.0 7 votes vote down vote up
/**
 * 配置内置的Servlet容器工厂为Tomcat
 * @return
 */
@Bean
public ServletWebServerFactory servletContainer() {
	TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() {
		@Override
		protected void postProcessContext(Context context) {
			SecurityConstraint securityConstraint = new SecurityConstraint();
			securityConstraint.setUserConstraint("CONFIDENTIAL");
			SecurityCollection collection = new SecurityCollection();
			collection.addPattern("/*");
			securityConstraint.addCollection(collection);
			context.addConstraint(securityConstraint);
		}
	};
	//添加配置信息,主要是Http的配置信息
	tomcat.addAdditionalTomcatConnectors(redirectConnector());
	return tomcat;
}
 
Example 3
Source File: SslConfig.java    From spring-boot-cookbook with Apache License 2.0 6 votes vote down vote up
@Bean
public EmbeddedServletContainerFactory servletContainer() {
    TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory() {
        @Override
        protected void postProcessContext(Context context) {
            // SecurityConstraint必须存在,可以通过其为不同的URL设置不同的重定向策略。
            SecurityConstraint constraint = new SecurityConstraint();
            constraint.setUserConstraint("CONFIDENTIAL");
            SecurityCollection collection = new SecurityCollection();
            collection.addPattern("/*");
            constraint.addCollection(collection);
            context.addConstraint(constraint);
        }
    };
    tomcat.addAdditionalTomcatConnectors(httpConnector());
    return tomcat;
}
 
Example 4
Source File: MaxKeySslConfig.java    From MaxKey with Apache License 2.0 6 votes vote down vote up
@Bean
public TomcatServletWebServerFactory tomcatServletWebServerFactory(Connector connector) {
    TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() {
        @Override
        protected void postProcessContext(Context context) {
            SecurityConstraint securityConstraint = new SecurityConstraint();
            securityConstraint.setUserConstraint("CONFIDENTIAL");
            SecurityCollection collection = new SecurityCollection();
            collection.addPattern("/*");
            securityConstraint.addCollection(collection);
            context.addConstraint(securityConstraint);
        }
    };
    tomcat.addAdditionalTomcatConnectors(connector);
    return tomcat;
}
 
Example 5
Source File: WebConfig.java    From jcart with MIT License 6 votes vote down vote up
@Bean
public EmbeddedServletContainerFactory servletContainer()
{
	TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory()
	{
		@Override
		protected void postProcessContext(Context context)
		{
			SecurityConstraint securityConstraint = new SecurityConstraint();
			securityConstraint.setUserConstraint("CONFIDENTIAL");
			SecurityCollection collection = new SecurityCollection();
			collection.addPattern("/*");
			securityConstraint.addCollection(collection);
			context.addConstraint(securityConstraint);
		}
	};

	tomcat.addAdditionalTomcatConnectors(initiateHttpConnector());
	return tomcat;
}
 
Example 6
Source File: SystemConfiguration.java    From NFVO with Apache License 2.0 6 votes vote down vote up
@Bean
public EmbeddedServletContainerFactory servletContainer() {
  if (https) {
    TomcatEmbeddedServletContainerFactory tomcat =
        new TomcatEmbeddedServletContainerFactory() {
          @Override
          protected void postProcessContext(Context context) {
            SecurityConstraint securityConstraint = new SecurityConstraint();
            securityConstraint.setUserConstraint("CONFIDENTIAL");
            SecurityCollection collection = new SecurityCollection();
            collection.addPattern("/*");
            securityConstraint.addCollection(collection);
            context.addConstraint(securityConstraint);
          }
        };

    tomcat.addAdditionalTomcatConnectors(initiateHttpConnector());
    return tomcat;
  }
  return new TomcatEmbeddedServletContainerFactory();
}
 
Example 7
Source File: WebConfig.java    From jcart with MIT License 6 votes vote down vote up
@Bean
public EmbeddedServletContainerFactory servletContainer() {
	TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory() {
		@Override
		protected void postProcessContext(Context context) {
			SecurityConstraint securityConstraint = new SecurityConstraint();
			securityConstraint.setUserConstraint("CONFIDENTIAL");
			SecurityCollection collection = new SecurityCollection();
			collection.addPattern("/*");
			securityConstraint.addCollection(collection);
			context.addConstraint(securityConstraint);
		}
	};

	tomcat.addAdditionalTomcatConnectors(initiateHttpConnector());
	return tomcat;
}
 
Example 8
Source File: HttpsConfig.java    From spring-boot-demo with MIT License 6 votes vote down vote up
@Bean
public TomcatServletWebServerFactory tomcatServletWebServerFactory(Connector connector) {
    TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() {
        @Override
        protected void postProcessContext(Context context) {
            SecurityConstraint securityConstraint = new SecurityConstraint();
            securityConstraint.setUserConstraint("CONFIDENTIAL");
            SecurityCollection collection = new SecurityCollection();
            collection.addPattern("/*");
            securityConstraint.addCollection(collection);
            context.addConstraint(securityConstraint);
        }
    };
    tomcat.addAdditionalTomcatConnectors(connector);
    return tomcat;
}
 
Example 9
Source File: TestDigestAuthenticator.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Override
public void setUp() throws Exception {
    super.setUp();

    // Configure a context with digest auth and a single protected resource
    Tomcat tomcat = getTomcatInstance();

    // No file system docBase required
    Context ctxt = tomcat.addContext(CONTEXT_PATH, null);

    // Add protected servlet
    Tomcat.addServlet(ctxt, "TesterServlet", new TesterServlet());
    ctxt.addServletMappingDecoded(URI, "TesterServlet");
    SecurityCollection collection = new SecurityCollection();
    collection.addPatternDecoded(URI);
    SecurityConstraint sc = new SecurityConstraint();
    sc.addAuthRole(ROLE);
    sc.addCollection(collection);
    ctxt.addConstraint(sc);

    // Configure the Realm
    TesterMapRealm realm = new TesterMapRealm();
    realm.addUser(USER, PWD);
    realm.addUserRole(USER, ROLE);
    ctxt.setRealm(realm);

    // Configure the authenticator
    LoginConfig lc = new LoginConfig();
    lc.setAuthMethod("DIGEST");
    lc.setRealmName(REALM);
    ctxt.setLoginConfig(lc);
    ctxt.getPipeline().addValve(new DigestAuthenticator());
}
 
Example 10
Source File: TestWebSocketFrameClient.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Test
public void testConnectToBasicEndpoint() throws Exception {

    Tomcat tomcat = getTomcatInstance();
    Context ctx = tomcat.addContext(URI_PROTECTED, null);
    ctx.addApplicationListener(TesterEchoServer.Config.class.getName());
    Tomcat.addServlet(ctx, "default", new DefaultServlet());
    ctx.addServletMappingDecoded("/", "default");

    SecurityCollection collection = new SecurityCollection();
    collection.addPatternDecoded("/");
    String utf8User = "test";
    String utf8Pass = "123\u00A3"; // pound sign

    tomcat.addUser(utf8User, utf8Pass);
    tomcat.addRole(utf8User, ROLE);

    SecurityConstraint sc = new SecurityConstraint();
    sc.addAuthRole(ROLE);
    sc.addCollection(collection);
    ctx.addConstraint(sc);

    LoginConfig lc = new LoginConfig();
    lc.setAuthMethod("BASIC");
    ctx.setLoginConfig(lc);

    AuthenticatorBase basicAuthenticator = new org.apache.catalina.authenticator.BasicAuthenticator();
    ctx.getPipeline().addValve(basicAuthenticator);

    tomcat.start();

    ClientEndpointConfig clientEndpointConfig = ClientEndpointConfig.Builder.create().build();
    clientEndpointConfig.getUserProperties().put(Constants.WS_AUTHENTICATION_USER_NAME, utf8User);
    clientEndpointConfig.getUserProperties().put(Constants.WS_AUTHENTICATION_PASSWORD, utf8Pass);

    echoTester(URI_PROTECTED, clientEndpointConfig);

}
 
Example 11
Source File: TestRestCsrfPreventionFilter2.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
private void setUpApplication() throws Exception {
    context = tomcat.addContext(CONTEXT_PATH_LOGIN, System.getProperty("java.io.tmpdir"));
    context.setSessionTimeout(SHORT_SESSION_TIMEOUT_MINS);

    Tomcat.addServlet(context, SERVLET_NAME, new TesterServlet());
    context.addServletMappingDecoded(URI_PROTECTED, SERVLET_NAME);

    FilterDef filterDef = new FilterDef();
    filterDef.setFilterName(FILTER_NAME);
    filterDef.setFilterClass(RestCsrfPreventionFilter.class.getCanonicalName());
    filterDef.addInitParameter(FILTER_INIT_PARAM, REMOVE_CUSTOMER + "," + ADD_CUSTOMER);
    context.addFilterDef(filterDef);

    FilterMap filterMap = new FilterMap();
    filterMap.setFilterName(FILTER_NAME);
    filterMap.addURLPatternDecoded(URI_CSRF_PROTECTED);
    context.addFilterMap(filterMap);

    SecurityCollection collection = new SecurityCollection();
    collection.addPatternDecoded(URI_PROTECTED);

    SecurityConstraint sc = new SecurityConstraint();
    sc.addAuthRole(ROLE);
    sc.addCollection(collection);
    context.addConstraint(sc);

    LoginConfig lc = new LoginConfig();
    lc.setAuthMethod(METHOD);
    context.setLoginConfig(lc);

    AuthenticatorBase basicAuthenticator = new BasicAuthenticator();
    context.getPipeline().addValve(basicAuthenticator);
}
 
Example 12
Source File: TestAuthInfoResponseHeaders.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Override
public void setUp() throws Exception {
    super.setUp();

    // Configure a context with digest auth and a single protected resource
    Tomcat tomcat = getTomcatInstance();
    tomcat.getHost().getPipeline().addValve(new RemoteIpValve());

    // No file system docBase required
    Context ctxt = tomcat.addContext(CONTEXT_PATH, null);

    // Add protected servlet
    Tomcat.addServlet(ctxt, "TesterServlet", new TesterServlet());
    ctxt.addServletMappingDecoded(URI, "TesterServlet");
    SecurityCollection collection = new SecurityCollection();
    collection.addPatternDecoded(URI);
    SecurityConstraint sc = new SecurityConstraint();
    sc.addAuthRole(ROLE);
    sc.addCollection(collection);
    ctxt.addConstraint(sc);

    // Configure the Realm
    TesterMapRealm realm = new TesterMapRealm();
    realm.addUser(USER, PWD);
    realm.addUserRole(USER, ROLE);
    ctxt.setRealm(realm);

    // Configure the authenticator
    LoginConfig lc = new LoginConfig();
    lc.setAuthMethod(HttpServletRequest.BASIC_AUTH);
    ctxt.setLoginConfig(lc);
    ctxt.getPipeline().addValve(new BasicAuthenticator());
}
 
Example 13
Source File: TestNonLoginAndBasicAuthenticator.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
private void setUpNonLogin() throws Exception {

        // Must have a real docBase for webapps - just use temp
        nonloginContext = tomcat.addContext(CONTEXT_PATH_NOLOGIN,
                System.getProperty("java.io.tmpdir"));

        // Add protected servlet to the context
        Tomcat.addServlet(nonloginContext, "TesterServlet1", new TesterServlet());
        nonloginContext.addServletMappingDecoded(URI_PROTECTED, "TesterServlet1");

        SecurityCollection collection1 = new SecurityCollection();
        collection1.addPatternDecoded(URI_PROTECTED);
        SecurityConstraint sc1 = new SecurityConstraint();
        sc1.addAuthRole(ROLE);
        sc1.addCollection(collection1);
        nonloginContext.addConstraint(sc1);

        // Add unprotected servlet to the context
        Tomcat.addServlet(nonloginContext, "TesterServlet2", new TesterServlet());
        nonloginContext.addServletMappingDecoded(URI_PUBLIC, "TesterServlet2");

        SecurityCollection collection2 = new SecurityCollection();
        collection2.addPatternDecoded(URI_PUBLIC);
        SecurityConstraint sc2 = new SecurityConstraint();
        // do not add a role - which signals access permitted without one
        sc2.addCollection(collection2);
        nonloginContext.addConstraint(sc2);

        // Configure the authenticator and inherit the Realm from Engine
        LoginConfig lc = new LoginConfig();
        lc.setAuthMethod("NONE");
        nonloginContext.setLoginConfig(lc);
        AuthenticatorBase nonloginAuthenticator = new NonLoginAuthenticator();
        nonloginContext.getPipeline().addValve(nonloginAuthenticator);
    }
 
Example 14
Source File: TestSSOnonLoginAndBasicAuthenticator.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
private void setUpLogin() throws Exception {

        // Must have a real docBase for webapps - just use temp
        basicContext = tomcat.addContext(CONTEXT_PATH_LOGIN,
                System.getProperty("java.io.tmpdir"));
        basicContext.setSessionTimeout(SHORT_SESSION_TIMEOUT_MINS);

        // Add protected servlet to the context
        Tomcat.addServlet(basicContext, "TesterServlet3",
                new TesterServletEncodeUrl());
        basicContext.addServletMappingDecoded(URI_PROTECTED, "TesterServlet3");
        SecurityCollection collection = new SecurityCollection();
        collection.addPatternDecoded(URI_PROTECTED);
        SecurityConstraint sc = new SecurityConstraint();
        sc.addAuthRole(ROLE);
        sc.addCollection(collection);
        basicContext.addConstraint(sc);

        // Add unprotected servlet to the context
        Tomcat.addServlet(basicContext, "TesterServlet4",
                new TesterServletEncodeUrl());
        basicContext.addServletMappingDecoded(URI_PUBLIC, "TesterServlet4");
        SecurityCollection collection2 = new SecurityCollection();
        collection2.addPatternDecoded(URI_PUBLIC);
        SecurityConstraint sc2 = new SecurityConstraint();
        // do not add a role - which signals access permitted without one
        sc2.addCollection(collection2);
        basicContext.addConstraint(sc2);

        // Configure the authenticator and inherit the Realm from Engine
        LoginConfig lc = new LoginConfig();
        lc.setAuthMethod("BASIC");
        basicContext.setLoginConfig(lc);
        AuthenticatorBase basicAuthenticator = new BasicAuthenticator();
        basicContext.getPipeline().addValve(basicAuthenticator);
    }
 
Example 15
Source File: TestSSOnonLoginAndBasicAuthenticator.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
private void setUpNonLogin() throws Exception {

        // Must have a real docBase for webapps - just use temp
        nonloginContext = tomcat.addContext(CONTEXT_PATH_NOLOGIN,
                System.getProperty("java.io.tmpdir"));
        nonloginContext.setSessionTimeout(LONG_SESSION_TIMEOUT_MINS);

        // Add protected servlet to the context
        Tomcat.addServlet(nonloginContext, "TesterServlet1",
                new TesterServletEncodeUrl());
        nonloginContext.addServletMappingDecoded(URI_PROTECTED, "TesterServlet1");

        SecurityCollection collection1 = new SecurityCollection();
        collection1.addPatternDecoded(URI_PROTECTED);
        SecurityConstraint sc1 = new SecurityConstraint();
        sc1.addAuthRole(ROLE);
        sc1.addCollection(collection1);
        nonloginContext.addConstraint(sc1);

        // Add unprotected servlet to the context
        Tomcat.addServlet(nonloginContext, "TesterServlet2",
                new TesterServletEncodeUrl());
        nonloginContext.addServletMappingDecoded(URI_PUBLIC, "TesterServlet2");

        SecurityCollection collection2 = new SecurityCollection();
        collection2.addPatternDecoded(URI_PUBLIC);
        SecurityConstraint sc2 = new SecurityConstraint();
        // do not add a role - which signals access permitted without one
        sc2.addCollection(collection2);
        nonloginContext.addConstraint(sc2);

        // Configure the authenticator and inherit the Realm from Engine
        LoginConfig lc = new LoginConfig();
        lc.setAuthMethod("NONE");
        nonloginContext.setLoginConfig(lc);
        AuthenticatorBase nonloginAuthenticator = new NonLoginAuthenticator();
        nonloginContext.getPipeline().addValve(nonloginAuthenticator);
    }
 
Example 16
Source File: TestMapperWebapps.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
@Test
public void testRedirect() throws Exception {
    Tomcat tomcat = getTomcatInstance();

    // Use standard test webapp as ROOT
    File rootDir = new File("test/webapp");
    org.apache.catalina.Context root =
            tomcat.addWebapp(null, "", rootDir.getAbsolutePath());

    // Add a security constraint
    SecurityConstraint constraint = new SecurityConstraint();
    SecurityCollection collection = new SecurityCollection();
    collection.addPatternDecoded("/welcome-files/*");
    collection.addPatternDecoded("/welcome-files");
    constraint.addCollection(collection);
    constraint.addAuthRole("foo");
    root.addConstraint(constraint);

    // Also make examples available
    File examplesDir = new File(getBuildDirectory(), "webapps/examples");
    org.apache.catalina.Context examples  = tomcat.addWebapp(
            null, "/examples", examplesDir.getAbsolutePath());
    examples.setMapperContextRootRedirectEnabled(false);
    // Then block access to the examples to test redirection
    RemoteAddrValve rav = new RemoteAddrValve();
    rav.setDeny(".*");
    rav.setDenyStatus(404);
    examples.getPipeline().addValve(rav);

    tomcat.start();

    // Redirects within a web application
    doRedirectTest("/welcome-files", 401);
    doRedirectTest("/welcome-files/", 401);

    doRedirectTest("/jsp", 302);
    doRedirectTest("/jsp/", 404);

    doRedirectTest("/WEB-INF", 404);
    doRedirectTest("/WEB-INF/", 404);

    // Redirects between web applications
    doRedirectTest("/examples", 404);
    doRedirectTest("/examples/", 404);
}
 
Example 17
Source File: HttpServer.java    From guardedbox with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * Bean: ServletWebServerFactory.
 * Creates a dual port Tomcat, listening both in an http port and an https port. The http port simply redirects to the https one.
 *
 * @return TomcatServletWebServerFactory.
 */
@Bean
public ServletWebServerFactory servletWebServerFactory() {

    // Check if there is dual port configuration.
    if (serverProperties.getInternalHttpPort() == null
            || serverProperties.getExternalHttpPort() == null
            || serverProperties.getInternalHttpsPort() == null
            || serverProperties.getExternalHttpsPort() == null
            || serverProperties.getPort().equals(serverProperties.getInternalHttpPort())
            || !serverProperties.getPort().equals(serverProperties.getInternalHttpsPort())) {
        return new TomcatServletWebServerFactory();
    }

    // Set TLS ECDH offered curves.
    if (!StringUtils.isEmpty(sslProperties.getEcdhCurves()))
        System.setProperty(JdkProperty.TLS_ECDH_CURVES.getPropertyName(), sslProperties.getEcdhCurves());

    // Enable TLS OCSP stapling.
    if (sslProperties.getEnableOcspStapling() != null)
        System.setProperty(JdkProperty.TLS_ENABLE_OCSP_STAPLING.getPropertyName(), sslProperties.getEnableOcspStapling().toString());

    // Create the https Tomcat.
    TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() {

        @Override
        protected void postProcessContext(
                Context context) {

            SecurityConstraint securityConstraint = new SecurityConstraint();
            securityConstraint.setUserConstraint("CONFIDENTIAL");
            SecurityCollection collection = new SecurityCollection();
            collection.addPattern("/*");
            securityConstraint.addCollection(collection);
            context.addConstraint(securityConstraint);

        }

    };

    // Customize the https connector.
    tomcat.addConnectorCustomizers(new TomcatConnectorCustomizer() {

        @Override
        public void customize(
                Connector connector) {

            SSLHostConfig sslHostConfig = connector.findSslHostConfigs()[0];
            sslHostConfig.setHonorCipherOrder(true);

        }

    });

    // Add the http connector with a redirection to the https port.
    Connector httpConnector = new Connector(TomcatServletWebServerFactory.DEFAULT_PROTOCOL);
    httpConnector.setScheme("http");
    httpConnector.setPort(serverProperties.getInternalHttpPort());
    httpConnector.setSecure(false);
    httpConnector.setRedirectPort(serverProperties.getExternalHttpsPort());
    tomcat.addAdditionalTomcatConnectors(httpConnector);

    return tomcat;

}
 
Example 18
Source File: TestHttp11Processor.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
private void doTestNon2xxResponseAndExpectation(boolean useExpectation) throws Exception {
    Tomcat tomcat = getTomcatInstance();

    // No file system docBase required
    Context ctx = tomcat.addContext("", null);

    Tomcat.addServlet(ctx, "echo", new EchoBodyServlet());
    ctx.addServletMappingDecoded("/echo", "echo");

    SecurityCollection collection = new SecurityCollection("All", "");
    collection.addPatternDecoded("/*");
    SecurityConstraint constraint = new SecurityConstraint();
    constraint.addAuthRole("Any");
    constraint.addCollection(collection);
    ctx.addConstraint(constraint);

    tomcat.start();

    String request =
            "POST /echo HTTP/1.1" + SimpleHttpClient.CRLF +
            "Host: localhost:" + getPort() + SimpleHttpClient.CRLF;
    if (useExpectation) {
        request += "Expect: 100-continue" + SimpleHttpClient.CRLF;
    }
    request += SimpleHttpClient.CRLF +
               "HelloWorld";

    Client client = new Client(tomcat.getConnector().getLocalPort());
    client.setRequest(new String[] {request});

    client.connect();
    client.processRequest();

    Assert.assertTrue(client.isResponse403());
    String connectionHeaderValue = null;
    for (String header : client.getResponseHeaders()) {
        if (header.startsWith("Connection:")) {
            connectionHeaderValue = header.substring(header.indexOf(':') + 1).trim();
            break;
        }
    }

    if (useExpectation) {
        List<String> connectionHeaders = new ArrayList<>();
        TokenList.parseTokenList(new StringReader(connectionHeaderValue), connectionHeaders);
        Assert.assertEquals(1, connectionHeaders.size());
        Assert.assertEquals("close", connectionHeaders.get(0));
    } else {
        Assert.assertNull(connectionHeaderValue);
    }
}
 
Example 19
Source File: TestFormAuthenticator.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
private FormAuthClientSelectedMethods(boolean clientShouldUseCookies,
        boolean clientShouldUseHttp11,
        boolean serverShouldUseCookies,
        boolean serverShouldChangeSessid) throws Exception {

    this.clientShouldUseHttp11 = clientShouldUseHttp11;

    Tomcat tomcat = getTomcatInstance();

    Context ctx = tomcat.addContext(
            "", System.getProperty("java.io.tmpdir"));
    Tomcat.addServlet(ctx, "SelectedMethods",
            new SelectedMethodsServlet());
    ctx.addServletMappingDecoded("/test", "SelectedMethods");
    // Login servlet just needs to respond "OK". Client will handle
    // creating a valid response. No need for a form.
    Tomcat.addServlet(ctx, "Login",
            new TesterServlet());
    ctx.addServletMappingDecoded("/login", "Login");

    // Configure the security constraints
    SecurityConstraint constraint = new SecurityConstraint();
    SecurityCollection collection = new SecurityCollection();
    collection.setName("Protect PUT");
    collection.addMethod("PUT");
    collection.addPatternDecoded("/test");
    constraint.addCollection(collection);
    constraint.addAuthRole("tomcat");
    ctx.addConstraint(constraint);

    // Configure authentication
    LoginConfig lc = new LoginConfig();
    lc.setAuthMethod("FORM");
    lc.setLoginPage("/login");
    ctx.setLoginConfig(lc);
    ctx.getPipeline().addValve(new FormAuthenticator());

    setUseCookies(clientShouldUseCookies);
    ctx.setCookies(serverShouldUseCookies);

    TesterMapRealm realm = new TesterMapRealm();
    realm.addUser("tomcat", "tomcat");
    realm.addUserRole("tomcat", "tomcat");
    ctx.setRealm(realm);

    tomcat.start();

    // Valve pipeline is only established after tomcat starts
    Valve[] valves = ctx.getPipeline().getValves();
    for (Valve valve : valves) {
        if (valve instanceof AuthenticatorBase) {
            ((AuthenticatorBase)valve)
                    .setChangeSessionIdOnAuthentication(
                                        serverShouldChangeSessid);
            break;
        }
    }

    // Port only known after Tomcat starts
    setPort(getPort());
}
 
Example 20
Source File: TomcatWsRegistry.java    From tomee with Apache License 2.0 4 votes vote down vote up
private static Context createNewContext(final ClassLoader classLoader, String authMethod, String transportGuarantee, final String realmName, final String name) {
    String path = name;
    if (path == null) {
        path = "/";
    }
    if (!path.startsWith("/")) {
        path = "/" + path;
    }

    final StandardContext context = new IgnoredStandardContext();
    context.setPath(path);
    context.setDocBase("");
    context.setParentClassLoader(classLoader);
    context.setDelegate(true);
    context.setName(name);
    ((TomcatWebAppBuilder) SystemInstance.get().getComponent(WebAppBuilder.class)).initJ2EEInfo(context);

    // Configure security
    if (authMethod != null) {
        authMethod = authMethod.toUpperCase();
    }
    if (transportGuarantee != null) {
        transportGuarantee = transportGuarantee.toUpperCase();
    }
    if (authMethod == null || "NONE".equals(authMethod)) { //NOPMD
        // ignore none for now as the  NonLoginAuthenticator seems to be completely hosed
    } else if ("BASIC".equals(authMethod) || "DIGEST".equals(authMethod) || "CLIENT-CERT".equals(authMethod)) {

        //Setup a login configuration
        final LoginConfig loginConfig = new LoginConfig();
        loginConfig.setAuthMethod(authMethod);
        loginConfig.setRealmName(realmName);
        context.setLoginConfig(loginConfig);

        //Setup a default Security Constraint
        final String securityRole = SystemInstance.get().getProperty(TOMEE_JAXWS_SECURITY_ROLE_PREFIX + name, "default");
        for (final String role : securityRole.split(",")) {
            final SecurityCollection collection = new SecurityCollection();
            collection.addMethod("GET");
            collection.addMethod("POST");
            collection.addPattern("/*");
            collection.setName(role);

            final SecurityConstraint sc = new SecurityConstraint();
            sc.addAuthRole("*");
            sc.addCollection(collection);
            sc.setAuthConstraint(true);
            sc.setUserConstraint(transportGuarantee);

            context.addConstraint(sc);
            context.addSecurityRole(role);
        }

        //Set the proper authenticator
        if ("BASIC".equals(authMethod)) {
            context.addValve(new BasicAuthenticator());
        } else if ("DIGEST".equals(authMethod)) {
            context.addValve(new DigestAuthenticator());
        } else if ("CLIENT-CERT".equals(authMethod)) {
            context.addValve(new SSLAuthenticator());
        } else if ("NONE".equals(authMethod)) {
            context.addValve(new NonLoginAuthenticator());
        }

        context.getPipeline().addValve(new OpenEJBValve());

    } else {
        throw new IllegalArgumentException("Invalid authMethod: " + authMethod);
    }

    return context;
}