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

The following examples show how to use org.apache.catalina.Context#setLoginConfig() . 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: Tomcat.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
@Override
public void lifecycleEvent(LifecycleEvent event) {
    try {
        Context context = (Context) event.getLifecycle();
        if (event.getType().equals(Lifecycle.CONFIGURE_START_EVENT)) {
            context.setConfigured(true);
        }
        // LoginConfig is required to process @ServletSecurity
        // annotations
        if (context.getLoginConfig() == null) {
            context.setLoginConfig(
                    new LoginConfig("NONE", null, null, null));
            context.getPipeline().addValve(new NonLoginAuthenticator());
        }
    } catch (ClassCastException e) {
        return;
    }
}
 
Example 2
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 3
Source File: TestSSOnonLoginAndDigestAuthenticator.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
private void setUpDigest(Tomcat tomcat) throws Exception {

        // Must have a real docBase for webapps - just use temp
        Context ctxt = tomcat.addContext(CONTEXT_PATH_DIGEST,
                System.getProperty("java.io.tmpdir"));
        ctxt.setSessionTimeout(SHORT_TIMEOUT_SECS);

        // Add protected servlet
        Tomcat.addServlet(ctxt, "TesterServlet3", new TesterServlet());
        ctxt.addServletMappingDecoded(URI_PROTECTED, "TesterServlet3");
        SecurityCollection collection = new SecurityCollection();
        collection.addPatternDecoded(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 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 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 6
Source File: Tomcat.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
@Override
public void lifecycleEvent(LifecycleEvent event) {
    try {
        Context context = (Context) event.getLifecycle();
        if (event.getType().equals(Lifecycle.CONFIGURE_START_EVENT)) {
            context.setConfigured(true);
        }
        // LoginConfig is required to process @ServletSecurity
        // annotations
        if (context.getLoginConfig() == null) {
            context.setLoginConfig(
                    new LoginConfig("NONE", null, null, null));
            context.getPipeline().addValve(new NonLoginAuthenticator());
        }
    } catch (ClassCastException e) {
        return;
    }
}
 
Example 7
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 8
Source File: TestDigestAuthenticator.java    From Tomcat7.0.67 with Apache License 2.0 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.addServletMapping(URI, "TesterServlet");
    SecurityCollection collection = new SecurityCollection();
    collection.addPattern(URI);
    SecurityConstraint sc = new SecurityConstraint();
    sc.addAuthRole(ROLE);
    sc.addCollection(collection);
    ctxt.addConstraint(sc);

    // Configure the Realm
    MapRealm realm = new MapRealm();
    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 9
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 10
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 11
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 12
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 13
Source File: TestDigestAuthenticator.java    From tomcatsrc with Apache License 2.0 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.addServletMapping(URI, "TesterServlet");
    SecurityCollection collection = new SecurityCollection();
    collection.addPattern(URI);
    SecurityConstraint sc = new SecurityConstraint();
    sc.addAuthRole(ROLE);
    sc.addCollection(collection);
    ctxt.addConstraint(sc);

    // Configure the Realm
    MapRealm realm = new MapRealm();
    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 Tomcat8-Source-Read with MIT License 5 votes vote down vote up
private void setUpNonLogin(Tomcat tomcat) throws Exception {

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

        // Add protected servlet
        Tomcat.addServlet(ctxt, "TesterServlet1", new TesterServlet());
        ctxt.addServletMappingDecoded(URI_PROTECTED, "TesterServlet1");
        SecurityCollection collection1 = new SecurityCollection();
        collection1.addPatternDecoded(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.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);
        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: 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 17
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 18
Source File: TestFormAuthenticator.java    From tomcatsrc 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 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: 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;
  }