org.eclipse.jetty.security.LoginService Java Examples

The following examples show how to use org.eclipse.jetty.security.LoginService. 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: HttpServer.java    From calcite-avatica with Apache License 2.0 6 votes vote down vote up
protected ConstraintSecurityHandler configureCommonAuthentication(String constraintName,
    String[] allowedRoles, Authenticator authenticator, String realm,
    LoginService loginService) {

  Constraint constraint = new Constraint();
  constraint.setName(constraintName);
  constraint.setRoles(allowedRoles);
  // This is telling Jetty to not allow unauthenticated requests through (very important!)
  constraint.setAuthenticate(true);

  ConstraintMapping cm = new ConstraintMapping();
  cm.setConstraint(constraint);
  cm.setPathSpec("/*");

  ConstraintSecurityHandler sh = new ConstraintSecurityHandler();
  sh.setAuthenticator(authenticator);
  sh.setLoginService(loginService);
  sh.setConstraintMappings(new ConstraintMapping[]{cm});
  sh.setRealmName(realm);

  return sh;
}
 
Example #2
Source File: JavaxServletSyncServerITest.java    From hawkular-apm with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void initClass() throws Exception {
    server = new Server(8180);

    LoginService loginService = new HashLoginService("MyRealm",
            "src/test/resources/realm.properties");
    server.addBean(loginService);

    ConstraintSecurityHandler security = new ConstraintSecurityHandler();
    server.setHandler(security);

    Constraint constraint = new Constraint();
    constraint.setName("auth");
    constraint.setAuthenticate(true);
    constraint.setRoles(new String[] { "user", "admin" });

    ConstraintMapping mapping = new ConstraintMapping();
    mapping.setPathSpec("/*");
    mapping.setConstraint(constraint);

    security.setConstraintMappings(Collections.singletonList(mapping));
    security.setAuthenticator(new BasicAuthenticator());
    security.setLoginService(loginService);

    ServletContextHandler context = new ServletContextHandler();
    context.setContextPath("/");
    context.addServlet(EmbeddedServlet.class, "/hello");
    security.setHandler(context);

    server.start();
}
 
Example #3
Source File: ApplicationTest.java    From rest-utils with Apache License 2.0 5 votes vote down vote up
@Test(expected = UnsupportedOperationException.class)
public void testBearerNoAuthenticator() {
  final Map<String, Object> config = ImmutableMap.of(
      RestConfig.AUTHENTICATION_METHOD_CONFIG, RestConfig.AUTHENTICATION_METHOD_BEARER);

  Application app = new TestApp(config) {
    @Override
    protected LoginService createLoginService() {
      return new JAASLoginService("realm");
    }
  };
  app.createBearerSecurityHandler();
}
 
Example #4
Source File: Application.java    From rest-utils with Apache License 2.0 5 votes vote down vote up
protected LoginService createLoginService() {
  final String realm = config.getString(RestConfig.AUTHENTICATION_REALM_CONFIG);
  final String method = config.getString(RestConfig.AUTHENTICATION_METHOD_CONFIG);
  if (enableBasicAuth(method)) {
    return new JAASLoginService(realm);
  } else if (enableBearerAuth(method)) {
    throw new UnsupportedOperationException(
            "Must implement Application.createLoginService() when using '"
                    + RestConfig.AUTHENTICATION_METHOD_CONFIG + "="
                    + RestConfig.AUTHENTICATION_METHOD_BEARER + "'."
    );
  }
  return null;
}
 
Example #5
Source File: BookServerSimpleSecurity.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
protected void configureServer(org.eclipse.jetty.server.Server server) throws Exception {
    URL resource = getClass()
        .getResource("/org/apache/cxf/systest/jaxrs/security/jetty-realm.properties");
    LoginService realm =
        new HashLoginService("BookStoreRealm", resource.toURI().getPath());
    server.addBean(realm);
}
 
Example #6
Source File: DigestServer.java    From cxf with Apache License 2.0 5 votes vote down vote up
private void configureServer() throws Exception {
    URL resource = getClass().getResource("jetty-realm.properties");

    LoginService realm =
        new HashLoginService("BookStoreRealm", resource.toString());
    server.addBean(realm);
}
 
Example #7
Source File: AppEngineAuthentication.java    From appengine-java-vm-runtime with Apache License 2.0 5 votes vote down vote up
/**
 * Inject custom {@link LoginService} and {@link Authenticator}
 * implementations into the specified {@link ConstraintSecurityHandler}.
 */
public static void configureSecurityHandler(
    ConstraintSecurityHandler handler, VmRuntimeTrustedAddressChecker checker) {

  LoginService loginService = new AppEngineLoginService();
  LoginAuthenticator authenticator = new AppEngineAuthenticator(checker);
  DefaultIdentityService identityService = new DefaultIdentityService();

  // Set allowed roles.
  handler.setRoles(new HashSet<String>(Arrays.asList(new String[] {USER_ROLE, ADMIN_ROLE})));
  handler.setLoginService(loginService);
  handler.setAuthenticator(authenticator);
  handler.setIdentityService(identityService);
  authenticator.setConfiguration(handler);
}
 
Example #8
Source File: WebServerTask.java    From datacollector with Apache License 2.0 5 votes vote down vote up
private ConstraintSecurityHandler configureForm(Configuration conf, Server server, String mode) {
  ConstraintSecurityHandler securityHandler = new ConstraintSecurityHandler();

  LoginService loginService = getLoginService(conf, mode);
  server.addBean(loginService);
  securityHandler.setLoginService(loginService);

  FormAuthenticator authenticator = new FormAuthenticator("/login.html", "/login.html?error=true", true);
  securityHandler.setAuthenticator(injectActivationCheck(new ProxyAuthenticator(authenticator, runtimeInfo, conf)));
  return securityHandler;
}
 
Example #9
Source File: WebServerTask.java    From datacollector with Apache License 2.0 5 votes vote down vote up
private ConstraintSecurityHandler configureDigestBasic(Configuration conf, Server server, String mode) {
  LoginService loginService = getLoginService(conf, mode);
  server.addBean(loginService);

  ConstraintSecurityHandler security = new ConstraintSecurityHandler();
  switch (mode) {
    case "digest":
      security.setAuthenticator(injectActivationCheck(new ProxyAuthenticator(
          new DigestAuthenticator(),
          runtimeInfo,
          conf
      )));
      break;
    case "basic":
      security.setAuthenticator(injectActivationCheck(new ProxyAuthenticator(
          new BasicAuthenticator(),
          runtimeInfo,
          conf
      )));
      break;
    default:
      // no action
      break;
  }
  security.setLoginService(loginService);
  return security;
}
 
Example #10
Source File: DataCollectorWebServerTask.java    From datacollector with Apache License 2.0 5 votes vote down vote up
@Override
protected LoginService getLoginService(Configuration conf, String mode) {
  LoginService loginService = super.getLoginService(conf, mode);
  String loginModule = this.conf.get(HTTP_AUTHENTICATION_LOGIN_MODULE, HTTP_AUTHENTICATION_LOGIN_MODULE_DEFAULT);
  if (loginModule.equals(FILE)) {
    this.userGroupManager.setLoginService(loginService);
  } else if (loginModule.equals(LDAP)) {
    this.userGroupManager.setRoleMapping(roleMapping);
  }
  return loginService;
}
 
Example #11
Source File: ClientJettyStreamITest.java    From hawkular-apm with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void initClass() {
    server = new Server(8180);

    LoginService loginService = new HashLoginService("MyRealm",
            "src/test/resources/realm.properties");
    server.addBean(loginService);

    ConstraintSecurityHandler security = new ConstraintSecurityHandler();
    server.setHandler(security);

    Constraint constraint = new Constraint();
    constraint.setName("auth");
    constraint.setAuthenticate(true);
    constraint.setRoles(new String[] { "user", "admin" });

    ConstraintMapping mapping = new ConstraintMapping();
    mapping.setPathSpec("/*");
    mapping.setConstraint(constraint);

    security.setConstraintMappings(Collections.singletonList(mapping));
    security.setAuthenticator(new BasicAuthenticator());
    security.setLoginService(loginService);

    ServletContextHandler context = new ServletContextHandler();
    context.setContextPath("/");
    context.addServlet(EmbeddedServlet.class, "/hello");
    security.setHandler(context);

    try {
        server.start();
    } catch (Exception e) {
        fail("Failed to start server: " + e);
    }
}
 
Example #12
Source File: HudsonTestCase.java    From jenkins-test-harness with MIT License 5 votes vote down vote up
/**
 * Configures a security realm for a test.
 */
protected LoginService configureUserRealm() {
    HashLoginService realm = new HashLoginService();
    realm.setName("default");   // this is the magic realm name to make it effective on everywhere
    UserStore userStore = new UserStore();
    realm.setUserStore( userStore );
    userStore.addUser("alice", new Password("alice"), new String[]{"user","female"});
    userStore.addUser("bob", new Password("bob"), new String[]{"user","male"});
    userStore.addUser("charlie", new Password("charlie"), new String[]{"user","male"});

    return realm;
}
 
Example #13
Source File: JenkinsRule.java    From jenkins-test-harness with MIT License 5 votes vote down vote up
/**
 * Creates a {@link HashLoginService} with three users: alice, bob and charlie
 *
 * The password is same as the username
 * @return a new login service
 * @since 2.50
 */
public static LoginService _configureUserRealm() {
    HashLoginService realm = new HashLoginService();
    realm.setName("default");   // this is the magic realm name to make it effective on everywhere
    UserStore userStore = new UserStore();
    realm.setUserStore( userStore );
    userStore.addUser("alice", new Password("alice"), new String[]{"user","female"});
    userStore.addUser("bob", new Password("bob"), new String[]{"user","male"});
    userStore.addUser("charlie", new Password("charlie"), new String[]{"user","male"});

    return realm;
}
 
Example #14
Source File: JwtSecurityProvider.java    From cruise-control with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public LoginService loginService() throws ServletException {
  try {
    return new JwtLoginService(authorizationService(), _publicKeyLocation, _audiences);
  } catch (IOException | CertificateException e) {
    throw new ServletException(e);
  }
}
 
Example #15
Source File: ServerRuntimeModule.java    From EDDI with Apache License 2.0 4 votes vote down vote up
@Override
protected void configure() {
    registerConfigFiles(configFiles);
    bind(LoginService.class).to(MongoLoginService.class).in(Scopes.SINGLETON);
}
 
Example #16
Source File: EmissaryServer.java    From emissary with Apache License 2.0 4 votes vote down vote up
/**
 * Creates and starts a server that is bound into the local Namespace using DEFAULT_NAMESPACE_NAME and returned
 *
 * 
 */
public Server startServer() {
    // do what StartJetty and then JettyServer did to start
    try {
        // Resource.setDefaultUseCaches(false);

        // needs to be loaded first into the server as it setups up Emissary stuff
        ContextHandler emissaryHandler = buildEmissaryHandler();
        // TODO: rework this, no need for it be set with a context path but if this
        // is left out, it matches / and nothing works correctly
        emissaryHandler.setContextPath("/idontreallyservecontentnowdoi");
        ContextHandler lbConfigHandler = buildLogbackConfigHandler();
        lbConfigHandler.setContextPath("/lbConfig");
        ContextHandler apiHandler = buildApiHandler();
        apiHandler.setContextPath("/api");
        ContextHandler mvcHandler = buildMVCHandler();
        mvcHandler.setContextPath("/emissary");
        // needs to be loaded last into the server so other contexts can match or fall through
        ContextHandler staticHandler = buildStaticHandler();
        staticHandler.setContextPath("/");

        LoginService loginService = buildLoginService();
        ConstraintSecurityHandler security = buildSecurityHandler();
        security.setLoginService(loginService);

        // secure some of the contexts
        final HandlerList securedHandlers = new HandlerList();
        securedHandlers.addHandler(lbConfigHandler);
        securedHandlers.addHandler(apiHandler);
        securedHandlers.addHandler(mvcHandler);
        securedHandlers.addHandler(staticHandler);
        security.setHandler(securedHandlers);

        final HandlerList handlers = new HandlerList();
        handlers.addHandler(emissaryHandler); // not secured, no endpoints and must be loaded first
        handlers.addHandler(security);

        Server server = configureServer();
        server.setHandler(handlers);
        server.addBean(loginService);
        server.setStopAtShutdown(true);
        server.setStopTimeout(10000l);
        if (this.cmd.shouldDumpJettyBeans()) {
            server.dump(System.out);
        }
        this.server = server;
        bindServer(); // emissary specific

        server.start();
        // server.join(); // don't join so we can shutdown

        String serverLocation = cmd.getScheme() + "://" + cmd.getHost() + ":" + cmd.getPort();

        // write out env.sh file here
        Path envsh = Paths.get(ConfigUtil.getProjectBase() + File.separator + "env.sh");
        if (Files.exists(envsh)) {
            LOG.debug("Removing old {}", envsh.toAbsolutePath());
            Files.delete(envsh);
        }
        String envURI = serverLocation + "/api/env.sh";
        EmissaryResponse er = new EmissaryClient().send(new HttpGet(envURI));
        String envString = er.getContentString();
        Files.createFile(envsh);
        Files.write(envsh, envString.getBytes());
        LOG.info("Wrote {}", envsh.toAbsolutePath());
        LOG.debug(" with \n{}", envString);

        if (cmd.isPause()) {
            pause(true);
        } else {
            unpause(true);
        }

        LOG.info("Started EmissaryServer at {}", serverLocation);
        return server;
    } catch (Throwable t) {
        t.printStackTrace(System.err);
        throw new RuntimeException("Emissary server didn't start", t);
    }
}
 
Example #17
Source File: EmissaryServer.java    From emissary with Apache License 2.0 4 votes vote down vote up
private LoginService buildLoginService() {
    String jettyUsersFile = ConfigUtil.getConfigFile("jetty-users.properties");
    System.setProperty("emissary.jetty.users.file", jettyUsersFile); // for EmissaryClient
    return new HashLoginService("EmissaryRealm", jettyUsersFile);
}
 
Example #18
Source File: BasicSecurityProvider.java    From cruise-control with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@Override
public LoginService loginService() {
  return new HashLoginService("DefaultLoginService", _userCredentialsFile);
}
 
Example #19
Source File: ProxyAuthenticator.java    From datacollector with Apache License 2.0 4 votes vote down vote up
@Override
public LoginService getLoginService() {
  return authenticator.getLoginService();
}
 
Example #20
Source File: AuthenticationIntegrationTest.java    From cruise-control with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@Override
public LoginService loginService() {
  return new ConstantLoginService();
}
 
Example #21
Source File: ODataTestServer.java    From syndesis with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings( "deprecation" )
private void initServer(SSLContext sslContext, String userName) throws UnknownHostException {
    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
    context.setContextPath(FORWARD_SLASH);
    this.setHandler(context);

    ServletHandler productsHandler = new ServletHandler();
    productsHandler.addServletWithMapping(
        ProductsServlet.class,
        FORWARD_SLASH + PRODUCTS_SVC + FORWARD_SLASH + STAR);
    productsHandler.addFilterWithMapping(ODataPathFilter.class, FORWARD_SLASH + STAR, FilterMapping.REQUEST);
    context.insertHandler(productsHandler);

    if (userName != null) {
        LoginService loginService = new HashLoginService("MyRealm", "src/test/resources/realm.properties");
        this.addBean(loginService);

        ConstraintSecurityHandler securityHandler = new ConstraintSecurityHandler();
        Constraint constraint = new Constraint();
        constraint.setName("auth");
        constraint.setAuthenticate(true);
        constraint.setRoles(new String[] { USER, "admin" });

        ConstraintMapping mapping = new ConstraintMapping();
        mapping.setPathSpec(FORWARD_SLASH + PRODUCTS_SVC + FORWARD_SLASH + STAR);
        mapping.setConstraint(constraint);

        securityHandler.setConstraintMappings(Collections.singletonList(mapping));
        securityHandler.setAuthenticator(new BasicAuthenticator());

        context.setSecurityHandler(securityHandler);
    }

    httpConnector = new ServerConnector(this);
    httpConnector.setPort(httpPort); // Finds next available port if still 0
    this.addConnector(httpConnector);


    if (sslContext != null) {
        // HTTPS
        HttpConfiguration httpConfiguration = new HttpConfiguration();
        httpConfiguration.setSecureScheme("https");
        httpConfiguration.setSecurePort(httpsPort); // Finds next available port if still 0
        httpConfiguration.addCustomizer(new SecureRequestCustomizer());

        final SslContextFactory sslContextFactory = new SslContextFactory();
        sslContextFactory.setSslContext(sslContext);
        httpsConnector = new ServerConnector(this, sslContextFactory, new HttpConnectionFactory(httpConfiguration));
        httpsConnector.setPort(httpsPort); // Finds next available port if still 0
        this.addConnector(httpsConnector);
    }
}
 
Example #22
Source File: JenkinsRule.java    From jenkins-test-harness with MIT License 4 votes vote down vote up
/**
 * Configures a security realm for a test.
 */
protected LoginService configureUserRealm() {
    return _configureUserRealm();
}
 
Example #23
Source File: FileUserGroupManager.java    From datacollector with Apache License 2.0 4 votes vote down vote up
@Override
public void setLoginService(LoginService loginService) {}
 
Example #24
Source File: LdapUserGroupManager.java    From datacollector with Apache License 2.0 4 votes vote down vote up
@Override
public void setLoginService(LoginService loginService) {
}
 
Example #25
Source File: TestWebServicesFetcher.java    From datacollector with Apache License 2.0 4 votes vote down vote up
protected void runServer(int port, boolean serverSsl, boolean clientSsl, String httpAuth, Callable<Void> test)
    throws Exception {
  Server server = createServer(port, serverSsl, clientSsl);

  ServletContextHandler contextHandler = new ServletContextHandler();
  if (!httpAuth.equals("none")) {
    File realmFile = new File(getConfDir(), httpAuth + ".properties");
    LoginService loginService = new HashLoginService(httpAuth, realmFile.getAbsolutePath());
    server.addBean(loginService);
    ConstraintSecurityHandler securityHandler = new ConstraintSecurityHandler();
    switch (httpAuth) {
      case "basic":
        securityHandler.setAuthenticator(new BasicAuthenticator());
        break;
      case "digest":
        securityHandler.setAuthenticator(new DigestAuthenticator());
        break;
    }
    securityHandler.setLoginService(loginService);
    Constraint constraint = new Constraint();
    constraint.setName("auth");
    constraint.setAuthenticate(true);
    constraint.setRoles(new String[]{"user"});
    ConstraintMapping mapping = new ConstraintMapping();
    mapping.setPathSpec("/*");
    mapping.setConstraint(constraint);
    securityHandler.addConstraintMapping(mapping);
    contextHandler.setSecurityHandler(securityHandler);
  }

  MockCyberArkServlet servlet = new MockCyberArkServlet();
  contextHandler.addServlet(new ServletHolder(servlet), "/AIMWebService/api/Accounts");
  contextHandler.setContextPath("/");
  server.setHandler(contextHandler);
  try {
    server.start();
    test.call();
  } finally {
    server.stop();
  }
}
 
Example #26
Source File: HybridLoginService.java    From sql-layer with GNU Affero General Public License v3.0 4 votes vote down vote up
public HybridLoginService(LoginService delegate, SecurityService securityService) {
    this.delegate = delegate;
    this.securityService = securityService;
}
 
Example #27
Source File: DrillHttpConstraintSecurityHandler.java    From Bats with Apache License 2.0 4 votes vote down vote up
public void setup(LoginAuthenticator authenticator, LoginService loginService) {
  final Set<String> knownRoles = ImmutableSet.of(AUTHENTICATED_ROLE, ADMIN_ROLE);
  setConstraintMappings(Collections.<ConstraintMapping>emptyList(), knownRoles);
  setAuthenticator(authenticator);
  setLoginService(loginService);
}
 
Example #28
Source File: JenkinsRule.java    From jenkins-test-harness with MIT License 4 votes vote down vote up
/**
 * Creates a web server on which Jenkins can run
 *
 * @param contextPath              the context path at which to put Jenkins
 * @param portSetter               the port on which the server runs will be set using this function
 * @param classLoader              the class loader for the {@link WebAppContext}
 * @param localPort                port on which the server runs
 * @param loginServiceSupplier     configures the {@link LoginService} for the instance
 * @param contextAndServerConsumer configures the {@link WebAppContext} and the {@link Server} for the instance, before they are started
 * @return ImmutablePair consisting of the {@link Server} and the {@link ServletContext}
 * @since 2.50
 */
public static ImmutablePair<Server, ServletContext> _createWebServer(String contextPath, Consumer<Integer> portSetter,
                                                                     ClassLoader classLoader, int localPort,
                                                                     Supplier<LoginService> loginServiceSupplier,
                                                                     @CheckForNull BiConsumer<WebAppContext, Server> contextAndServerConsumer)
        throws Exception {
    QueuedThreadPool qtp = new QueuedThreadPool();
    qtp.setName("Jetty (JenkinsRule)");
    Server server = new Server(qtp);

    WebAppContext context = new WebAppContext(WarExploder.getExplodedDir().getPath(), contextPath);
    context.setClassLoader(classLoader);
    context.setConfigurations(new Configuration[]{new WebXmlConfiguration()});
    context.addBean(new NoListenerConfiguration(context));
    server.setHandler(context);
    context.setMimeTypes(MIME_TYPES);
    context.getSecurityHandler().setLoginService(loginServiceSupplier.get());
    context.setResourceBase(WarExploder.getExplodedDir().getPath());

    ServerConnector connector = new ServerConnector(server);
    HttpConfiguration config = connector.getConnectionFactory(HttpConnectionFactory.class).getHttpConfiguration();
    // use a bigger buffer as Stapler traces can get pretty large on deeply nested URL
    config.setRequestHeaderSize(12 * 1024);
    connector.setHost("localhost");
    if (System.getProperty("port") != null) {
        connector.setPort(Integer.parseInt(System.getProperty("port")));
    } else if (localPort != 0) {
        connector.setPort(localPort);
    }

    server.addConnector(connector);
    if (contextAndServerConsumer != null) {
        contextAndServerConsumer.accept(context, server);
    }
    server.start();

    portSetter.accept(connector.getLocalPort());

    ServletContext servletContext =  context.getServletContext();
    return new ImmutablePair<>(server, servletContext);
}
 
Example #29
Source File: JenkinsRule.java    From jenkins-test-harness with MIT License 3 votes vote down vote up
/**
 * Creates a web server on which Jenkins can run
 *
 * @param contextPath          the context path at which to put Jenkins
 * @param portSetter           the port on which the server runs will be set using this function
 * @param classLoader          the class loader for the {@link WebAppContext}
 * @param localPort            port on which the server runs
 * @param loginServiceSupplier configures the {@link LoginService} for the instance
 * @return ImmutablePair consisting of the {@link Server} and the {@link ServletContext}
 * @since 2.50
 */
public static ImmutablePair<Server, ServletContext> _createWebServer(String contextPath, Consumer<Integer> portSetter,
                                                                     ClassLoader classLoader, int localPort,
                                                                     Supplier<LoginService> loginServiceSupplier)
        throws Exception {
    return _createWebServer(contextPath, portSetter, classLoader, localPort, loginServiceSupplier, null);
}
 
Example #30
Source File: SecurityProvider.java    From cruise-control with BSD 2-Clause "Simplified" License 2 votes vote down vote up
/**
 * Associates a username, credentials and roles with a {@link org.eclipse.jetty.server.UserIdentity}
 * that will be used by Jetty to manage the authentication.
 *
 * @throws ServletException if any problem occurred during the initialization of the LoginService.
 * @return a new {@link LoginService}.
 */
LoginService loginService() throws ServletException;