Java Code Examples for org.eclipse.jetty.security.ConstraintSecurityHandler#setConstraintMappings()

The following examples show how to use org.eclipse.jetty.security.ConstraintSecurityHandler#setConstraintMappings() . 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: HttpProtocolServer.java    From gitflow-incremental-builder with MIT License 6 votes vote down vote up
private void addBasicAuth(Server server) {
    
    ConstraintSecurityHandler security = new ConstraintSecurityHandler();
    security.setAuthenticator(new BasicAuthenticator());

    Constraint constraint = new Constraint();
    constraint.setAuthenticate(true);
    constraint.setRoles(ROLES);
    ConstraintMapping mapping = new ConstraintMapping();
    mapping.setPathSpec("/*");
    mapping.setConstraint(constraint);
    security.setConstraintMappings(Collections.singletonList(mapping));

    HashLoginService loginService = new HashLoginService();
    loginService.setUserStore(buildUserStore());
    server.addBean(loginService);
    security.setLoginService(loginService);

    security.setHandler(server.getHandler());
    server.setHandler(security);
}
 
Example 3
Source File: HttpServerUtil.java    From hbase with Apache License 2.0 6 votes vote down vote up
/**
 * Add constraints to a Jetty Context to disallow undesirable Http methods.
 * @param ctxHandler The context to modify
 * @param allowOptionsMethod if true then OPTIONS method will not be set in constraint mapping
 */
public static void constrainHttpMethods(ServletContextHandler ctxHandler,
    boolean allowOptionsMethod) {
  Constraint c = new Constraint();
  c.setAuthenticate(true);

  ConstraintMapping cmt = new ConstraintMapping();
  cmt.setConstraint(c);
  cmt.setMethod("TRACE");
  cmt.setPathSpec("/*");

  ConstraintSecurityHandler securityHandler = new ConstraintSecurityHandler();

  if (!allowOptionsMethod) {
    ConstraintMapping cmo = new ConstraintMapping();
    cmo.setConstraint(c);
    cmo.setMethod("OPTIONS");
    cmo.setPathSpec("/*");
    securityHandler.setConstraintMappings(new ConstraintMapping[] { cmt, cmo });
  } else {
    securityHandler.setConstraintMappings(new ConstraintMapping[] { cmt });
  }

  ctxHandler.setSecurityHandler(securityHandler);
}
 
Example 4
Source File: WebServerTestCase.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Starts the web server delivering response from the provided connection.
 * @param mockConnection the sources for responses
 * @throws Exception if a problem occurs
 */
protected void startWebServer(final MockWebConnection mockConnection) throws Exception {
    if (STATIC_SERVER_ == null) {
        final Server server = buildServer(PORT);

        final WebAppContext context = new WebAppContext();
        context.setContextPath("/");
        context.setResourceBase("./");

        if (isBasicAuthentication()) {
            final Constraint constraint = new Constraint();
            constraint.setName(Constraint.__BASIC_AUTH);
            constraint.setRoles(new String[]{"user"});
            constraint.setAuthenticate(true);

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

            final ConstraintSecurityHandler handler = (ConstraintSecurityHandler) context.getSecurityHandler();
            handler.setLoginService(new HashLoginService("MyRealm", "./src/test/resources/realm.properties"));
            handler.setConstraintMappings(new ConstraintMapping[]{constraintMapping});
        }

        context.addServlet(MockWebConnectionServlet.class, "/*");
        server.setHandler(context);

        tryStart(PORT, server);
        STATIC_SERVER_ = server;
    }
    MockWebConnectionServlet.setMockconnection(mockConnection);
}
 
Example 5
Source File: EmissaryServer.java    From emissary with Apache License 2.0 5 votes vote down vote up
private ConstraintSecurityHandler buildSecurityHandler() {
    ConstraintSecurityHandler handler = new ConstraintSecurityHandler();
    Constraint constraint = new Constraint();
    constraint.setName("auth");
    constraint.setAuthenticate(true);
    constraint.setRoles(new String[] {"everyone", "emissary", "admin", "support", "manager"});
    ConstraintMapping mapping = new ConstraintMapping();
    mapping.setPathSpec("/*");
    mapping.setConstraint(constraint);
    handler.setConstraintMappings(Collections.singletonList(mapping));
    handler.setAuthenticator(new DigestAuthenticator());
    return handler;
}
 
Example 6
Source File: KafkaCruiseControlApp.java    From cruise-control with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private void maybeSetSecurityHandler(ServletContextHandler contextHandler) throws ServletException {
  SecurityProvider securityProvider = null;
  if (_config.getBoolean(WebServerConfig.WEBSERVER_SECURITY_ENABLE_CONFIG)) {
    securityProvider = _config.getConfiguredInstance(WebServerConfig.WEBSERVER_SECURITY_PROVIDER_CONFIG, SecurityProvider.class);
  }
  if (securityProvider != null) {
    securityProvider.init(_config);
    ConstraintSecurityHandler securityHandler = new CruiseControlSecurityHandler();
    securityHandler.setConstraintMappings(securityProvider.constraintMappings());
    securityHandler.setAuthenticator(securityProvider.authenticator());
    securityHandler.setLoginService(securityProvider.loginService());
    securityHandler.setRoles(securityProvider.roles());
    contextHandler.setSecurityHandler(securityHandler);
  }
}
 
Example 7
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 8
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 9
Source File: BaleenWebApi.java    From baleen with Apache License 2.0 5 votes vote down vote up
private void configureServer(Server server, WebAuthConfig authConfig, Handler servletHandler)
    throws BaleenException {
  Handler serverHandler;

  if (authConfig == null || authConfig.getType() == AuthType.NONE) {
    LOGGER.warn("No security applied to API");
    // No security
    serverHandler = servletHandler;
  } else if (authConfig.getType() == AuthType.BASIC) {
    // Basic authentication
    LOGGER.info("Using Basic HTTP authentication for API");

    HashLoginService loginService = new HashLoginService(authConfig.getName());

    UserStore userStore = new UserStore();
    for (WebUser user : authConfig.getUsers()) {
      Credential credential = Credential.getCredential(user.getPassword());
      userStore.addUser(user.getUsername(), credential, user.getRolesAsArray());
    }
    loginService.setUserStore(userStore);
    server.addBean(loginService);

    ConstraintSecurityHandler securityHandler = new ConstraintSecurityHandler();

    securityHandler.setHandler(servletHandler);
    securityHandler.setConstraintMappings(constraintMappings);
    securityHandler.setAuthenticator(new BasicAuthenticator());
    securityHandler.setLoginService(loginService);

    serverHandler = securityHandler;
  } else {
    throw new InvalidParameterException("Configuration of authentication failed");
  }

  server.setHandler(serverHandler);
}
 
Example 10
Source File: WebServerTask.java    From datacollector with Apache License 2.0 5 votes vote down vote up
protected SecurityHandler createSecurityHandler(
    Server server, Configuration appConf, ServletContextHandler appHandler, String appContext
) {
  ConstraintSecurityHandler securityHandler;
  String auth = conf.get(AUTHENTICATION_KEY, AUTHENTICATION_DEFAULT);
  boolean isDPMEnabled = runtimeInfo.isDPMEnabled();
  if (isDPMEnabled && !runtimeInfo.isRemoteSsoDisabled()) {
    securityHandler = configureSSO(appConf, appHandler, appContext);
  } else {
    switch (auth) {
      case "none":
        securityHandler = null;
        break;
      case "digest":
      case "basic":
        securityHandler = configureDigestBasic(appConf, server, auth);
        break;
      case "form":
        securityHandler = configureForm(appConf, server, auth);
        break;
      default:
        throw new RuntimeException(Utils.format("Invalid authentication mode '{}', must be one of '{}'",
            auth, AUTHENTICATION_MODES));
    }
  }
  if (securityHandler != null) {
    List<ConstraintMapping> constraintMappings = new ArrayList<>();
    constraintMappings.addAll(createConstraintMappings());
    securityHandler.setConstraintMappings(constraintMappings);
  }
  return securityHandler;
}
 
Example 11
Source File: WebDriverTestCase.java    From htmlunit with Apache License 2.0 4 votes vote down vote up
/**
 * Starts the web server delivering response from the provided connection.
 * @param mockConnection the sources for responses
 * @param serverCharset the {@link Charset} at the server side
 * @throws Exception if a problem occurs
 */
protected void startWebServer(final MockWebConnection mockConnection, final Charset serverCharset)
        throws Exception {
    if (Boolean.FALSE.equals(LAST_TEST_UsesMockWebConnection_)) {
        stopWebServers();
    }

    LAST_TEST_UsesMockWebConnection_ = Boolean.TRUE;
    if (STATIC_SERVER_ == null) {
        final Server server = buildServer(PORT);

        final WebAppContext context = new WebAppContext();
        context.setContextPath("/");
        context.setResourceBase("./");

        if (isBasicAuthentication()) {
            final Constraint constraint = new Constraint();
            constraint.setName(Constraint.__BASIC_AUTH);
            constraint.setRoles(new String[]{"user"});
            constraint.setAuthenticate(true);

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

            final ConstraintSecurityHandler handler = (ConstraintSecurityHandler) context.getSecurityHandler();
            handler.setLoginService(new HashLoginService("MyRealm", "./src/test/resources/realm.properties"));
            handler.setConstraintMappings(new ConstraintMapping[]{constraintMapping});
        }

        context.addServlet(MockWebConnectionServlet.class, "/*");
        if (serverCharset != null) {
            AsciiEncodingFilter.CHARSET_ = serverCharset;
            context.addFilter(AsciiEncodingFilter.class, "/*",
                    EnumSet.of(DispatcherType.INCLUDE, DispatcherType.REQUEST));
        }
        server.setHandler(context);
        WebServerTestCase.tryStart(PORT, server);

        STATIC_SERVER_STARTER_ = ExceptionUtils.getStackTrace(new Throwable("StaticServerStarter"));
        STATIC_SERVER_ = server;
    }
    MockWebConnectionServlet.MockConnection_ = mockConnection;

    if (STATIC_SERVER2_ == null && needThreeConnections()) {
        final Server server2 = buildServer(PORT2);
        final WebAppContext context2 = new WebAppContext();
        context2.setContextPath("/");
        context2.setResourceBase("./");
        context2.addServlet(MockWebConnectionServlet.class, "/*");
        server2.setHandler(context2);
        WebServerTestCase.tryStart(PORT2, server2);

        STATIC_SERVER2_STARTER_ = ExceptionUtils.getStackTrace(new Throwable("StaticServer2Starter"));
        STATIC_SERVER2_ = server2;

        final Server server3 = buildServer(PORT3);
        final WebAppContext context3 = new WebAppContext();
        context3.setContextPath("/");
        context3.setResourceBase("./");
        context3.addServlet(MockWebConnectionServlet.class, "/*");
        server3.setHandler(context3);
        WebServerTestCase.tryStart(PORT3, server3);

        STATIC_SERVER3_STARTER_ = ExceptionUtils.getStackTrace(new Throwable("StaticServer3Starter"));
        STATIC_SERVER3_ = server3;
        /*
         * The mock connection servlet call sit under both servers, so long as tests
         * keep the URLs distinct.
         */
    }
}
 
Example 12
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 13
Source File: HttpReceiverServerPush.java    From datacollector with Apache License 2.0 4 votes vote down vote up
public static SecurityHandler getSpnegoAuthHandler(HttpSourceConfigs httpCourceConf, Stage.Context context) throws StageException {
  String domainRealm = httpCourceConf.getSpnegoConfigBean().getKerberosRealm();
  String principal = httpCourceConf.getSpnegoConfigBean().getSpnegoPrincipal();
  String keytab = httpCourceConf.getSpnegoConfigBean().getSpnegoKeytabFilePath();

  File f = new File(context.getResourcesDirectory()+"/spnego.conf");
  try {
    PrintWriter pw = new PrintWriter(f);
    pw.println(String.format(JGSS_INITITATE ,principal,keytab) +"\n"+ String.format(JGSS_ACCEPT,principal,keytab));
    pw.close();
  } catch (IOException e) {
    throw new StageException(Errors.HTTP_36, e);
  }

  System.setProperty(JAVAX_SECURITY_AUTH_USE_SUBJECT_CREDS_ONLY, "false");
  System.setProperty(JAVA_SECURITY_AUTH_LOGIN_CONFIG, context.getResourcesDirectory()+"/spnego.conf");

  Constraint constraint = new Constraint();
  constraint.setName(Constraint.__SPNEGO_AUTH);
  constraint.setRoles(new String[]{domainRealm});
  constraint.setAuthenticate(true);

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

  SpnegoLoginService loginService = new SpnegoLoginService(){
    @Override
    protected void doStart() throws Exception {
      // Override the parent implementation to set the targetName without having
      // an extra .properties file.
      final Field targetNameField = SpnegoLoginService.class.getDeclaredField(TARGET_NAME_FIELD_NAME);
      targetNameField.setAccessible(true);
      targetNameField.set(this, principal);
    }
  };
  loginService.setName(domainRealm);

  ConstraintSecurityHandler csh = new ConstraintSecurityHandler();
  csh.setAuthenticator(new SpnegoAuthenticator());
  csh.setLoginService(loginService);
  csh.setConstraintMappings(new ConstraintMapping[]{cm});
  csh.setRealmName(domainRealm);

  return csh;
}