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

The following examples show how to use org.apache.catalina.Context#setRealm() . 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: TestRequest.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
/**
 * Test case for {@link Request#login(String, String)} and
 * {@link Request#logout()}.
 */
@Test
public void testLoginLogout() throws Exception{
    // Setup Tomcat instance
    Tomcat tomcat = getTomcatInstance();

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

    LoginConfig config = new LoginConfig();
    config.setAuthMethod("BASIC");
    ctx.setLoginConfig(config);
    ctx.getPipeline().addValve(new BasicAuthenticator());

    Tomcat.addServlet(ctx, "servlet", new LoginLogoutServlet());
    ctx.addServletMapping("/", "servlet");

    MapRealm realm = new MapRealm();
    realm.addUser(LoginLogoutServlet.USER, LoginLogoutServlet.PWD);
    ctx.setRealm(realm);

    tomcat.start();

    ByteChunk res = getUrl("http://localhost:" + getPort() + "/");
    assertEquals(LoginLogoutServlet.OK, res.toString());
}
 
Example 2
Source File: TesterDigestAuthenticatorPerformance.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Before
public void setUp() throws Exception {

    ConcurrentMessageDigest.init("MD5");

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

    // Add the Realm to the Context
    Context context = new StandardContext();
    context.setName(CONTEXT_PATH);
    context.setRealm(realm);

    // Configure the Login config
    LoginConfig config = new LoginConfig();
    config.setRealmName(REALM);
    context.setLoginConfig(config);

    // Make the Context and Realm visible to the Authenticator
    authenticator.setContainer(context);
    authenticator.setNonceCountWindowSize(8 * 1024);

    authenticator.start();
}
 
Example 3
Source File: TestRequest.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Test
public void testLoginLogout() throws Exception{
    // Setup Tomcat instance
    Tomcat tomcat = getTomcatInstance();

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

    LoginConfig config = new LoginConfig();
    config.setAuthMethod("BASIC");
    ctx.setLoginConfig(config);
    ctx.getPipeline().addValve(new BasicAuthenticator());

    Tomcat.addServlet(ctx, "servlet", new LoginLogoutServlet());
    ctx.addServletMappingDecoded("/", "servlet");

    TesterMapRealm realm = new TesterMapRealm();
    realm.addUser(LoginLogoutServlet.USER, LoginLogoutServlet.PWD);
    ctx.setRealm(realm);

    tomcat.start();

    ByteChunk res = getUrl("http://localhost:" + getPort() + "/");
    Assert.assertEquals(LoginLogoutServlet.OK, res.toString());
}
 
Example 4
Source File: TestRequest.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
/**
 * Test case for {@link Request#login(String, String)} and
 * {@link Request#logout()}.
 */
@Test
public void testLoginLogout() throws Exception{
    // Setup Tomcat instance
    Tomcat tomcat = getTomcatInstance();

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

    LoginConfig config = new LoginConfig();
    config.setAuthMethod("BASIC");
    ctx.setLoginConfig(config);
    ctx.getPipeline().addValve(new BasicAuthenticator());

    Tomcat.addServlet(ctx, "servlet", new LoginLogoutServlet());
    ctx.addServletMapping("/", "servlet");

    MapRealm realm = new MapRealm();
    realm.addUser(LoginLogoutServlet.USER, LoginLogoutServlet.PWD);
    ctx.setRealm(realm);

    tomcat.start();

    ByteChunk res = getUrl("http://localhost:" + getPort() + "/");
    assertEquals(LoginLogoutServlet.OK, res.toString());
}
 
Example 5
Source File: TesterDigestAuthenticatorPerformance.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {

    ConcurrentMessageDigest.init("MD5");

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

    // Add the Realm to the Context
    Context context = new StandardContext();
    context.setName(CONTEXT_PATH);
    context.setRealm(realm);

    // Make the Context and Realm visible to the Authenticator
    authenticator.setContainer(context);
    authenticator.setNonceCountWindowSize(8 * 1024);

    authenticator.start();
}
 
Example 6
Source File: TestFormAuthenticator.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
private FormAuthClient(boolean clientShouldUseCookies,
        boolean clientShouldUseHttp11,
        boolean serverShouldUseCookies,
        boolean serverShouldChangeSessid) throws Exception {

    this.clientShouldUseHttp11 = clientShouldUseHttp11;

    Tomcat tomcat = getTomcatInstance();
    File appDir = new File(System.getProperty("tomcat.test.basedir"), "webapps/examples");
    Context ctx = tomcat.addWebapp(null, "/examples",
            appDir.getAbsolutePath());
    setUseCookies(clientShouldUseCookies);
    ctx.setCookies(serverShouldUseCookies);
    ctx.addApplicationListener(WsContextListener.class.getName());

    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 7
Source File: TesterSupport.java    From Tomcat7.0.67 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 8
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 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: 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 11
Source File: TestFormAuthenticator.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
private FormAuthClient(boolean clientShouldUseCookies,
        boolean serverShouldUseCookies,
        boolean serverShouldChangeSessid) throws Exception {

    Tomcat tomcat = getTomcatInstance();
    File appDir = new File(getBuildDirectory(), "webapps/examples");
    Context ctx = tomcat.addWebapp(null, "/examples",
            appDir.getAbsolutePath());
    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 12
Source File: TestStandardContext.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
@Test
public void testBug50015() throws Exception {
    // Test that configuring servlet security constraints programmatically
    // does work.

    // Set up a container
    Tomcat tomcat = getTomcatInstance();

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

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

    // Configure app for BASIC auth
    LoginConfig lc = new LoginConfig();
    lc.setAuthMethod("BASIC");
    ctx.setLoginConfig(lc);
    ctx.getPipeline().addValve(new BasicAuthenticator());

    // Add ServletContainerInitializer
    ServletContainerInitializer sci = new Bug50015SCI();
    ctx.addServletContainerInitializer(sci, null);

    // Start the context
    tomcat.start();

    // Request the first servlet
    ByteChunk bc = new ByteChunk();
    int rc = getUrl("http://localhost:" + getPort() + "/bug50015",
            bc, null);

    // Check for a 401
    assertNotSame("OK", bc.toString());
    assertEquals(401, rc);
}
 
Example 13
Source File: TestFormAuthenticator.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
private FormAuthClient(boolean clientShouldUseCookies,
        boolean serverShouldUseCookies,
        boolean serverShouldChangeSessid) throws Exception {

    Tomcat tomcat = getTomcatInstance();
    File appDir = new File(getBuildDirectory(), "webapps/examples");
    Context ctx = tomcat.addWebapp(null, "/examples",
            appDir.getAbsolutePath());
    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 14
Source File: TestStandardContext.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
@Test
public void testBug50015() throws Exception {
    // Test that configuring servlet security constraints programmatically
    // does work.

    // Set up a container
    Tomcat tomcat = getTomcatInstance();

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

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

    // Configure app for BASIC auth
    LoginConfig lc = new LoginConfig();
    lc.setAuthMethod("BASIC");
    ctx.setLoginConfig(lc);
    ctx.getPipeline().addValve(new BasicAuthenticator());

    // Add ServletContainerInitializer
    ServletContainerInitializer sci = new Bug50015SCI();
    ctx.addServletContainerInitializer(sci, null);

    // Start the context
    tomcat.start();

    // Request the first servlet
    ByteChunk bc = new ByteChunk();
    int rc = getUrl("http://localhost:" + getPort() + "/bug50015",
            bc, null);

    // Check for a 401
    assertNotSame("OK", bc.toString());
    assertEquals(401, rc);
}
 
Example 15
Source File: TestStandardWrapper.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
private void doTest(String servletClassName, boolean usePost,
        boolean useRole, boolean expect200, boolean denyUncovered)
        throws Exception {

    // Setup Tomcat instance
    Tomcat tomcat = getTomcatInstance();

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

    ctx.setDenyUncoveredHttpMethods(denyUncovered);

    Wrapper wrapper = Tomcat.addServlet(ctx, "servlet", servletClassName);
    wrapper.setAsyncSupported(true);
    ctx.addServletMappingDecoded("/", "servlet");

    if (useRole) {
        TesterMapRealm realm = new TesterMapRealm();
        realm.addUser("testUser", "testPwd");
        realm.addUserRole("testUser", "testRole");
        ctx.setRealm(realm);

        ctx.setLoginConfig(new LoginConfig("BASIC", null, null, null));
        ctx.getPipeline().addValve(new BasicAuthenticator());
    }

    tomcat.start();

    ByteChunk bc = new ByteChunk();
    Map<String,List<String>> reqHeaders = null;
    if (useRole) {
        reqHeaders = new HashMap<>();
        List<String> authHeaders = new ArrayList<>();
        // testUser, testPwd
        authHeaders.add("Basic dGVzdFVzZXI6dGVzdFB3ZA==");
        reqHeaders.put("Authorization", authHeaders);
    }

    int rc;
    if (usePost) {
        rc = postUrl(null, "http://localhost:" + getPort() + "/", bc,
                reqHeaders, null);
    } else {
        rc = getUrl("http://localhost:" + getPort() + "/", bc, reqHeaders,
                null);
    }

    if (expect200) {
        Assert.assertEquals("OK", bc.toString());
        Assert.assertEquals(200, rc);
    } else {
        Assert.assertTrue(bc.getLength() > 0);
        Assert.assertEquals(403, rc);
    }
}
 
Example 16
Source File: TestStandardWrapper.java    From tomcatsrc with Apache License 2.0 4 votes vote down vote up
private void doTest(String servletClassName, boolean usePost,
        boolean useRole, boolean expect200) throws Exception {

    // Setup Tomcat instance
    Tomcat tomcat = getTomcatInstance();

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

    Wrapper wrapper = Tomcat.addServlet(ctx, "servlet", servletClassName);
    wrapper.setAsyncSupported(true);
    ctx.addServletMapping("/", "servlet");

    if (useRole) {
        MapRealm realm = new MapRealm();
        realm.addUser("testUser", "testPwd");
        realm.addUserRole("testUser", "testRole");
        ctx.setRealm(realm);

        ctx.setLoginConfig(new LoginConfig("BASIC", null, null, null));
        ctx.getPipeline().addValve(new BasicAuthenticator());
    }

    tomcat.start();

    ByteChunk bc = new ByteChunk();
    Map<String,List<String>> reqHeaders = null;
    if (useRole) {
        reqHeaders = new HashMap<String,List<String>>();
        List<String> authHeaders = new ArrayList<String>();
        // testUser, testPwd
        authHeaders.add("Basic dGVzdFVzZXI6dGVzdFB3ZA==");
        reqHeaders.put("Authorization", authHeaders);
    }

    int rc;
    if (usePost) {
        rc = postUrl(null, "http://localhost:" + getPort() + "/", bc,
                reqHeaders, null);
    } else {
        rc = getUrl("http://localhost:" + getPort() + "/", bc, reqHeaders,
                null);
    }

    if (expect200) {
        assertEquals("OK", bc.toString());
        assertEquals(200, rc);
    } else {
        assertTrue(bc.getLength() > 0);
        assertEquals(403, rc);
    }
}
 
Example 17
Source File: TestStandardWrapper.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
private void doTestRoleMapping(String realmContainer)
        throws Exception {
    // Setup Tomcat instance
    Tomcat tomcat = getTomcatInstance();

    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    ctx.addRoleMapping("testRole", "very-complex-role-name");

    Wrapper wrapper = Tomcat.addServlet(ctx, "servlet", RoleAllowServlet.class.getName());
    ctx.addServletMappingDecoded("/", "servlet");

    ctx.setLoginConfig(new LoginConfig("BASIC", null, null, null));
    ctx.getPipeline().addValve(new BasicAuthenticator());

    TesterMapRealm realm = new TesterMapRealm();
    MessageDigestCredentialHandler ch = new MessageDigestCredentialHandler();
    ch.setAlgorithm("SHA");
    realm.setCredentialHandler(ch);

    /* Attach the realm to the appropriate container, but role mapping must
     * always succeed because it is evaluated at context level.
     */
    if (realmContainer.equals("engine")) {
        tomcat.getEngine().setRealm(realm);
    } else if (realmContainer.equals("host")) {
        tomcat.getHost().setRealm(realm);
    } else if (realmContainer.equals("context")) {
        ctx.setRealm(realm);
    } else {
        throw new IllegalArgumentException("realmContainer is invalid");
    }

    realm.addUser("testUser", ch.mutate("testPwd"));
    realm.addUserRole("testUser", "testRole1");
    realm.addUserRole("testUser", "very-complex-role-name");
    realm.addUserRole("testUser", "another-very-complex-role-name");

    tomcat.start();

    Principal p = realm.authenticate("testUser", "testPwd");

    Assert.assertNotNull(p);
    Assert.assertEquals("testUser", p.getName());
    // This one is mapped
    Assert.assertTrue(realm.hasRole(wrapper, p, "testRole"));
    Assert.assertTrue(realm.hasRole(wrapper, p, "testRole1"));
    Assert.assertFalse(realm.hasRole(wrapper, p, "testRole2"));
    Assert.assertTrue(realm.hasRole(wrapper, p, "very-complex-role-name"));
    Assert.assertTrue(realm.hasRole(wrapper, p, "another-very-complex-role-name"));

    // This now tests RealmBase#hasResourcePermission() because we need a wrapper
    // to be passed from an authenticator
    ByteChunk bc = new ByteChunk();
    Map<String,List<String>> reqHeaders = new HashMap<>();
    List<String> authHeaders = new ArrayList<>();
    // testUser, testPwd
    authHeaders.add("Basic dGVzdFVzZXI6dGVzdFB3ZA==");
    reqHeaders.put("Authorization", authHeaders);

    int rc = getUrl("http://localhost:" + getPort() + "/", bc, reqHeaders,
            null);

    Assert.assertEquals("OK", bc.toString());
    Assert.assertEquals(200, rc);
}
 
Example 18
Source File: TestStandardContext.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
private void doTestDenyUncoveredHttpMethodsSCI(boolean enableDeny)
        throws Exception {
    // Test that denying uncovered HTTP methods when adding servlet security
    // constraints programmatically does work.

    // Set up a container
    Tomcat tomcat = getTomcatInstance();

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

    ctx.setDenyUncoveredHttpMethods(enableDeny);

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

    // Configure app for BASIC auth
    LoginConfig lc = new LoginConfig();
    lc.setAuthMethod("BASIC");
    ctx.setLoginConfig(lc);
    ctx.getPipeline().addValve(new BasicAuthenticator());

    // Add ServletContainerInitializer
    ServletContainerInitializer sci = new DenyUncoveredHttpMethodsSCI();
    ctx.addServletContainerInitializer(sci, null);

    // Start the context
    tomcat.start();

    // Request the first servlet
    ByteChunk bc = new ByteChunk();
    int rc = getUrl("http://localhost:" + getPort() + "/test",
            bc, null);

    // Check for a 401
    if (enableDeny) {
        // Should be default error page
        Assert.assertTrue(bc.toString().contains("403"));
        Assert.assertEquals(403, rc);
    } else {
        Assert.assertEquals("OK", bc.toString());
        Assert.assertEquals(200, rc);
    }
}
 
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: TestRegistration.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
@Test
public void testMBeanDeregistration() throws Exception {
    final MBeanServer mbeanServer = Registry.getRegistry(null, null).getMBeanServer();
    // Verify there are no Catalina or Tomcat MBeans
    Set<ObjectName> onames = mbeanServer.queryNames(new ObjectName("Catalina:*"), null);
    log.info(MBeanDumper.dumpBeans(mbeanServer, onames));
    Assert.assertEquals("Unexpected: " + onames, 0, onames.size());
    onames = mbeanServer.queryNames(new ObjectName("Tomcat:*"), null);
    log.info(MBeanDumper.dumpBeans(mbeanServer, onames));
    Assert.assertEquals("Unexpected: " + onames, 0, onames.size());

    final Tomcat tomcat = getTomcatInstance();
    final File contextDir = new File(getTemporaryDirectory(), "webappFoo");
    addDeleteOnTearDown(contextDir);
    if (!contextDir.mkdirs() && !contextDir.isDirectory()) {
        Assert.fail("Failed to create: [" + contextDir.toString() + "]");
    }
    Context ctx = tomcat.addContext(contextName, contextDir.getAbsolutePath());

    CombinedRealm combinedRealm = new CombinedRealm();
    Realm nullRealm = new NullRealm();
    combinedRealm.addRealm(nullRealm);
    ctx.setRealm(combinedRealm);

    tomcat.start();

    getUrl("http://localhost:" + getPort());

    // Verify there are no Catalina MBeans
    onames = mbeanServer.queryNames(new ObjectName("Catalina:*"), null);
    log.info(MBeanDumper.dumpBeans(mbeanServer, onames));
    Assert.assertEquals("Found: " + onames, 0, onames.size());

    // Verify there are the correct Tomcat MBeans
    onames = mbeanServer.queryNames(new ObjectName("Tomcat:*"), null);
    ArrayList<String> found = new ArrayList<>(onames.size());
    for (ObjectName on: onames) {
        found.add(on.toString());
    }

    // Create the list of expected MBean names
    String protocol = tomcat.getConnector().getProtocolHandlerClassName();
    if (protocol.indexOf("Nio2") > 0) {
        protocol = "nio2";
    } else if (protocol.indexOf("Apr") > 0) {
        protocol = "apr";
    } else {
        protocol = "nio";
    }
    String index = tomcat.getConnector().getProperty("nameIndex").toString();
    ArrayList<String> expected = new ArrayList<>(Arrays.asList(basicMBeanNames()));
    expected.addAll(Arrays.asList(hostMBeanNames("localhost")));
    expected.addAll(Arrays.asList(contextMBeanNames("localhost", contextName)));
    expected.addAll(Arrays.asList(connectorMBeanNames("auto-" + index, protocol)));
    expected.addAll(Arrays.asList(optionalMBeanNames("localhost")));
    expected.addAll(Arrays.asList(requestMBeanNames(
            "auto-" + index + "-" + getPort(), protocol)));

    // Did we find all expected MBeans?
    ArrayList<String> missing = new ArrayList<>(expected);
    missing.removeAll(found);
    Assert.assertTrue("Missing Tomcat MBeans: " + missing, missing.isEmpty());

    // Did we find any unexpected MBeans?
    List<String> additional = found;
    additional.removeAll(expected);
    Assert.assertTrue("Unexpected Tomcat MBeans: " + additional, additional.isEmpty());

    tomcat.stop();

    // There should still be some Tomcat MBeans
    onames = mbeanServer.queryNames(new ObjectName("Tomcat:*"), null);
    Assert.assertTrue("No Tomcat MBeans", onames.size() > 0);

    // add a new host
    StandardHost host = new StandardHost();
    host.setName("otherhost");
    tomcat.getEngine().addChild(host);

    final File contextDir2 = new File(getTemporaryDirectory(), "webappFoo2");
    addDeleteOnTearDown(contextDir2);
    if (!contextDir2.mkdirs() && !contextDir2.isDirectory()) {
        Assert.fail("Failed to create: [" + contextDir2.toString() + "]");
    }
    tomcat.addContext(host, contextName + "2", contextDir2.getAbsolutePath());

    tomcat.start();
    tomcat.stop();
    tomcat.destroy();

    // There should be no Catalina MBeans and no Tomcat MBeans
    onames = mbeanServer.queryNames(new ObjectName("Catalina:*"), null);
    log.info(MBeanDumper.dumpBeans(mbeanServer, onames));
    Assert.assertEquals("Remaining: " + onames, 0, onames.size());
    onames = mbeanServer.queryNames(new ObjectName("Tomcat:*"), null);
    log.info(MBeanDumper.dumpBeans(mbeanServer, onames));
    Assert.assertEquals("Remaining: " + onames, 0, onames.size());
}