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; }
public static final void main(String args[]) throws Exception { // Create the server Server server = new Server(8080); // Enable parsing of jndi-related parts of web.xml and jetty-env.xml org.eclipse.jetty.webapp.Configuration.ClassList classlist = org.eclipse.jetty.webapp.Configuration.ClassList.setServerDefault(server); classlist.addAfter( "org.eclipse.jetty.webapp.FragmentConfiguration", "org.eclipse.jetty.plus.webapp.EnvConfiguration", "org.eclipse.jetty.plus.webapp.PlusConfiguration"); classlist.addBefore( "org.eclipse.jetty.webapp.JettyWebXmlConfiguration", "org.eclipse.jetty.annotations.AnnotationConfiguration"); // Create a WebApp WebAppContext webapp = new WebAppContext(); webapp.setContextPath("/"); webapp.setWar( "../../tests/test-webapps/test-servlet-spec/test-spec-webapp/target/test-spec-webapp-9.1.0-SNAPSHOT.war"); webapp.setAttribute( "org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern", ".*/javax.servlet-[^/]*\\.jar$|.*/servlet-api-[^/]*\\.jar$"); server.setHandler(webapp); // Register new transaction manager in JNDI // At runtime, the webapp accesses this as java:comp/UserTransaction org.eclipse.jetty.plus.jndi.Transaction transactionMgr = new org.eclipse.jetty.plus.jndi.Transaction(new com.acme.MockUserTransaction()); // Define an env entry with webapp scope. org.eclipse.jetty.plus.jndi.EnvEntry maxAmount = new org.eclipse.jetty.plus.jndi.EnvEntry(webapp, "maxAmount", new Double(100), true); // Register a mock DataSource scoped to the webapp org.eclipse.jetty.plus.jndi.Resource mydatasource = new org.eclipse.jetty.plus.jndi.Resource( webapp, "jdbc/mydatasource", new com.acme.MockDataSource()); // Configure a LoginService HashLoginService loginService = new HashLoginService(); loginService.setName("Test Realm"); loginService.setConfig("src/test/resources/realm.properties"); server.addBean(loginService); server.start(); server.join(); }
/** Creates a basic auth security handler. */ private SecurityHandler createSecurityHandler() { HashLoginService l = new HashLoginService(); for (String[] userInfo : TestUsers.USERS) { String user = userInfo[0]; String pwd = userInfo[1]; String[] roles = new String[] {"apiuser"}; if (user.startsWith("admin")) roles = new String[] {"apiuser", "apiadmin"}; l.putUser(user, Credential.getCredential(pwd), roles); } l.setName("apimanrealm"); ConstraintSecurityHandler csh = new ConstraintSecurityHandler(); csh.setAuthenticator(new BasicAuthenticator()); csh.setRealmName("apimanrealm"); csh.setLoginService(l); return csh; }
public Server getJettyServer(int port, int sslPort, int maxThreads) throws IOException { Server server = new Server(); HandlerCollection handlers = new HandlerCollection(); ContextHandlerCollection contexts = new ContextHandlerCollection(); server.setThreadPool(new QueuedThreadPool(maxThreads)); SslSocketConnector sslSocketConnector = null; if (sslPort > 0) { System.out.println("SSL is Starting on port " + sslPort + "..."); sslSocketConnector = new SslSocketConnector(); sslSocketConnector.setPort(getContainerConfig().getSSLPort()); sslSocketConnector.setKeystore("conf/servertestkeystore"); sslSocketConnector.setPassword(getContainerConfig().getSSLKeyPassword()); sslSocketConnector.setKeyPassword(getContainerConfig().getSSLKeyStorePassword()); sslSocketConnector.setTruststore("conf/servertestkeystore"); sslSocketConnector.setTrustPassword(getContainerConfig().getSSLKeyStorePassword()); } else if (getContainerConfig().isAcEnabled()) logger.error("SSL MUST be configured in the gsn.xml file when Access Control is enabled !"); AbstractConnector connector = new SelectChannelConnector(); // before was connector//new SocketConnector ();//using basic // connector for windows bug; Fast // option=>SelectChannelConnector connector.setPort(port); connector.setMaxIdleTime(30000); connector.setAcceptors(2); connector.setConfidentialPort(sslPort); if (sslSocketConnector == null) server.setConnectors(new Connector[] {connector}); else server.setConnectors(new Connector[] {connector, sslSocketConnector}); WebAppContext webAppContext = new WebAppContext(contexts, DEFAULT_WEB_APP_PATH, "/"); handlers.setHandlers(new Handler[] {contexts, new DefaultHandler()}); server.setHandler(handlers); Properties usernames = new Properties(); usernames.load(new FileReader("conf/realm.properties")); if (!usernames.isEmpty()) { HashLoginService loginService = new HashLoginService(); loginService.setName("GSNRealm"); loginService.setConfig("conf/realm.properties"); loginService.setRefreshInterval(10000); // re-reads the file every 10 seconds. Constraint constraint = new Constraint(); constraint.setName("GSN User"); constraint.setRoles(new String[] {"gsnuser"}); constraint.setAuthenticate(true); ConstraintMapping cm = new ConstraintMapping(); cm.setConstraint(constraint); cm.setPathSpec("/*"); cm.setMethod("GET"); ConstraintMapping cm2 = new ConstraintMapping(); cm2.setConstraint(constraint); cm2.setPathSpec("/*"); cm2.setMethod("POST"); ConstraintSecurityHandler securityHandler = new ConstraintSecurityHandler(); securityHandler.setLoginService(loginService); securityHandler.setConstraintMappings(new ConstraintMapping[] {cm, cm2}); securityHandler.setAuthenticator(new BasicAuthenticator()); webAppContext.setSecurityHandler(securityHandler); } server.setSendServerVersion(true); server.setStopAtShutdown(true); server.setSendServerVersion(false); server.setSessionIdManager(new HashSessionIdManager(new Random())); return server; }
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(); }
public void addUser(String name, String password, String... roles) { loginService.putUser(name, Credential.getCredential(password), roles); }
public static void main(String[] args) throws Exception { String jetty_home = System.getProperty("jetty.home", "../../jetty-distribution/target/distribution"); System.setProperty("jetty.home", jetty_home); // Setup Threadpool QueuedThreadPool threadPool = new QueuedThreadPool(512); Server server = new Server(threadPool); server.manage(threadPool); server.setDumpAfterStart(false); server.setDumpBeforeStop(false); // Setup JMX MBeanContainer mbContainer = new MBeanContainer(ManagementFactory.getPlatformMBeanServer()); server.addBean(mbContainer); // Common HTTP configuration HttpConfiguration config = new HttpConfiguration(); config.setSecurePort(8443); config.addCustomizer(new ForwardedRequestCustomizer()); config.addCustomizer(new SecureRequestCustomizer()); config.setSendServerVersion(true); // Http Connector HttpConnectionFactory http = new HttpConnectionFactory(config); ServerConnector httpConnector = new ServerConnector(server, http); httpConnector.setPort(8080); httpConnector.setIdleTimeout(10000); server.addConnector(httpConnector); // SSL configurations SslContextFactory sslContextFactory = new SslContextFactory(); sslContextFactory.setKeyStorePath(jetty_home + "/etc/keystore"); sslContextFactory.setKeyStorePassword("OBF:1vny1zlo1x8e1vnw1vn61x8g1zlu1vn4"); sslContextFactory.setKeyManagerPassword("OBF:1u2u1wml1z7s1z7a1wnl1u2g"); sslContextFactory.setTrustStorePath(jetty_home + "/etc/keystore"); sslContextFactory.setTrustStorePassword("OBF:1vny1zlo1x8e1vnw1vn61x8g1zlu1vn4"); sslContextFactory.setExcludeCipherSuites( "SSL_RSA_WITH_DES_CBC_SHA", "SSL_DHE_RSA_WITH_DES_CBC_SHA", "SSL_DHE_DSS_WITH_DES_CBC_SHA", "SSL_RSA_EXPORT_WITH_RC4_40_MD5", "SSL_RSA_EXPORT_WITH_DES40_CBC_SHA", "SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA", "SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA"); // Spdy Connector SPDYServerConnectionFactory.checkNPNAvailable(); PushStrategy push = new ReferrerPushStrategy(); HTTPSPDYServerConnectionFactory spdy2 = new HTTPSPDYServerConnectionFactory(2, config, push); spdy2.setInputBufferSize(8192); spdy2.setInitialWindowSize(32768); HTTPSPDYServerConnectionFactory spdy3 = new HTTPSPDYServerConnectionFactory(3, config, push); spdy2.setInputBufferSize(8192); NPNServerConnectionFactory npn = new NPNServerConnectionFactory( spdy3.getProtocol(), spdy2.getProtocol(), http.getProtocol()); npn.setDefaultProtocol(http.getProtocol()); npn.setInputBufferSize(1024); SslConnectionFactory ssl = new SslConnectionFactory(sslContextFactory, npn.getProtocol()); ServerConnector spdyConnector = new ServerConnector(server, ssl, npn, spdy3, spdy2, http); spdyConnector.setPort(8443); server.addConnector(spdyConnector); // Setup handlers HandlerCollection handlers = new HandlerCollection(); ContextHandlerCollection contexts = new ContextHandlerCollection(); RequestLogHandler requestLogHandler = new RequestLogHandler(); handlers.setHandlers(new Handler[] {contexts, new DefaultHandler(), requestLogHandler}); StatisticsHandler stats = new StatisticsHandler(); stats.setHandler(handlers); server.setHandler(stats); // Setup deployers DeploymentManager deployer = new DeploymentManager(); deployer.setContexts(contexts); server.addBean(deployer); WebAppProvider webapp_provider = new WebAppProvider(); webapp_provider.setMonitoredDirName(jetty_home + "/webapps"); webapp_provider.setParentLoaderPriority(false); webapp_provider.setExtractWars(true); webapp_provider.setScanInterval(2); webapp_provider.setDefaultsDescriptor(jetty_home + "/etc/webdefault.xml"); deployer.addAppProvider(webapp_provider); HashLoginService login = new HashLoginService(); login.setName("Test Realm"); login.setConfig(jetty_home + "/etc/realm.properties"); server.addBean(login); NCSARequestLog requestLog = new AsyncNCSARequestLog(); requestLog.setFilename(jetty_home + "/logs/jetty-yyyy_mm_dd.log"); requestLog.setExtended(false); requestLogHandler.setRequestLog(requestLog); server.setStopAtShutdown(true); server.start(); server.dumpStdErr(); server.join(); }
@Test public void checkBasicAuthAccess() throws Throwable { final Server server = new Server(); final SelectChannelConnector connector = new SelectChannelConnector(); connector.setPort(/* any */ 0); connector.setReuseAddress(false); connector.setSoLingerTime(0); server.addConnector(connector); HashLoginService loginService = new HashLoginService(); loginService.putUser("username", new Password("userpass"), new String[] {"role1", "role2"}); final CountDownLatch latch = new CountDownLatch(1); WebAppContext wac = new WebAppContext(); wac.getSecurityHandler().setLoginService(loginService); wac.setContextPath("/"); connector.addLifeCycleListener( new ListenerAdapter() { public void lifeCycleStarted(LifeCycle lc) { System.out.println("Started on port: " + connector.getLocalPort()); latch.countDown(); } public void lifeCycleFailure(LifeCycle lc, Throwable t) { System.out.println("Failure: " + t); latch.countDown(); } }); wac.setParentLoaderPriority(true); URL resource = getClass().getResource("/auth/basic/kaczynski.xml"); assertThat(resource.toURI().getScheme()).isEqualTo("file"); File webapp = new File(resource.toURI()); webapp = webapp.getParentFile(); // /auth/basic webapp = webapp.getParentFile(); // /auth wac.setWar(webapp.getAbsolutePath()); wac.setClassLoader(Thread.currentThread().getContextClassLoader()); server.setHandler(wac); server.setStopAtShutdown(true); try { server.start(); latch.await(); System.setProperty(HttpAuthHub.USERNAME_PROPERTY, "username"); System.setProperty(HttpAuthHub.PASSWORD_PROPERTY, "userpass"); Controller c = ControllerFactory.createSimple(); try { Map<String, Object> attrs = new HashMap<String, Object>(); XmlDocumentSourceDescriptor.attributeBuilder(attrs) .xml( new URLResourceWithParams( new URL( "http://localhost:" + connector.getLocalPort() + "/basic/kaczynski.xml"))); ProcessingResult r = c.process(attrs, XmlDocumentSource.class); assertThat(r.getDocuments()).hasSize(50); } finally { c.dispose(); } } finally { server.stop(); } }