Java Code Examples for org.apache.catalina.Context#addConstraint()

The following examples show how to use org.apache.catalina.Context#addConstraint() . 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: 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 2
Source File: TestSSOnonLoginAndDigestAuthenticator.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
private void setUpDigest(Tomcat tomcat) throws Exception {

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

        // Add protected servlet
        Tomcat.addServlet(ctxt, "TesterServlet3", new TesterServlet());
        ctxt.addServletMapping(URI_PROTECTED, "TesterServlet3");
        SecurityCollection collection = new SecurityCollection();
        collection.addPattern(URI_PROTECTED);
        SecurityConstraint sc = new SecurityConstraint();
        sc.addAuthRole(ROLE);
        sc.addCollection(collection);
        ctxt.addConstraint(sc);

        // Configure the appropriate authenticator
        LoginConfig lc = new LoginConfig();
        lc.setAuthMethod("DIGEST");
        ctxt.setLoginConfig(lc);
        ctxt.getPipeline().addValve(new DigestAuthenticator());
    }
 
Example 3
Source File: TestAbstractHttp11Processor.java    From Tomcat7.0.67 with Apache License 2.0 6 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.addServletMapping("/echo", "echo");

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

    tomcat.start();

    Non2xxResponseClient client = new Non2xxResponseClient(useExpectation);
    client.setPort(getPort());
    client.doResourceRequest("GET http://localhost:" + getPort()
            + "/echo HTTP/1.1", "HelloWorld");
    Assert.assertTrue(client.isResponse403());
    Assert.assertTrue(client.checkConnectionHeader());
}
 
Example 4
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 5
Source File: TestSSOnonLoginAndDigestAuthenticator.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
private void setUpDigest(Tomcat tomcat) throws Exception {

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

        // Add protected servlet
        Tomcat.addServlet(ctxt, "TesterServlet3", new TesterServlet());
        ctxt.addServletMapping(URI_PROTECTED, "TesterServlet3");
        SecurityCollection collection = new SecurityCollection();
        collection.addPattern(URI_PROTECTED);
        SecurityConstraint sc = new SecurityConstraint();
        sc.addAuthRole(ROLE);
        sc.addCollection(collection);
        ctxt.addConstraint(sc);

        // Configure the appropriate authenticator
        LoginConfig lc = new LoginConfig();
        lc.setAuthMethod("DIGEST");
        ctxt.setLoginConfig(lc);
        ctxt.getPipeline().addValve(new DigestAuthenticator());
    }
 
Example 6
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 7
Source File: SSLConfig.java    From NoteBlog with MIT License 6 votes vote down vote up
@Bean
public EmbeddedServletContainerFactory servletContainer() {
    TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory() {

        @Override
        protected void postProcessContext(Context context) {
            if (environment.getProperty("server.ssl.enabled", Boolean.class, Boolean.FALSE)) {
                SecurityConstraint constraint = new SecurityConstraint();
                constraint.setUserConstraint("CONFIDENTIAL");
                SecurityCollection collection = new SecurityCollection();
                collection.addPattern("/*");
                constraint.addCollection(collection);
                context.addConstraint(constraint);
            } else {
                super.postProcessContext(context);
            }
        }
    };
    if (environment.getProperty("server.ssl.enabled", Boolean.class, Boolean.FALSE)) {
        tomcat.addAdditionalTomcatConnectors(httpConnector());
    }
    return tomcat;
}
 
Example 8
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 9
Source File: TesterSupport.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
protected static void configureClientCertContext(Tomcat tomcat) {
    TesterSupport.initSsl(tomcat);

    // Need a web application with a protected and unprotected URL
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);

    Tomcat.addServlet(ctx, "simple", new SimpleServlet());
    ctx.addServletMapping("/unprotected", "simple");
    ctx.addServletMapping("/protected", "simple");

    // Security constraints
    SecurityCollection collection = new SecurityCollection();
    collection.addPattern("/protected");
    SecurityConstraint sc = new SecurityConstraint();
    sc.addAuthRole(ROLE);
    sc.addCollection(collection);
    ctx.addConstraint(sc);

    // Configure the Realm
    MapRealm realm = new MapRealm();
    realm.addUser("CN=user1, C=US", "not used");
    realm.addUserRole("CN=user1, C=US", ROLE);
    ctx.setRealm(realm);

    // Configure the authenticator
    LoginConfig lc = new LoginConfig();
    lc.setAuthMethod("CLIENT-CERT");
    ctx.setLoginConfig(lc);
    ctx.getPipeline().addValve(new SSLAuthenticator());
}
 
Example 10
Source File: TestSSOnonLoginAndDigestAuthenticator.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
private void setUpNonLogin(Tomcat tomcat) throws Exception {

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

        // Add protected servlet
        Tomcat.addServlet(ctxt, "TesterServlet1", new TesterServlet());
        ctxt.addServletMapping(URI_PROTECTED, "TesterServlet1");
        SecurityCollection collection1 = new SecurityCollection();
        collection1.addPattern(URI_PROTECTED);
        SecurityConstraint sc1 = new SecurityConstraint();
        sc1.addAuthRole(ROLE);
        sc1.addCollection(collection1);
        ctxt.addConstraint(sc1);

        // Add unprotected servlet
        Tomcat.addServlet(ctxt, "TesterServlet2", new TesterServlet());
        ctxt.addServletMapping(URI_PUBLIC, "TesterServlet2");
        SecurityCollection collection2 = new SecurityCollection();
        collection2.addPattern(URI_PUBLIC);
        SecurityConstraint sc2 = new SecurityConstraint();
        // do not add a role - which signals access permitted without one
        sc2.addCollection(collection2);
        ctxt.addConstraint(sc2);

        // Configure the appropriate authenticator
        LoginConfig lc = new LoginConfig();
        lc.setAuthMethod("NONE");
        ctxt.setLoginConfig(lc);
        ctxt.getPipeline().addValve(new NonLoginAuthenticator());
    }
 
Example 11
Source File: Http2Https.java    From springBoot with MIT License 5 votes vote down vote up
@Bean
public TomcatServletWebServerFactory servletContainerFactory() {
    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);
        }
    };
    Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
    //设置将分配给通过此连接器接收到的请求的方案
    connector.setScheme("http");

    //true: http使用http, https使用https;
    //false: http重定向到https;
    connector.setSecure(false);

    //设置监听请求的端口号,这个端口不能其他已经在使用的端口重复,否则会报错
    connector.setPort(httpPort);

    //重定向端口号(非SSL到SSL)
    connector.setRedirectPort(sslPort);

    tomcat.addAdditionalTomcatConnectors(connector);
    return tomcat;
}
 
Example 12
Source File: TestWebSocketFrameClient.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Test
public void testConnectToDigestEndpoint() 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("/*");

    tomcat.addUser(USER, PWD);
    tomcat.addRole(USER, ROLE);

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

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

    AuthenticatorBase digestAuthenticator = new org.apache.catalina.authenticator.DigestAuthenticator();
    ctx.getPipeline().addValve(digestAuthenticator);

    tomcat.start();

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

    echoTester(URI_PROTECTED, clientEndpointConfig);

}
 
Example 13
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 14
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 15
Source File: TestSSOnonLoginAndDigestAuthenticator.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
private void setUpNonLogin(Tomcat tomcat) throws Exception {

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

        // Add protected servlet
        Tomcat.addServlet(ctxt, "TesterServlet1", new TesterServlet());
        ctxt.addServletMapping(URI_PROTECTED, "TesterServlet1");
        SecurityCollection collection1 = new SecurityCollection();
        collection1.addPattern(URI_PROTECTED);
        SecurityConstraint sc1 = new SecurityConstraint();
        sc1.addAuthRole(ROLE);
        sc1.addCollection(collection1);
        ctxt.addConstraint(sc1);

        // Add unprotected servlet
        Tomcat.addServlet(ctxt, "TesterServlet2", new TesterServlet());
        ctxt.addServletMapping(URI_PUBLIC, "TesterServlet2");
        SecurityCollection collection2 = new SecurityCollection();
        collection2.addPattern(URI_PUBLIC);
        SecurityConstraint sc2 = new SecurityConstraint();
        // do not add a role - which signals access permitted without one
        sc2.addCollection(collection2);
        ctxt.addConstraint(sc2);

        // Configure the appropriate authenticator
        LoginConfig lc = new LoginConfig();
        lc.setAuthMethod("NONE");
        ctxt.setLoginConfig(lc);
        ctxt.getPipeline().addValve(new NonLoginAuthenticator());
    }
 
Example 16
Source File: Runner.java    From myrrix-recommender with Apache License 2.0 4 votes vote down vote up
private Context makeContext(Tomcat tomcat, File noSuchBaseDir, int port) throws IOException {

    File contextPath = new File(noSuchBaseDir, "context");
    if (!contextPath.mkdirs()) {
      throw new IOException("Could not create " + contextPath);
    }

    String contextPathURIBase = config.getContextPath();
    Context context = 
        tomcat.addContext(contextPathURIBase == null ? "" : contextPathURIBase, contextPath.getAbsolutePath());
    context.addApplicationListener(new ApplicationListener(InitListener.class.getName(), false));
    context.setWebappVersion("3.0");
    context.addWelcomeFile("index.jspx");
    addErrorPages(context);

    ServletContext servletContext = context.getServletContext();
    servletContext.setAttribute(InitListener.INSTANCE_ID_KEY, config.getInstanceID());
    servletContext.setAttribute(InitListener.BUCKET_KEY, config.getBucket());
    servletContext.setAttribute(InitListener.RESCORER_PROVIDER_CLASS_KEY, config.getRescorerProviderClassName());
    servletContext.setAttribute(InitListener.CLIENT_THREAD_CLASS_KEY, config.getClientThreadClassName());    
    servletContext.setAttribute(InitListener.LOCAL_INPUT_DIR_KEY, config.getLocalInputDir());
    servletContext.setAttribute(InitListener.PORT_KEY, port);
    servletContext.setAttribute(InitListener.READ_ONLY_KEY, config.isReadOnly());
    servletContext.setAttribute(InitListener.ALL_PARTITIONS_SPEC_KEY, config.getAllPartitionsSpecification());
    servletContext.setAttribute(InitListener.PARTITION_KEY, config.getPartition());

    boolean needHTTPS = config.getKeystoreFile() != null;
    boolean needAuthentication = config.getUserName() != null;

    if (needHTTPS || needAuthentication) {

      SecurityCollection securityCollection = new SecurityCollection("Protected Resources");
      if (config.isConsoleOnlyPassword()) {
        securityCollection.addPattern("/index.jspx");
      } else {
        securityCollection.addPattern("/*");
      }
      SecurityConstraint securityConstraint = new SecurityConstraint();
      securityConstraint.addCollection(securityCollection);

      if (needHTTPS) {
        securityConstraint.setUserConstraint("CONFIDENTIAL");
      }

      if (needAuthentication) {

        LoginConfig loginConfig = new LoginConfig();
        loginConfig.setAuthMethod("DIGEST");
        loginConfig.setRealmName(InMemoryRealm.NAME);
        context.setLoginConfig(loginConfig);

        securityConstraint.addAuthRole(InMemoryRealm.AUTH_ROLE);

        context.addSecurityRole(InMemoryRealm.AUTH_ROLE);
        DigestAuthenticator authenticator = new DigestAuthenticator();
        authenticator.setNonceValidity(10 * 1000L); // Shorten from 5 minutes to 10 seconds
        authenticator.setNonceCacheSize(20000); // Increase from 1000 to 20000
        context.getPipeline().addValve(authenticator);
      }

      context.addConstraint(securityConstraint);
    }

    context.setCookies(false);

    return context;
  }
 
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 Tomcat7.0.67 with Apache License 2.0 4 votes vote down vote up
private FormAuthClientSelectedMethods(boolean clientShouldUseCookies,
        boolean serverShouldUseCookies,
        boolean serverShouldChangeSessid) throws Exception {

    Tomcat tomcat = getTomcatInstance();

    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    Tomcat.addServlet(ctx, "SelectedMethods",
            new SelectedMethodsServlet());
    ctx.addServletMapping("/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.addServletMapping("/login", "Login");

    // Configure the security constraints
    SecurityConstraint constraint = new SecurityConstraint();
    SecurityCollection collection = new SecurityCollection();
    collection.setName("Protect PUT");
    collection.addMethod("PUT");
    collection.addPattern("/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);

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

    tomcat.start();

    // perhaps this does not work until tomcat has started?
    ctx.setSessionTimeout(TIMEOUT_MINS);

    // 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: 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());
}