private static void addAuthHandler( Server server, String auth, LoginAuthenticator authenticator, Handler handler) { server.addBean(LOGIN_SERVICE); Constraint constraint = new Constraint(); constraint.setName(auth); constraint.setRoles(new String[] {USER, ADMIN}); constraint.setAuthenticate(true); ConstraintMapping mapping = new ConstraintMapping(); mapping.setConstraint(constraint); mapping.setPathSpec("/*"); Set<String> knownRoles = new HashSet<>(); knownRoles.add(USER); knownRoles.add(ADMIN); List<ConstraintMapping> cm = new ArrayList<>(); cm.add(mapping); ConstraintSecurityHandler security = new ConstraintSecurityHandler(); security.setConstraintMappings(cm, knownRoles); security.setAuthenticator(authenticator); security.setLoginService(LOGIN_SERVICE); security.setHandler(handler); server.setHandler(security); }
public static final SecurityHandler basicAuth(AuthConfig config) { ConstraintSecurityHandler securityHandler = new ConstraintSecurityHandler(); securityHandler.setAuthenticator(new BasicAuthenticator()); securityHandler.setRealmName(config.getRealm()); ConstraintMapping constraintMapping = new ConstraintMapping(); Constraint constraint = new Constraint(Constraint.__BASIC_AUTH, USER_ROLE); constraint.setAuthenticate(true); constraintMapping.setConstraint(constraint); constraintMapping.setPathSpec("/*"); securityHandler.addConstraintMapping(constraintMapping); HashLoginService loginService = new HashLoginService(); loginService.putUser( config.getUsername(), Credential.getCredential(config.getPassword()), new String[] {USER_ROLE}); loginService.setName(config.getRealm()); securityHandler.setLoginService(loginService); return securityHandler; }
private static SecurityHandler createSecurityHandler(LoginService loginService) { Constraint constraint = new Constraint(); constraint.setAuthenticate(false); ConstraintMapping constraintMapping = new ConstraintMapping(); constraintMapping.setConstraint(constraint); constraintMapping.setPathSpec("/*"); ConstraintSecurityHandler securityHandler = new ConstraintSecurityHandler(); securityHandler.setLoginService(loginService); // TODO: support for other auth schemes (digest, etc) securityHandler.setAuthenticator(new BasicAuthenticator()); securityHandler.setConstraintMappings(Arrays.asList(constraintMapping)); return securityHandler; }
public AuthenticationServer(Integer port) { server = new BlockingServer(port); Constraint constraint = new Constraint(); constraint.setName(Constraint.__BASIC_AUTH); constraint.setRoles(new String[] {"user", "admin", "moderator"}); constraint.setAuthenticate(true); ConstraintMapping cm = new ConstraintMapping(); cm.setConstraint(constraint); cm.setPathSpec("/*"); ConstraintSecurityHandler sh = new ConstraintSecurityHandler(); loginService = new HashLoginService("MyRealm"); sh.setLoginService(loginService); sh.setConstraintMappings(new ConstraintMapping[] {cm}); sh.setStrict(false); accessedUri = new ArrayList<String>(); Handler handler = new AbstractHandler() { public void handle( String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); response.setStatus(HttpServletResponse.SC_OK); response.getWriter().println("<h1>Hello</h1>"); ((Request) request).setHandled(true); accessedUri.add(((Request) request).getUri().toString()); } }; HandlerCollection handlers = new HandlerCollection(); handlers.setHandlers(new Handler[] {handler, new DefaultHandler()}); sh.setHandler(handlers); server.setHandler(sh); }
private static final SecurityHandler basicAuth(String realm) { OpenfireLoginService l = new OpenfireLoginService(); l.setName(realm); Constraint constraint = new Constraint(); constraint.setName(Constraint.__BASIC_AUTH); constraint.setRoles(new String[] {"jmxweb"}); constraint.setAuthenticate(true); ConstraintMapping cm = new ConstraintMapping(); cm.setConstraint(constraint); cm.setPathSpec("/*"); ConstraintSecurityHandler csh = new ConstraintSecurityHandler(); csh.setAuthenticator(new BasicAuthenticator()); csh.setRealmName(realm); csh.addConstraintMapping(cm); csh.setLoginService(l); return csh; }
private void start(Authenticator authenticator, Handler handler) throws Exception { server = new Server(); File realmFile = MavenTestingUtils.getTestResourceFile("realm.properties"); LoginService loginService = new HashLoginService(realm, realmFile.getAbsolutePath()); server.addBean(loginService); ConstraintSecurityHandler securityHandler = new ConstraintSecurityHandler(); Constraint constraint = new Constraint(); constraint.setAuthenticate(true); constraint.setRoles(new String[] {"*"}); ConstraintMapping mapping = new ConstraintMapping(); mapping.setPathSpec("/secure"); mapping.setConstraint(constraint); securityHandler.addConstraintMapping(mapping); securityHandler.setAuthenticator(authenticator); securityHandler.setLoginService(loginService); securityHandler.setStrict(false); securityHandler.setHandler(handler); start(securityHandler); }
private SecurityHandler getSecurityHandler() throws IOException { Constraint constraint = new Constraint(Constraint.__BASIC_AUTH, "websocket"); constraint.setAuthenticate(true); ConstraintMapping cm = new ConstraintMapping(); cm.setPathSpec("/openicf/*"); cm.setConstraint(constraint); ConstraintSecurityHandler sh = new ConstraintSecurityHandler(); sh.setAuthenticator(new BasicAuthenticator()); sh.setConstraintMappings(Arrays.asList(new ConstraintMapping[] {cm})); MappedLoginService loginService = new MappedLoginService() { @Override protected UserIdentity loadUser(String username) { return null; } @Override protected void loadUsers() throws IOException { Credential credential = Credential.getCredential(DEFAULT_PASSWORD); String[] roles = new String[] {"websocket"}; putUser("plain", credential, roles); putUser("secure", credential, roles); putUser("proxy", credential, roles); putUser("anonymous", credential, roles); } }; loginService.setName("OpenICF-Service"); sh.setLoginService(loginService); sh.setConstraintMappings(Arrays.asList(new ConstraintMapping[] {cm})); return sh; }
public void start(String args[]) { Logger.getRootLogger().setLevel(Level.ERROR); PropertiesManager pm = new PropertiesManager(); File propFile = new File(propFileName); if (propFile.isFile()) pm.join(propFile); pm.importSystemProps(); try { pm.update(); } catch (IllegalArgumentException e) { System.err.println("invalid configuration, can't start: " + e.getMessage()); System.exit(1); } if (pm.withjmx) { doJmx(pm); } System.setProperty("org.eclipse.jetty.util.log.class", "org.eclipse.jetty.util.log.Slf4jLog"); System.setProperty("org.eclipse.jetty.LEVEL", "DEBUG"); final Server server = new Server(); ServerConnector connector = new ServerConnector(server); if (host != null) { connector.setHost(host); } connector.setPort(port); // Let's try to start the connector before the application try { connector.open(); } catch (IOException e) { connector.close(); throw new RuntimeException("Jetty server failed to start", e); } server.setConnectors(new Connector[] {connector}); WebAppContext webapp = new WebAppContext(); webapp.setContextPath("/"); webapp.setResourceBase(webRoot); webapp.setClassLoader(getClass().getClassLoader()); webapp.setInitParameter("propertiesFile", propFileName); ResourceHandler staticFiles = new ResourceHandler(); staticFiles.setWelcomeFiles(new String[] {"index.html"}); staticFiles.setResourceBase(webRoot); if (pm.security) { LoginService loginService = new HashLoginService("jrds", pm.userfile); server.addBean(loginService); Authenticator auth = new BasicAuthenticator(); Constraint constraint = new Constraint(); constraint.setName("jrds"); constraint.setRoles(new String[] {Constraint.ANY_ROLE}); constraint.setAuthenticate(true); constraint.setDataConstraint(Constraint.DC_NONE); ConstraintMapping cm = new ConstraintMapping(); cm.setConstraint(constraint); cm.setPathSpec("/*"); ConstraintSecurityHandler sh = new ConstraintSecurityHandler(); sh.setConstraintMappings(Collections.singletonList(cm)); sh.setAuthenticator(auth); webapp.setSecurityHandler(sh); } HandlerCollection handlers = new HandlerList(); handlers.setHandlers(new Handler[] {staticFiles, webapp}); server.setHandler(handlers); if (pm.withjmx || MBeanServerFactory.findMBeanServer(null).size() > 0) { MBeanServer mbs = java.lang.management.ManagementFactory.getPlatformMBeanServer(); server.addBean(new MBeanContainer(mbs)); handlers.addHandler(new StatisticsHandler()); } // Properties are not needed any more pm = null; Thread finish = new Thread() { public void run() { try { server.stop(); } catch (Exception e) { throw new RuntimeException("Jetty server failed to stop", e); } } }; Runtime.getRuntime().addShutdownHook(finish); try { server.start(); server.join(); } catch (Exception e) { throw new RuntimeException("Jetty server failed to start", e); } }
protected void initializeServerWithConfig(final JUnitHttpServer config) { Server server = null; if (config.https()) { server = new Server(); final SslContextFactory factory = new SslContextFactory(config.keystore()); factory.setKeyStorePath(config.keystore()); factory.setKeyStorePassword(config.keystorePassword()); factory.setKeyManagerPassword(config.keyPassword()); factory.setTrustStore(config.keystore()); factory.setTrustStorePassword(config.keystorePassword()); final SslSocketConnector connector = new SslSocketConnector(factory); connector.setPort(config.port()); server.setConnectors(new Connector[] {connector}); } else { server = new Server(config.port()); } m_server = server; final ContextHandler context1 = new ContextHandler(); context1.setContextPath("/"); context1.setWelcomeFiles(new String[] {"index.html"}); context1.setResourceBase(config.resource()); context1.setClassLoader(Thread.currentThread().getContextClassLoader()); context1.setVirtualHosts(config.vhosts()); final ContextHandler context = context1; Handler topLevelHandler = null; final HandlerList handlers = new HandlerList(); if (config.basicAuth()) { // check for basic auth if we're configured to do so LOG.debug("configuring basic auth"); final HashLoginService loginService = new HashLoginService("MyRealm", config.basicAuthFile()); loginService.setRefreshInterval(300000); m_server.addBean(loginService); final ConstraintSecurityHandler security = new ConstraintSecurityHandler(); final Set<String> knownRoles = new HashSet<String>(); knownRoles.add("user"); knownRoles.add("admin"); knownRoles.add("moderator"); final Constraint constraint = new Constraint(); constraint.setName("auth"); constraint.setAuthenticate(true); constraint.setRoles(knownRoles.toArray(new String[0])); final ConstraintMapping mapping = new ConstraintMapping(); mapping.setPathSpec("/*"); mapping.setConstraint(constraint); security.setConstraintMappings(Collections.singletonList(mapping), knownRoles); security.setAuthenticator(new BasicAuthenticator()); security.setLoginService(loginService); security.setStrict(false); security.setRealmName("MyRealm"); security.setHandler(context); topLevelHandler = security; } else { topLevelHandler = context; } final Webapp[] webapps = config.webapps(); if (webapps != null) { for (final Webapp webapp : webapps) { final WebAppContext wac = new WebAppContext(); String path = null; if (!"".equals(webapp.pathSystemProperty()) && System.getProperty(webapp.pathSystemProperty()) != null) { path = System.getProperty(webapp.pathSystemProperty()); } else { path = webapp.path(); } if (path == null || "".equals(path)) { throw new IllegalArgumentException( "path or pathSystemProperty of @Webapp points to a null or blank value"); } wac.setWar(path); wac.setContextPath(webapp.context()); handlers.addHandler(wac); } } final ResourceHandler rh = new ResourceHandler(); rh.setWelcomeFiles(new String[] {"index.html"}); rh.setResourceBase(config.resource()); handlers.addHandler(rh); // fall through to default handlers.addHandler(new DefaultHandler()); context.setHandler(handlers); m_server.setHandler(topLevelHandler); }
public static void main(String[] args) throws Exception { ReplayProps.Init(); ReplayDB.init(); ReplayLogger.log(Level.INFO, "Log opened..."); org.eclipse.jetty.util.log.Log.setLog(ReplayLogger.replayLogger); final int quickTaskFrequencyInSeconds = ReplayProps.getInt("quickTaskFrequencyInSeconds", "10"); final int longTaskFrequencyInHours = ReplayProps.getInt("longTaskFrequencyInHours", "1"); timer = new Timer(); if (quickTaskFrequencyInSeconds != 0) { timer.schedule( new CleanupTask.QuickTask(), quickTaskFrequencyInSeconds * 1000, quickTaskFrequencyInSeconds * 1000); } if (quickTaskFrequencyInSeconds != 0) { timer.schedule( new CleanupTask.LongTask(), 60 * 60 * 1000 * longTaskFrequencyInHours, 60 * 60 * 1000 * longTaskFrequencyInHours); } final int httpPort = ReplayProps.getInt("httpPort", "80"); final Server server = new Server(httpPort); ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS | ServletContextHandler.SECURITY); context.setContextPath("/"); server.setHandler(context); // Change default timeout to 45 seconds (from 30) /* ServerConnector http = new ServerConnector( server ); //http.setHost( "localhost" ); http.setPort( httpPort ); http.setIdleTimeout( 45000 ); server.addConnector( http ); */ final boolean bTestAuthorize = false; if (bTestAuthorize) { context.addServlet( new ServletHolder( new HttpServlet() { private static final long serialVersionUID = 1L; @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { final ServletInputStream inputStream = request.getInputStream(); FileUtils.ReplayOutputStream outputStream = FileUtils.getReplayOutputStream("authorize.txt", false); byte[] buffer = new byte[1024]; int readBytes = 0; while ((readBytes = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, readBytes); } inputStream.close(); outputStream.close(); response.setContentType("text/html"); response .getWriter() .println("<p>Worked: " + request.getContentType() + " </p><br>"); } }), "/j_security_check"); } context.addServlet(new ServletHolder(new Download()), "/download/*"); context.addServlet(new ServletHolder(new DownloadEvent()), "/downloadevent/*"); context.addServlet(new ServletHolder(new Upload()), "/upload/*"); context.addServlet(new ServletHolder(new UploadEvent()), "/uploadevent/*"); context.addServlet(new ServletHolder(new StartUploading()), "/startuploading/*"); context.addServlet(new ServletHolder(new StopUploading()), "/stopuploading/*"); context.addServlet(new ServletHolder(new StartDownloading()), "/startdownloading/*"); context.addServlet(new ServletHolder(new DeleteSession()), "/deletesession/*"); context.addServlet(new ServletHolder(new EnumerateSessions()), "/enumsessions/*"); context.addServlet(new ServletHolder(new EnumEvents()), "/enumevents/*"); context.addServlet(new ServletHolder(new RefreshViewer()), "/refreshviewer/*"); context.addServlet(new ServletHolder(new ViewFile()), "/viewfile/*"); if (ReplayProps.getInt("enableBuiltInWebServer", "1") == 1) { context.addServlet(new ServletHolder(new Index()), "/*"); } // Password protect the delete session page context.addServlet( new ServletHolder( new HttpServlet() { private static final long serialVersionUID = 1L; @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); response .getWriter() .append( "<form method='POST' action='/j_security_check'>" + "<input type='text' name='j_username'/>" + "<input type='password' name='j_password'/>" + "<input type='submit' value='Login'/></form>"); } }), "/login"); final Constraint constraint = new Constraint(); constraint.setName(Constraint.__FORM_AUTH); constraint.setRoles(new String[] {"user", "admin", "moderator"}); constraint.setAuthenticate(true); final ConstraintMapping constraintMapping = new ConstraintMapping(); constraintMapping.setConstraint(constraint); constraintMapping.setPathSpec("/deletesession/*"); final ConstraintSecurityHandler securityHandler = new ConstraintSecurityHandler(); securityHandler.addConstraintMapping(constraintMapping); HashLoginService loginService = new HashLoginService(); loginService.putUser("usern", new Password("pass"), new String[] {"user"}); loginService.putUser("admin", new Password("pass"), new String[] {"admin"}); securityHandler.setLoginService(loginService); final FormAuthenticator authenticator = new FormAuthenticator("/login", "/login", false); securityHandler.setAuthenticator(authenticator); if (!bTestAuthorize) { context.setSecurityHandler(securityHandler); } server.start(); server.join(); ReplayDB.shutdown(); }
/** * 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": ++i; // skip break; case "--jar": ++i; // skip break; case "--classes": ++i; // skip break; case "--stats": _enableStats = true; _statsPropFile = args[++i]; _statsPropFile = ("unsecure".equalsIgnoreCase(_statsPropFile) ? null : _statsPropFile); break; default: // process contexts if (!runnerServerInitialized) // log handlers not registered, server maybe not created, // etc { if (_server == null) // server not initialized yet { // 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 ConnectorStatistics()); } else { if (_enableStats) { for (Connector connector : connectors) { ((AbstractConnector) connector).addBean(new ConnectorStatistics()); } } } 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().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); handler.setAttribute( "org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern", __containerIncludeJarPattern); } else { // assume it is a WAR file WebAppContext webapp = new WebAppContext(_contexts, ctx.toString(), contextPath); webapp.setConfigurationClasses(__plusConfigurationClasses); webapp.setAttribute( "org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern", __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); } }
protected void createServer(Connector connector) throws Exception { _server.setConnectors(new Connector[] {connector}); if (H2O.ARGS.hash_login || H2O.ARGS.ldap_login) { // REFER TO // http://www.eclipse.org/jetty/documentation/9.1.4.v20140401/embedded-examples.html#embedded-secured-hello-handler if (H2O.ARGS.login_conf == null) { Log.err("Must specify -login_conf argument"); H2O.exit(1); } LoginService loginService; if (H2O.ARGS.hash_login) { Log.info("Configuring HashLoginService"); loginService = new HashLoginService("H2O", H2O.ARGS.login_conf); } else if (H2O.ARGS.ldap_login) { Log.info("Configuring JAASLoginService (with LDAP)"); System.setProperty("java.security.auth.login.config", H2O.ARGS.login_conf); loginService = new JAASLoginService("ldaploginmodule"); } else { throw H2O.fail(); } IdentityService identityService = new DefaultIdentityService(); loginService.setIdentityService(identityService); _server.addBean(loginService); // Set a security handler as the first handler in the chain. ConstraintSecurityHandler security = new ConstraintSecurityHandler(); // Set up a constraint to authenticate all calls, and allow certain roles in. Constraint constraint = new Constraint(); constraint.setName("auth"); constraint.setAuthenticate(true); // Configure role stuff (to be disregarded). We are ignoring roles, and only going off the // user name. // // Jetty 8 and prior. // // Jetty 8 requires the security.setStrict(false) and ANY_ROLE. security.setStrict(false); constraint.setRoles(new String[] {Constraint.ANY_ROLE}); // Jetty 9 and later. // // Jetty 9 and later uses a different servlet spec, and ANY_AUTH gives the same behavior // for that API version as ANY_ROLE did previously. This required some low-level // debugging // to figure out, so I'm documenting it here. // Jetty 9 did not require security.setStrict(false). // // constraint.setRoles(new String[]{Constraint.ANY_AUTH}); ConstraintMapping mapping = new ConstraintMapping(); mapping.setPathSpec("/*"); // Lock down all API calls mapping.setConstraint(constraint); security.setConstraintMappings(Collections.singletonList(mapping)); // Authentication / Authorization security.setAuthenticator(new BasicAuthenticator()); security.setLoginService(loginService); // Pass-through to H2O if authenticated. registerHandlers(security); _server.setHandler(security); } else { registerHandlers(_server); } _server.start(); }
@Before public void setupSecurity() { _security = new ConstraintSecurityHandler(); _session.setHandler(_security); RequestHandler _handler = new RequestHandler(); _security.setHandler(_handler); /* <security-constraint> <web-resource-collection> <web-resource-name>precluded methods</web-resource-name> <url-pattern>/*</url-pattern> <url-pattern>/acme/wholesale/*</url-pattern> <url-pattern>/acme/retail/*</url-pattern> <http-method-exception>GET</http-method-exception> <http-method-exception>POST</http-method-exception> </web-resource-collection> <auth-constraint/> </security-constraint> */ Constraint constraint0 = new Constraint(); constraint0.setAuthenticate(true); constraint0.setName("precluded methods"); ConstraintMapping mapping0 = new ConstraintMapping(); mapping0.setPathSpec("/*"); mapping0.setConstraint(constraint0); mapping0.setMethodOmissions(new String[] {"GET", "POST"}); ConstraintMapping mapping1 = new ConstraintMapping(); mapping1.setPathSpec("/acme/wholesale/*"); mapping1.setConstraint(constraint0); mapping1.setMethodOmissions(new String[] {"GET", "POST"}); ConstraintMapping mapping2 = new ConstraintMapping(); mapping2.setPathSpec("/acme/retail/*"); mapping2.setConstraint(constraint0); mapping2.setMethodOmissions(new String[] {"GET", "POST"}); /* <security-constraint> <web-resource-collection> <web-resource-name>wholesale</web-resource-name> <url-pattern>/acme/wholesale/*</url-pattern> <http-method>GET</http-method> <http-method>PUT</http-method> </web-resource-collection> <auth-constraint> <role-name>SALESCLERK</role-name> </auth-constraint> </security-constraint> */ Constraint constraint1 = new Constraint(); constraint1.setAuthenticate(true); constraint1.setName("wholesale"); constraint1.setRoles(new String[] {"SALESCLERK"}); ConstraintMapping mapping3 = new ConstraintMapping(); mapping3.setPathSpec("/acme/wholesale/*"); mapping3.setConstraint(constraint1); mapping3.setMethod("GET"); ConstraintMapping mapping4 = new ConstraintMapping(); mapping4.setPathSpec("/acme/wholesale/*"); mapping4.setConstraint(constraint1); mapping4.setMethod("PUT"); /* <security-constraint> <web-resource-collection> <web-resource-name>wholesale 2</web-resource-name> <url-pattern>/acme/wholesale/*</url-pattern> <http-method>GET</http-method> <http-method>POST</http-method> </web-resource-collection> <auth-constraint> <role-name>CONTRACTOR</role-name> </auth-constraint> <user-data-constraint> <transport-guarantee>CONFIDENTIAL</transport-guarantee> </user-data-constraint> </security-constraint> */ Constraint constraint2 = new Constraint(); constraint2.setAuthenticate(true); constraint2.setName("wholesale 2"); constraint2.setRoles(new String[] {"CONTRACTOR"}); constraint2.setDataConstraint(Constraint.DC_CONFIDENTIAL); ConstraintMapping mapping5 = new ConstraintMapping(); mapping5.setPathSpec("/acme/wholesale/*"); mapping5.setMethod("GET"); mapping5.setConstraint(constraint2); ConstraintMapping mapping6 = new ConstraintMapping(); mapping6.setPathSpec("/acme/wholesale/*"); mapping6.setMethod("POST"); mapping6.setConstraint(constraint2); /* <security-constraint> <web-resource-collection> <web-resource-name>retail</web-resource-name> <url-pattern>/acme/retail/*</url-pattern> <http-method>GET</http-method> <http-method>POST</http-method> </web-resource-collection> <auth-constraint> <role-name>CONTRACTOR</role-name> <role-name>HOMEOWNER</role-name> </auth-constraint> </security-constraint> */ Constraint constraint4 = new Constraint(); constraint4.setName("retail"); constraint4.setAuthenticate(true); constraint4.setRoles(new String[] {"CONTRACTOR", "HOMEOWNER"}); ConstraintMapping mapping7 = new ConstraintMapping(); mapping7.setPathSpec("/acme/retail/*"); mapping7.setMethod("GET"); mapping7.setConstraint(constraint4); ConstraintMapping mapping8 = new ConstraintMapping(); mapping8.setPathSpec("/acme/retail/*"); mapping8.setMethod("POST"); mapping8.setConstraint(constraint4); Set<String> knownRoles = new HashSet<String>(); knownRoles.add("CONTRACTOR"); knownRoles.add("HOMEOWNER"); knownRoles.add("SALESCLERK"); _security.setConstraintMappings( Arrays.asList( new ConstraintMapping[] { mapping0, mapping1, mapping2, mapping3, mapping4, mapping5, mapping6, mapping7, mapping8 }), knownRoles); }