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; }
/** 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 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); }
@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(); } }