org.apache.tomcat.util.descriptor.web.LoginConfig Java Examples

The following examples show how to use org.apache.tomcat.util.descriptor.web.LoginConfig. 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: AuthenticatorBase.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
protected static String getRealmName(Context context) {
    if (context == null) {
        // Very unlikely
        return REALM_NAME;
    }

    LoginConfig config = context.getLoginConfig();
    if (config == null) {
        return REALM_NAME;
    }

    String result = config.getRealmName();
    if (result == null) {
        return REALM_NAME;
    }

    return result;
}
 
Example #2
Source File: KeycloakAuthenticatorValve.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
protected boolean forwardToErrorPageInternal(Request request, HttpServletResponse response, Object loginConfig) throws IOException {
    if (loginConfig == null) return false;
    LoginConfig config = (LoginConfig)loginConfig;
    if (config.getErrorPage() == null) return false;
    // had to do this to get around compiler/IDE issues :(
    try {
        Method method = null;
        /*
        for (Method m : getClass().getDeclaredMethods()) {
            if (m.getName().equals("forwardToErrorPage")) {
                method = m;
                break;
            }
        }
        */
        method = FormAuthenticator.class.getDeclaredMethod("forwardToErrorPage", Request.class, HttpServletResponse.class, LoginConfig.class);
        method.setAccessible(true);
        method.invoke(this, request, response, config);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return true;
}
 
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: 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 #5
Source File: Tomcat.java    From Tomcat8-Source-Read with MIT License 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);

            // Process annotations
            WebAnnotationSet.loadApplicationAnnotations(context);

            // 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) {
    }
}
 
Example #6
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 #7
Source File: TestStandardContext.java    From Tomcat8-Source-Read with MIT License 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
    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 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
    Assert.assertNotSame("OK", bc.toString());
    Assert.assertEquals(401, rc);
}
 
Example #8
Source File: SamlAuthenticatorValve.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean forwardToErrorPageInternal(Request request, HttpServletResponse response, Object loginConfig) throws IOException {
    if (loginConfig == null) return false;
    LoginConfig config = (LoginConfig)loginConfig;
    if (config.getErrorPage() == null) return false;
    // had to do this to get around compiler/IDE issues :(
    try {
        Method method = FormAuthenticator.class.getDeclaredMethod("forwardToErrorPage", Request.class, HttpServletResponse.class, LoginConfig.class);
        method.setAccessible(true);
        method.invoke(this, request, response, config);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return true;
}
 
Example #9
Source File: KeycloakBaseSpringBootConfiguration.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public void customize(DeploymentInfo deploymentInfo) {

            io.undertow.servlet.api.LoginConfig loginConfig = new io.undertow.servlet.api.LoginConfig(keycloakProperties.getRealm());
            loginConfig.addFirstAuthMethod("KEYCLOAK");

            deploymentInfo.setLoginConfig(loginConfig);

            deploymentInfo.addInitParameter("keycloak.config.resolver", KeycloakSpringBootConfigResolverWrapper.class.getName());
            
            
            /* Support for '*' as all roles allowed
             * We clear out the role in the SecurityConstraints
             * and set the EmptyRoleSemantic to Authenticate
             * But we will set EmptyRoleSemantic to DENY (default)
             * if roles are non existing or left empty
             */
            Iterator<io.undertow.servlet.api.SecurityConstraint> it = this.getSecurityConstraints().iterator();
            while (it.hasNext()) {
            	io.undertow.servlet.api.SecurityConstraint securityConstraint = it.next();
            	Set<String> rolesAllowed = securityConstraint.getRolesAllowed();
            	
            	if (rolesAllowed.contains("*") || rolesAllowed.contains("**") ) {
            		io.undertow.servlet.api.SecurityConstraint allRolesAllowed = new io.undertow.servlet.api.SecurityConstraint();
            		allRolesAllowed.setEmptyRoleSemantic(EmptyRoleSemantic.AUTHENTICATE);
            		allRolesAllowed.setTransportGuaranteeType(securityConstraint.getTransportGuaranteeType());
            		for (WebResourceCollection wr : securityConstraint.getWebResourceCollections()) {
            			allRolesAllowed.addWebResourceCollection(wr);
            		}
            		deploymentInfo.addSecurityConstraint(allRolesAllowed);
            	} else // left empty will fall back on default EmptyRoleSemantic.DENY
            		deploymentInfo.addSecurityConstraint(securityConstraint);
            	
            }
            deploymentInfo.addServletExtension(new KeycloakServletExtension());
        }
 
Example #10
Source File: BaseOpenIDConnectAuthenticator.java    From tomcat-oidcauth with Apache License 2.0 5 votes vote down vote up
@Override
protected void forwardToErrorPage(final Request request,
		final HttpServletResponse response, final LoginConfig config)
	throws IOException {

	// add login configuration request attributes for the page
	this.addLoginConfiguration(request);

	// proceed to the login error page
	super.forwardToErrorPage(request, response, config);
}
 
Example #11
Source File: BaseOpenIDConnectAuthenticator.java    From tomcat-oidcauth with Apache License 2.0 5 votes vote down vote up
@Override
protected void forwardToLoginPage(final Request request,
		final HttpServletResponse response, final LoginConfig config)
	throws IOException {

	// add login configuration request attributes for the page
	this.addLoginConfiguration(request);

	// proceed to the login page
	super.forwardToLoginPage(request, response, config);
}
 
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: 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 #14
Source File: TestRestCsrfPreventionFilter2.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
private void setUpApplication() throws Exception {
    context = tomcat.addContext(CONTEXT_PATH_LOGIN, System.getProperty("java.io.tmpdir"));
    context.setSessionTimeout(SHORT_SESSION_TIMEOUT_MINS);

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

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

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

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

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

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

    AuthenticatorBase basicAuthenticator = new BasicAuthenticator();
    context.getPipeline().addValve(basicAuthenticator);
}
 
Example #15
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 #16
Source File: TestNonLoginAndBasicAuthenticator.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
private void setUpLogin() throws Exception {

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        // Configure the authenticator and inherit the Realm from Engine
        LoginConfig lc = new LoginConfig();
        lc.setAuthMethod("NONE");
        nonloginContext.setLoginConfig(lc);
        AuthenticatorBase nonloginAuthenticator = new NonLoginAuthenticator();
        nonloginContext.getPipeline().addValve(nonloginAuthenticator);
    }
 
Example #21
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 #22
Source File: FailedContext.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
@Override
public LoginConfig getLoginConfig() { return null; }
 
Example #23
Source File: FailedContext.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
@Override
public void setLoginConfig(LoginConfig config) { /* NO-OP */ }
 
Example #24
Source File: TomcatHessianRegistry.java    From tomee with Apache License 2.0 4 votes vote down vote up
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;
}
 
Example #25
Source File: TomcatWsRegistry.java    From tomee with Apache License 2.0 4 votes vote down vote up
private static Context createNewContext(final ClassLoader classLoader, String authMethod, String transportGuarantee, final String realmName, final String name) {
    String path = name;
    if (path == null) {
        path = "/";
    }
    if (!path.startsWith("/")) {
        path = "/" + path;
    }

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

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

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

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

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

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

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

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

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

    return context;
}
 
Example #26
Source File: ConfigurationTest.java    From tomee with Apache License 2.0 4 votes vote down vote up
@Test
public void autoConfig() {
    final Configuration configuration = new Configuration();
    configuration.loadFromProperties(new PropertiesBuilder()
            // plain params
            .p("http", "1234")
            .p("stop", "1235")
            .p("host", "here")
            .p("dir", "target/dirtmp")
            .p("quickSession", "false")
            .p("webResourceCached", "false")
            .p("withEjbRemote", "true")
            .p("deployOpenEjbApp", "true")
            .p("users.u1", "p1")
            .p("users.u2", "p2")
            .p("roles.admin", "u1,u2")
            .p("roles.simple", "u1")
            // more complex structures
            .p("realm", "org.apache.catalina.realm.JAASRealm")
            .p("realm.appName", "app")
            .p("realm.configFile", "configuration.jaas")
            // there we ensure our builders are xbean friendly
            .p("login", "")
            .p("login.realmName", "app")
            .p("login.authMethod", "BASIC")
            .p("securityConstraint", "")
            .p("securityConstraint.authConstraint", "true")
            .p("securityConstraint.authRole", "**")
            .p("securityConstraint.collection", "api:/api/*")
            .build());

    assertEquals(1234, configuration.getHttpPort());
    assertEquals(1235, configuration.getStopPort());
    assertEquals("target/dirtmp", configuration.getDir());
    assertFalse(configuration.isQuickSession());
    assertTrue(configuration.isWithEjbRemote());
    assertTrue(configuration.isDeployOpenEjbApp());
    assertEquals(new HashMap<String, String>() {{
        put("u1", "p1");
        put("u2", "p2");
    }}, configuration.getUsers());
    assertEquals(new HashMap<String, String>() {{
        put("admin", "u1,u2");
        put("simple", "u1");
    }}, configuration.getRoles());

    assertNotNull(configuration.getRealm());
    assertTrue(JAASRealm.class.isInstance(configuration.getRealm()));
    final JAASRealm realm = JAASRealm.class.cast(configuration.getRealm());
    assertEquals("app", realm.getAppName());
    assertEquals("configuration.jaas", realm.getConfigFile());

    assertNotNull(configuration.getLoginConfig());
    final LoginConfig loginConfig = configuration.getLoginConfig().build();
    assertEquals("app", loginConfig.getRealmName());
    assertEquals("BASIC", loginConfig.getAuthMethod());

    final Collection<SecurityConstaintBuilder> securityConstraints = configuration.getSecurityConstraints();
    assertNotNull(securityConstraints);
    assertEquals(1, securityConstraints.size());
    final SecurityConstraint constraint = securityConstraints.iterator().next().build();
    assertTrue(constraint.getAuthConstraint());
    assertTrue(constraint.getAuthenticatedUsers());
    assertEquals("/api/*", constraint.findCollection("api").findPatterns()[0]);
}
 
Example #27
Source File: LoginConfigBuilder.java    From tomee with Apache License 2.0 4 votes vote down vote up
public LoginConfig build() {
    return loginConfig;
}
 
Example #28
Source File: ServingLayer.java    From oryx with Apache License 2.0 4 votes vote down vote up
private void makeContext(Tomcat tomcat, Path noSuchBaseDir) throws IOException {
  Path contextPath = noSuchBaseDir.resolve("context");
  Files.createDirectories(contextPath);

  context = tomcat.addContext(contextPathURIBase, contextPath.toAbsolutePath().toString());

  context.setWebappVersion("3.1");
  context.setName("Oryx");

  context.addWelcomeFile("index.html");
  addErrorPages(context);

  // OryxApplication only needs one config value, so just pass it
  context.addParameter(OryxApplication.class.getName() + ".packages", appResourcesPackages);
  // ModelManagerListener will need whole config
  String serializedConfig = ConfigUtils.serialize(config);
  context.addParameter(ConfigUtils.class.getName() + ".serialized", serializedConfig);

  Wrapper wrapper =
      Tomcat.addServlet(context, "Jersey", "org.glassfish.jersey.servlet.ServletContainer");
  wrapper.addInitParameter("javax.ws.rs.Application", OryxApplication.class.getName());
  //wrapper.addInitParameter(OryxApplication.class.getName() + ".packages", appResourcesPackage);
  wrapper.addMapping("/*");
  wrapper.setLoadOnStartup(1);
  wrapper.setMultipartConfigElement(new MultipartConfigElement(""));

  if (!doNotInitTopics) { // Only for tests
    context.addApplicationListener(ModelManagerListener.class.getName());
  }

  // Better way to configure JASPIC?
  AuthConfigFactory.setFactory(new AuthConfigFactoryImpl());

  boolean needHTTPS = keystoreFile != null;
  boolean needAuthentication = userName != null;

  if (needHTTPS || needAuthentication) {

    SecurityCollection securityCollection = new SecurityCollection();
    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);
}
 
Example #29
Source File: Meecrowave.java    From openwebbeans-meecrowave with Apache License 2.0 4 votes vote down vote up
public LoginConfig build() {
    return loginConfig;
}
 
Example #30
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());
}