Search in sources :

Example 11 with BasicAuthenticator

use of org.apache.catalina.authenticator.BasicAuthenticator in project tomee by apache.

the class TomcatHessianRegistry method createNewContext.

private static Context createNewContext(final ClassLoader classLoader, final String rAuthMethod, final String rTransportGuarantee, 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.class.cast(SystemInstance.get().getComponent(WebAppBuilder.class)).initJ2EEInfo(context);
    // Configure security
    String authMethod = rAuthMethod;
    if (authMethod != null) {
        authMethod = authMethod.toUpperCase();
    }
    String transportGuarantee = rTransportGuarantee;
    if (transportGuarantee != null) {
        transportGuarantee = transportGuarantee.toUpperCase();
    }
    if (authMethod != null & !"NONE".equals(authMethod)) {
        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_HESSIAN_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
        switch(authMethod) {
            case "BASIC":
                context.addValve(new BasicAuthenticator());
                break;
            case "DIGEST":
                context.addValve(new DigestAuthenticator());
                break;
            case "CLIENT-CERT":
                context.addValve(new SSLAuthenticator());
                break;
            case "NONE":
                context.addValve(new NonLoginAuthenticator());
                break;
        }
        context.getPipeline().addValve(new OpenEJBValve());
    } else {
        throw new IllegalArgumentException("Invalid authMethod: " + authMethod);
    }
    return context;
}
Also used : TomcatWebAppBuilder(org.apache.tomee.catalina.TomcatWebAppBuilder) NonLoginAuthenticator(org.apache.catalina.authenticator.NonLoginAuthenticator) SecurityConstraint(org.apache.tomcat.util.descriptor.web.SecurityConstraint) IgnoredStandardContext(org.apache.tomee.catalina.IgnoredStandardContext) SSLAuthenticator(org.apache.catalina.authenticator.SSLAuthenticator) BasicAuthenticator(org.apache.catalina.authenticator.BasicAuthenticator) OpenEJBValve(org.apache.tomee.catalina.OpenEJBValve) DigestAuthenticator(org.apache.catalina.authenticator.DigestAuthenticator) IgnoredStandardContext(org.apache.tomee.catalina.IgnoredStandardContext) StandardContext(org.apache.catalina.core.StandardContext) LoginConfig(org.apache.tomcat.util.descriptor.web.LoginConfig) SecurityCollection(org.apache.tomcat.util.descriptor.web.SecurityCollection)

Example 12 with BasicAuthenticator

use of org.apache.catalina.authenticator.BasicAuthenticator in project tomcat by apache.

the class TestRestCsrfPreventionFilter2 method setUpApplication.

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);
}
Also used : AuthenticatorBase(org.apache.catalina.authenticator.AuthenticatorBase) FilterDef(org.apache.tomcat.util.descriptor.web.FilterDef) BasicAuthenticator(org.apache.catalina.authenticator.BasicAuthenticator) LoginConfig(org.apache.tomcat.util.descriptor.web.LoginConfig) FilterMap(org.apache.tomcat.util.descriptor.web.FilterMap) SecurityConstraint(org.apache.tomcat.util.descriptor.web.SecurityConstraint) SecurityCollection(org.apache.tomcat.util.descriptor.web.SecurityCollection)

Example 13 with BasicAuthenticator

use of org.apache.catalina.authenticator.BasicAuthenticator in project tomcat by apache.

the class TestStandardWrapper method doTestRoleMapping.

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);
}
Also used : Context(org.apache.catalina.Context) ServletContext(jakarta.servlet.ServletContext) Wrapper(org.apache.catalina.Wrapper) Tomcat(org.apache.catalina.startup.Tomcat) ByteChunk(org.apache.tomcat.util.buf.ByteChunk) HashMap(java.util.HashMap) MessageDigestCredentialHandler(org.apache.catalina.realm.MessageDigestCredentialHandler) ArrayList(java.util.ArrayList) HttpConstraint(jakarta.servlet.annotation.HttpConstraint) HttpMethodConstraint(jakarta.servlet.annotation.HttpMethodConstraint) TesterMapRealm(org.apache.catalina.startup.TesterMapRealm) BasicAuthenticator(org.apache.catalina.authenticator.BasicAuthenticator) LoginConfig(org.apache.tomcat.util.descriptor.web.LoginConfig) ArrayList(java.util.ArrayList) List(java.util.List) Principal(java.security.Principal)

Example 14 with BasicAuthenticator

use of org.apache.catalina.authenticator.BasicAuthenticator in project tomcat by apache.

the class TestStandardContext method doTestDenyUncoveredHttpMethodsSCI.

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);
    }
}
Also used : ServletContext(jakarta.servlet.ServletContext) Context(org.apache.catalina.Context) ServletContainerInitializer(jakarta.servlet.ServletContainerInitializer) Tomcat(org.apache.catalina.startup.Tomcat) TesterMapRealm(org.apache.catalina.startup.TesterMapRealm) BasicAuthenticator(org.apache.catalina.authenticator.BasicAuthenticator) ByteChunk(org.apache.tomcat.util.buf.ByteChunk) LoginConfig(org.apache.tomcat.util.descriptor.web.LoginConfig) HttpMethodConstraint(jakarta.servlet.annotation.HttpMethodConstraint) HttpConstraint(jakarta.servlet.annotation.HttpConstraint)

Aggregations

BasicAuthenticator (org.apache.catalina.authenticator.BasicAuthenticator)14 LoginConfig (org.apache.tomcat.util.descriptor.web.LoginConfig)10 Context (org.apache.catalina.Context)8 Tomcat (org.apache.catalina.startup.Tomcat)8 ByteChunk (org.apache.tomcat.util.buf.ByteChunk)8 TesterMapRealm (org.apache.catalina.startup.TesterMapRealm)5 SecurityCollection (org.apache.tomcat.util.descriptor.web.SecurityCollection)5 SecurityConstraint (org.apache.tomcat.util.descriptor.web.SecurityConstraint)5 ServletContext (jakarta.servlet.ServletContext)4 HttpConstraint (jakarta.servlet.annotation.HttpConstraint)4 HttpMethodConstraint (jakarta.servlet.annotation.HttpMethodConstraint)4 LoginConfig (org.apache.catalina.deploy.LoginConfig)4 TomcatBaseTest (org.apache.catalina.startup.TomcatBaseTest)4 Test (org.junit.Test)4 ArrayList (java.util.ArrayList)3 List (java.util.List)3 Wrapper (org.apache.catalina.Wrapper)3 MapRealm (org.apache.catalina.startup.TestTomcat.MapRealm)3 ServletContainerInitializer (jakarta.servlet.ServletContainerInitializer)2 ServletContext (javax.servlet.ServletContext)2