Search in sources :

Example 1 with BasicAuthenticator

use of org.eclipse.jetty.security.authentication.BasicAuthenticator in project jetty.project by eclipse.

the class Runner method configure.

/**
     * Configure a jetty instance and deploy the webapps presented as args
     *
     * @param args the command line arguments
     * @throws Exception if unable to configure
     */
public void configure(String[] args) throws Exception {
    // handle classpath bits first so we can initialize the log mechanism.
    for (int i = 0; i < args.length; i++) {
        if ("--lib".equals(args[i])) {
            try (Resource lib = Resource.newResource(args[++i])) {
                if (!lib.exists() || !lib.isDirectory())
                    usage("No such lib directory " + lib);
                _classpath.addJars(lib);
            }
        } else if ("--jar".equals(args[i])) {
            try (Resource jar = Resource.newResource(args[++i])) {
                if (!jar.exists() || jar.isDirectory())
                    usage("No such jar " + jar);
                _classpath.addPath(jar);
            }
        } else if ("--classes".equals(args[i])) {
            try (Resource classes = Resource.newResource(args[++i])) {
                if (!classes.exists() || !classes.isDirectory())
                    usage("No such classes directory " + classes);
                _classpath.addPath(classes);
            }
        } else if (args[i].startsWith("--"))
            i++;
    }
    initClassLoader();
    LOG.info("Runner");
    LOG.debug("Runner classpath {}", _classpath);
    String contextPath = __defaultContextPath;
    boolean contextPathSet = false;
    int port = __defaultPort;
    String host = null;
    int stopPort = 0;
    String stopKey = null;
    boolean runnerServerInitialized = false;
    for (int i = 0; i < args.length; i++) {
        switch(args[i]) {
            case "--port":
                port = Integer.parseInt(args[++i]);
                break;
            case "--host":
                host = args[++i];
                break;
            case "--stop-port":
                stopPort = Integer.parseInt(args[++i]);
                break;
            case "--stop-key":
                stopKey = args[++i];
                break;
            case "--log":
                _logFile = args[++i];
                break;
            case "--out":
                String outFile = args[++i];
                PrintStream out = new PrintStream(new RolloverFileOutputStream(outFile, true, -1));
                LOG.info("Redirecting stderr/stdout to " + outFile);
                System.setErr(out);
                System.setOut(out);
                break;
            case "--path":
                contextPath = args[++i];
                contextPathSet = true;
                break;
            case "--config":
                if (_configFiles == null)
                    _configFiles = new ArrayList<>();
                _configFiles.add(args[++i]);
                break;
            case "--lib":
                //skip
                ++i;
                break;
            case "--jar":
                //skip
                ++i;
                break;
            case "--classes":
                //skip
                ++i;
                break;
            case "--stats":
                _enableStats = true;
                _statsPropFile = args[++i];
                _statsPropFile = ("unsecure".equalsIgnoreCase(_statsPropFile) ? null : _statsPropFile);
                break;
            default:
                if (// log handlers not registered, server maybe not created, etc
                !runnerServerInitialized) {
                    if (// server not initialized yet
                    _server == null) {
                        // build the server
                        _server = new Server();
                    }
                    //apply jetty config files if there are any
                    if (_configFiles != null) {
                        for (String cfg : _configFiles) {
                            try (Resource resource = Resource.newResource(cfg)) {
                                XmlConfiguration xmlConfiguration = new XmlConfiguration(resource.getURL());
                                xmlConfiguration.configure(_server);
                            }
                        }
                    }
                    //check that everything got configured, and if not, make the handlers
                    HandlerCollection handlers = (HandlerCollection) _server.getChildHandlerByClass(HandlerCollection.class);
                    if (handlers == null) {
                        handlers = new HandlerCollection();
                        _server.setHandler(handlers);
                    }
                    //check if contexts already configured
                    _contexts = (ContextHandlerCollection) handlers.getChildHandlerByClass(ContextHandlerCollection.class);
                    if (_contexts == null) {
                        _contexts = new ContextHandlerCollection();
                        prependHandler(_contexts, handlers);
                    }
                    if (_enableStats) {
                        //if no stats handler already configured
                        if (handlers.getChildHandlerByClass(StatisticsHandler.class) == null) {
                            StatisticsHandler statsHandler = new StatisticsHandler();
                            Handler oldHandler = _server.getHandler();
                            statsHandler.setHandler(oldHandler);
                            _server.setHandler(statsHandler);
                            ServletContextHandler statsContext = new ServletContextHandler(_contexts, "/stats");
                            statsContext.addServlet(new ServletHolder(new StatisticsServlet()), "/");
                            statsContext.setSessionHandler(new SessionHandler());
                            if (_statsPropFile != null) {
                                HashLoginService loginService = new HashLoginService("StatsRealm", _statsPropFile);
                                Constraint constraint = new Constraint();
                                constraint.setName("Admin Only");
                                constraint.setRoles(new String[] { "admin" });
                                constraint.setAuthenticate(true);
                                ConstraintMapping cm = new ConstraintMapping();
                                cm.setConstraint(constraint);
                                cm.setPathSpec("/*");
                                ConstraintSecurityHandler securityHandler = new ConstraintSecurityHandler();
                                securityHandler.setLoginService(loginService);
                                securityHandler.setConstraintMappings(Collections.singletonList(cm));
                                securityHandler.setAuthenticator(new BasicAuthenticator());
                                statsContext.setSecurityHandler(securityHandler);
                            }
                        }
                    }
                    //ensure a DefaultHandler is present
                    if (handlers.getChildHandlerByClass(DefaultHandler.class) == null) {
                        handlers.addHandler(new DefaultHandler());
                    }
                    //ensure a log handler is present
                    _logHandler = (RequestLogHandler) handlers.getChildHandlerByClass(RequestLogHandler.class);
                    if (_logHandler == null) {
                        _logHandler = new RequestLogHandler();
                        handlers.addHandler(_logHandler);
                    }
                    //check a connector is configured to listen on
                    Connector[] connectors = _server.getConnectors();
                    if (connectors == null || connectors.length == 0) {
                        ServerConnector connector = new ServerConnector(_server);
                        connector.setPort(port);
                        if (host != null)
                            connector.setHost(host);
                        _server.addConnector(connector);
                        if (_enableStats)
                            connector.addBean(new ConnectionStatistics());
                    } else {
                        if (_enableStats) {
                            for (Connector connector : connectors) {
                                ((AbstractConnector) connector).addBean(new ConnectionStatistics());
                            }
                        }
                    }
                    runnerServerInitialized = true;
                }
                // Create a context
                try (Resource ctx = Resource.newResource(args[i])) {
                    if (!ctx.exists())
                        usage("Context '" + ctx + "' does not exist");
                    if (contextPathSet && !(contextPath.startsWith("/")))
                        contextPath = "/" + contextPath;
                    // Configure the context
                    if (!ctx.isDirectory() && ctx.toString().toLowerCase(Locale.ENGLISH).endsWith(".xml")) {
                        // It is a context config file
                        XmlConfiguration xmlConfiguration = new XmlConfiguration(ctx.getURL());
                        xmlConfiguration.getIdMap().put("Server", _server);
                        ContextHandler handler = (ContextHandler) xmlConfiguration.configure();
                        if (contextPathSet)
                            handler.setContextPath(contextPath);
                        _contexts.addHandler(handler);
                        String containerIncludeJarPattern = (String) handler.getAttribute(WebInfConfiguration.CONTAINER_JAR_PATTERN);
                        if (containerIncludeJarPattern == null)
                            containerIncludeJarPattern = __containerIncludeJarPattern;
                        else {
                            if (!containerIncludeJarPattern.contains(__containerIncludeJarPattern)) {
                                containerIncludeJarPattern = containerIncludeJarPattern + (StringUtil.isBlank(containerIncludeJarPattern) ? "" : "|") + __containerIncludeJarPattern;
                            }
                        }
                        handler.setAttribute(WebInfConfiguration.CONTAINER_JAR_PATTERN, containerIncludeJarPattern);
                        //check the configurations, if not explicitly set up, then configure all of them
                        if (handler instanceof WebAppContext) {
                            WebAppContext wac = (WebAppContext) handler;
                            if (wac.getConfigurationClasses() == null || wac.getConfigurationClasses().length == 0)
                                wac.setConfigurationClasses(__plusConfigurationClasses);
                        }
                    } else {
                        // assume it is a WAR file
                        WebAppContext webapp = new WebAppContext(_contexts, ctx.toString(), contextPath);
                        webapp.setConfigurationClasses(__plusConfigurationClasses);
                        webapp.setAttribute(WebInfConfiguration.CONTAINER_JAR_PATTERN, __containerIncludeJarPattern);
                    }
                }
                //reset
                contextPathSet = false;
                contextPath = __defaultContextPath;
                break;
        }
    }
    if (_server == null)
        usage("No Contexts defined");
    _server.setStopAtShutdown(true);
    switch((stopPort > 0 ? 1 : 0) + (stopKey != null ? 2 : 0)) {
        case 1:
            usage("Must specify --stop-key when --stop-port is specified");
            break;
        case 2:
            usage("Must specify --stop-port when --stop-key is specified");
            break;
        case 3:
            ShutdownMonitor monitor = ShutdownMonitor.getInstance();
            monitor.setPort(stopPort);
            monitor.setKey(stopKey);
            monitor.setExitVm(true);
            break;
    }
    if (_logFile != null) {
        NCSARequestLog requestLog = new NCSARequestLog(_logFile);
        requestLog.setExtended(false);
        _logHandler.setRequestLog(requestLog);
    }
}
Also used : SessionHandler(org.eclipse.jetty.server.session.SessionHandler) AbstractConnector(org.eclipse.jetty.server.AbstractConnector) ServerConnector(org.eclipse.jetty.server.ServerConnector) Connector(org.eclipse.jetty.server.Connector) ShutdownMonitor(org.eclipse.jetty.server.ShutdownMonitor) Server(org.eclipse.jetty.server.Server) ConnectionStatistics(org.eclipse.jetty.io.ConnectionStatistics) Constraint(org.eclipse.jetty.util.security.Constraint) ServletHolder(org.eclipse.jetty.servlet.ServletHolder) ArrayList(java.util.ArrayList) ContextHandlerCollection(org.eclipse.jetty.server.handler.ContextHandlerCollection) RolloverFileOutputStream(org.eclipse.jetty.util.RolloverFileOutputStream) XmlConfiguration(org.eclipse.jetty.xml.XmlConfiguration) ServerConnector(org.eclipse.jetty.server.ServerConnector) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler) ContextHandler(org.eclipse.jetty.server.handler.ContextHandler) WebAppContext(org.eclipse.jetty.webapp.WebAppContext) HashLoginService(org.eclipse.jetty.security.HashLoginService) BasicAuthenticator(org.eclipse.jetty.security.authentication.BasicAuthenticator) RequestLogHandler(org.eclipse.jetty.server.handler.RequestLogHandler) ConstraintSecurityHandler(org.eclipse.jetty.security.ConstraintSecurityHandler) NCSARequestLog(org.eclipse.jetty.server.NCSARequestLog) ContextHandlerCollection(org.eclipse.jetty.server.handler.ContextHandlerCollection) HandlerCollection(org.eclipse.jetty.server.handler.HandlerCollection) PrintStream(java.io.PrintStream) ConstraintMapping(org.eclipse.jetty.security.ConstraintMapping) Resource(org.eclipse.jetty.util.resource.Resource) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler) Handler(org.eclipse.jetty.server.Handler) DefaultHandler(org.eclipse.jetty.server.handler.DefaultHandler) ConstraintSecurityHandler(org.eclipse.jetty.security.ConstraintSecurityHandler) StatisticsHandler(org.eclipse.jetty.server.handler.StatisticsHandler) ContextHandler(org.eclipse.jetty.server.handler.ContextHandler) SessionHandler(org.eclipse.jetty.server.session.SessionHandler) RequestLogHandler(org.eclipse.jetty.server.handler.RequestLogHandler) Constraint(org.eclipse.jetty.util.security.Constraint) DefaultHandler(org.eclipse.jetty.server.handler.DefaultHandler) StatisticsServlet(org.eclipse.jetty.servlet.StatisticsServlet) StatisticsHandler(org.eclipse.jetty.server.handler.StatisticsHandler) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler) AbstractConnector(org.eclipse.jetty.server.AbstractConnector)

Example 2 with BasicAuthenticator

use of org.eclipse.jetty.security.authentication.BasicAuthenticator in project jetty.project by eclipse.

the class SpecExampleConstraintTest method testUncoveredHttpMethodDetection.

@Test
public void testUncoveredHttpMethodDetection() throws Exception {
    _security.setAuthenticator(new BasicAuthenticator());
    _server.start();
    Set<String> paths = _security.getPathsWithUncoveredHttpMethods();
    assertEquals(1, paths.size());
    assertEquals("/*", paths.iterator().next());
}
Also used : BasicAuthenticator(org.eclipse.jetty.security.authentication.BasicAuthenticator) Test(org.junit.Test)

Example 3 with BasicAuthenticator

use of org.eclipse.jetty.security.authentication.BasicAuthenticator in project jetty.project by eclipse.

the class ConstraintTest method testUncoveredHttpMethodDetection.

@Test
public void testUncoveredHttpMethodDetection() throws Exception {
    //Test no methods named
    Constraint constraint1 = new Constraint();
    constraint1.setAuthenticate(true);
    constraint1.setName("** constraint");
    //No methods named, no uncovered methods
    constraint1.setRoles(new String[] { Constraint.ANY_AUTH, "user" });
    ConstraintMapping mapping1 = new ConstraintMapping();
    mapping1.setPathSpec("/starstar/*");
    mapping1.setConstraint(constraint1);
    _security.setConstraintMappings(Collections.singletonList(mapping1));
    _security.setAuthenticator(new BasicAuthenticator());
    _server.start();
    Set<String> uncoveredPaths = _security.getPathsWithUncoveredHttpMethods();
    //no uncovered methods
    Assert.assertTrue(uncoveredPaths.isEmpty());
    //Test only an explicitly named method, no omissions to cover other methods
    Constraint constraint2 = new Constraint();
    constraint2.setAuthenticate(true);
    constraint2.setName("user constraint");
    constraint2.setRoles(new String[] { "user" });
    ConstraintMapping mapping2 = new ConstraintMapping();
    mapping2.setPathSpec("/user/*");
    mapping2.setMethod("GET");
    mapping2.setConstraint(constraint2);
    _security.addConstraintMapping(mapping2);
    uncoveredPaths = _security.getPathsWithUncoveredHttpMethods();
    Assert.assertNotNull(uncoveredPaths);
    Assert.assertEquals(1, uncoveredPaths.size());
    Assert.assertTrue(uncoveredPaths.contains("/user/*"));
    //Test an explicitly named method with a http-method-omission to cover all other methods
    Constraint constraint2a = new Constraint();
    constraint2a.setAuthenticate(true);
    constraint2a.setName("forbid constraint");
    ConstraintMapping mapping2a = new ConstraintMapping();
    mapping2a.setPathSpec("/user/*");
    mapping2a.setMethodOmissions(new String[] { "GET" });
    mapping2a.setConstraint(constraint2a);
    _security.addConstraintMapping(mapping2a);
    uncoveredPaths = _security.getPathsWithUncoveredHttpMethods();
    Assert.assertNotNull(uncoveredPaths);
    Assert.assertEquals(0, uncoveredPaths.size());
    //Test a http-method-omission only
    Constraint constraint3 = new Constraint();
    constraint3.setAuthenticate(true);
    constraint3.setName("omit constraint");
    ConstraintMapping mapping3 = new ConstraintMapping();
    mapping3.setPathSpec("/omit/*");
    mapping3.setMethodOmissions(new String[] { "GET", "POST" });
    mapping3.setConstraint(constraint3);
    _security.addConstraintMapping(mapping3);
    uncoveredPaths = _security.getPathsWithUncoveredHttpMethods();
    Assert.assertNotNull(uncoveredPaths);
    Assert.assertTrue(uncoveredPaths.contains("/omit/*"));
    _security.setDenyUncoveredHttpMethods(true);
    uncoveredPaths = _security.getPathsWithUncoveredHttpMethods();
    Assert.assertNotNull(uncoveredPaths);
    Assert.assertEquals(0, uncoveredPaths.size());
}
Also used : BasicAuthenticator(org.eclipse.jetty.security.authentication.BasicAuthenticator) Constraint(org.eclipse.jetty.util.security.Constraint) Test(org.junit.Test)

Example 4 with BasicAuthenticator

use of org.eclipse.jetty.security.authentication.BasicAuthenticator in project jetty.project by eclipse.

the class ConstraintTest method testDataRedirection.

@Test
public void testDataRedirection() throws Exception {
    _security.setAuthenticator(new BasicAuthenticator());
    _server.start();
    String response;
    response = _connector.getResponse("GET /ctx/data/info HTTP/1.0\r\n\r\n");
    Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 403"));
    _config.setSecurePort(8443);
    _config.setSecureScheme("https");
    response = _connector.getResponse("GET /ctx/data/info HTTP/1.0\r\n\r\n");
    Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 302 Found"));
    Assert.assertTrue(response.indexOf("Location") > 0);
    Assert.assertTrue(response.indexOf(":8443/ctx/data/info") > 0);
    Assert.assertThat(response, Matchers.not(Matchers.containsString("https:///")));
    _config.setSecurePort(443);
    response = _connector.getResponse("GET /ctx/data/info HTTP/1.0\r\n\r\n");
    Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 302 Found"));
    Assert.assertTrue(response.indexOf("Location") > 0);
    Assert.assertTrue(!response.contains(":443/ctx/data/info"));
    _config.setSecurePort(8443);
    response = _connector.getResponse("GET /ctx/data/info HTTP/1.0\r\nHost: wobble.com\r\n\r\n");
    Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 302 Found"));
    Assert.assertTrue(response.indexOf("Location") > 0);
    Assert.assertTrue(response.indexOf("https://wobble.com:8443/ctx/data/info") > 0);
    _config.setSecurePort(443);
    response = _connector.getResponse("GET /ctx/data/info HTTP/1.0\r\nHost: wobble.com\r\n\r\n");
    Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 302 Found"));
    Assert.assertTrue(response.indexOf("Location") > 0);
    Assert.assertTrue(!response.contains(":443"));
    Assert.assertTrue(response.indexOf("https://wobble.com/ctx/data/info") > 0);
}
Also used : BasicAuthenticator(org.eclipse.jetty.security.authentication.BasicAuthenticator) Test(org.junit.Test)

Example 5 with BasicAuthenticator

use of org.eclipse.jetty.security.authentication.BasicAuthenticator in project jetty.project by eclipse.

the class ConstraintTest method testStrictBasic.

@Test
public void testStrictBasic() throws Exception {
    _security.setAuthenticator(new BasicAuthenticator());
    _server.start();
    String response;
    response = _connector.getResponse("GET /ctx/noauth/info HTTP/1.0\r\n\r\n");
    Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 200 OK"));
    response = _connector.getResponse("GET /ctx/forbid/info HTTP/1.0\r\n\r\n");
    Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 403 Forbidden"));
    response = _connector.getResponse("GET /ctx/auth/info HTTP/1.0\r\n\r\n");
    Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 401 Unauthorized"));
    Assert.assertThat(response, Matchers.containsString("WWW-Authenticate: basic realm=\"TestRealm\""));
    response = _connector.getResponse("GET /ctx/auth/info HTTP/1.0\r\n" + "Authorization: Basic " + B64Code.encode("user:wrong") + "\r\n" + "\r\n");
    Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 401 Unauthorized"));
    Assert.assertThat(response, Matchers.containsString("WWW-Authenticate: basic realm=\"TestRealm\""));
    response = _connector.getResponse("GET /ctx/auth/info HTTP/1.0\r\n" + "Authorization: Basic " + B64Code.encode("user3:password") + "\r\n" + "\r\n");
    Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 403"));
    response = _connector.getResponse("GET /ctx/auth/info HTTP/1.0\r\n" + "Authorization: Basic " + B64Code.encode("user2:password") + "\r\n" + "\r\n");
    Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 200 OK"));
    // test admin
    response = _connector.getResponse("GET /ctx/admin/info HTTP/1.0\r\n\r\n");
    Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 401 Unauthorized"));
    Assert.assertThat(response, Matchers.containsString("WWW-Authenticate: basic realm=\"TestRealm\""));
    response = _connector.getResponse("GET /ctx/admin/info HTTP/1.0\r\n" + "Authorization: Basic " + B64Code.encode("admin:wrong") + "\r\n" + "\r\n");
    Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 401 Unauthorized"));
    Assert.assertThat(response, Matchers.containsString("WWW-Authenticate: basic realm=\"TestRealm\""));
    response = _connector.getResponse("GET /ctx/admin/info HTTP/1.0\r\n" + "Authorization: Basic " + B64Code.encode("user:password") + "\r\n" + "\r\n");
    Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 403 "));
    Assert.assertThat(response, Matchers.containsString("!role"));
    response = _connector.getResponse("GET /ctx/admin/info HTTP/1.0\r\n" + "Authorization: Basic " + B64Code.encode("admin:password") + "\r\n" + "\r\n");
    Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 200 OK"));
    response = _connector.getResponse("GET /ctx/admin/relax/info HTTP/1.0\r\n\r\n");
    Assert.assertThat(response, Matchers.startsWith("HTTP/1.1 200 OK"));
}
Also used : BasicAuthenticator(org.eclipse.jetty.security.authentication.BasicAuthenticator) Test(org.junit.Test)

Aggregations

BasicAuthenticator (org.eclipse.jetty.security.authentication.BasicAuthenticator)40 Constraint (org.eclipse.jetty.util.security.Constraint)27 ConstraintMapping (org.eclipse.jetty.security.ConstraintMapping)17 ConstraintSecurityHandler (org.eclipse.jetty.security.ConstraintSecurityHandler)17 HashLoginService (org.eclipse.jetty.security.HashLoginService)17 Test (org.junit.Test)12 Server (org.eclipse.jetty.server.Server)6 HashSet (java.util.HashSet)3 ServletContextHandler (org.eclipse.jetty.servlet.ServletContextHandler)3 Password (org.eclipse.jetty.util.security.Password)3 WebAppContext (org.eclipse.jetty.webapp.WebAppContext)3 File (java.io.File)2 ArrayList (java.util.ArrayList)2 LoginService (org.eclipse.jetty.security.LoginService)2 ClientCertAuthenticator (org.eclipse.jetty.security.authentication.ClientCertAuthenticator)2 DigestAuthenticator (org.eclipse.jetty.security.authentication.DigestAuthenticator)2 FormAuthenticator (org.eclipse.jetty.security.authentication.FormAuthenticator)2 SpnegoAuthenticator (org.eclipse.jetty.security.authentication.SpnegoAuthenticator)2 Connector (org.eclipse.jetty.server.Connector)2 Handler (org.eclipse.jetty.server.Handler)2