Java Code Examples for org.eclipse.jetty.servlet.ServletContextHandler#setSecurityHandler()

The following examples show how to use org.eclipse.jetty.servlet.ServletContextHandler#setSecurityHandler() . 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: RestServiceReceiverServer.java    From datacollector with Apache License 2.0 6 votes vote down vote up
@Override
public void addReceiverServlet(Stage.Context context, ServletContextHandler contextHandler) {
  servlet = new RestServiceReceiverServlet(context, receiver, errorQueue);
  contextHandler.addServlet(new ServletHolder(servlet), receiver.getUriPath());
  HttpSourceConfigs httpSourceConfigs = (HttpSourceConfigs) configs;

  SecurityHandler securityHandler = null;
  if (httpSourceConfigs.spnegoConfigBean.isSpnegoEnabled()) {
    securityHandler = HttpReceiverServerPush.getSpnegoAuthHandler(httpSourceConfigs, context);
  } else if (httpSourceConfigs.tlsConfigBean.isEnabled()) {
    securityHandler = HttpReceiverServerPush.getBasicAuthHandler(httpSourceConfigs);
  }
  if (securityHandler != null) {
    contextHandler.setSecurityHandler(securityHandler);
  }
}
 
Example 2
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 3
Source File: CustomInitTest.java    From rest-utils with Apache License 2.0 6 votes vote down vote up
@Override
public void accept(final ServletContextHandler context) {
  final List<String> roles = config.getList(RestConfig.AUTHENTICATION_ROLES_CONFIG);
  final Constraint constraint = new Constraint();
  constraint.setAuthenticate(true);
  constraint.setRoles(roles.toArray(new String[0]));

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

  final ConstraintSecurityHandler securityHandler = new ConstraintSecurityHandler();
  securityHandler.addConstraintMapping(constraintMapping);
  securityHandler.setAuthenticator(new BasicAuthenticator());
  securityHandler.setLoginService(new TestLoginService());
  securityHandler.setRealmName("TestRealm");

 context.setSecurityHandler(securityHandler);
}
 
Example 4
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 5
Source File: HttpReceiverServerPush.java    From datacollector with Apache License 2.0 5 votes vote down vote up
@Override
public void addReceiverServlet(Stage.Context context, ServletContextHandler contextHandler) {
  super.addReceiverServlet(context, contextHandler);
  HttpSourceConfigs httpSourceConfigs = (HttpSourceConfigs) configs;
  SecurityHandler securityHandler =
      httpSourceConfigs.spnegoConfigBean.isSpnegoEnabled() ? getSpnegoAuthHandler(httpSourceConfigs, context) :
          httpSourceConfigs.tlsConfigBean.isEnabled() ? getBasicAuthHandler(httpSourceConfigs) : null;
  if(securityHandler!=null) {
    contextHandler.setSecurityHandler(securityHandler);
  }
}
 
Example 6
Source File: GerritRestClientTest.java    From gerrit-rest-java-client with Apache License 2.0 5 votes vote down vote up
public String startJetty(Class<? extends HttpServlet> loginServletClass) throws Exception {
    Server server = new Server(0);

    ResourceHandler resourceHandler = new ResourceHandler();
    MimeTypes mimeTypes = new MimeTypes();
    mimeTypes.addMimeMapping("json", "application/json");
    resourceHandler.setMimeTypes(mimeTypes);
    URL url = this.getClass().getResource(".");
    resourceHandler.setBaseResource(new FileResource(url));
    resourceHandler.setWelcomeFiles(new String[] {"changes.json", "projects.json", "account.json"});

    ServletContextHandler servletContextHandler = new ServletContextHandler();
    servletContextHandler.addServlet(loginServletClass, "/login/");

    ServletContextHandler basicAuthContextHandler = new ServletContextHandler(ServletContextHandler.SECURITY);
    basicAuthContextHandler.setSecurityHandler(basicAuth("foo", "bar", "Gerrit Auth"));
    basicAuthContextHandler.setContextPath("/a");

    HandlerCollection handlers = new HandlerCollection();
    handlers.setHandlers(new Handler[] {
        servletContextHandler,
        resourceHandler,
        basicAuthContextHandler
    });
    server.setHandler(handlers);

    server.start();

    Connector connector = server.getConnectors()[0];
    String host = "localhost";
    int port = connector.getLocalPort();
    return String.format("http://%s:%s", host, port);
}
 
Example 7
Source File: DigestAuthSupplierJettyTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
protected void run() {
    server = new Server(PORT);

    HashLoginService loginService = new HashLoginService();
    loginService.setName("My Realm");
    UserStore userStore = new UserStore();
    String[] roles = new String[] {"user"};
    userStore.addUser(USER, Credential.getCredential(PWD), roles);
    loginService.setUserStore(userStore);

    Constraint constraint = new Constraint();
    constraint.setName(Constraint.__DIGEST_AUTH);
    constraint.setRoles(roles);
    constraint.setAuthenticate(true);

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

    ConstraintSecurityHandler csh = new ConstraintSecurityHandler();
    csh.setAuthenticator(new DigestAuthenticator());
    csh.addConstraintMapping(cm);
    csh.setLoginService(loginService);

    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
    context.setSecurityHandler(csh);
    context.setContextPath("/");
    server.setHandler(context);
    context.addServlet(new ServletHolder(new TestServlet()), "/*");

    try {
        server.start();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 8
Source File: Application.java    From rest-utils with Apache License 2.0 5 votes vote down vote up
protected void configureSecurityHandler(ServletContextHandler context) {
  String authMethod = config.getString(RestConfig.AUTHENTICATION_METHOD_CONFIG);
  if (enableBasicAuth(authMethod)) {
    context.setSecurityHandler(createBasicSecurityHandler());
  } else if (enableBearerAuth(authMethod)) {
    context.setSecurityHandler(createBearerSecurityHandler());
  }
}
 
Example 9
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 10
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 11
Source File: ManagerApiTestServer.java    From apiman with Apache License 2.0 4 votes vote down vote up
/**
     * Configure the web application(s).
     * @param handlers
     * @throws Exception
     */
    protected void addModulesToJetty(ContextHandlerCollection handlers) throws Exception {
        /* *************
         * Manager API
         * ************* */
        ServletContextHandler apiManServer = new ServletContextHandler(ServletContextHandler.SESSIONS);
        apiManServer.setSecurityHandler(createSecurityHandler());
        apiManServer.setContextPath("/apiman");
        apiManServer.addEventListener(new Listener());
        apiManServer.addEventListener(new BeanManagerResourceBindingListener());
        apiManServer.addEventListener(new ResteasyBootstrap());
        apiManServer.addFilter(DatabaseSeedFilter.class, "/db-seeder", EnumSet.of(DispatcherType.REQUEST));
//        apiManServer.addFilter(LocaleFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST));
        apiManServer.addFilter(ApimanCorsFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST));
        apiManServer.addFilter(DisableCachingFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST));
        configureAuthentication(apiManServer);
        apiManServer.addFilter(DefaultSecurityContextFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST));
        apiManServer.addFilter(TransactionWatchdogFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST));
        apiManServer.addFilter(RootResourceFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST));
        ServletHolder resteasyServlet = new ServletHolder(new HttpServletDispatcher());
        resteasyServlet.setInitParameter("javax.ws.rs.Application", TestManagerApiApplication.class.getName());
        apiManServer.addServlet(resteasyServlet, "/*");

        apiManServer.setInitParameter("resteasy.injector.factory", "org.jboss.resteasy.cdi.CdiInjectorFactory");
        apiManServer.setInitParameter("resteasy.scan", "true");
        apiManServer.setInitParameter("resteasy.servlet.mapping.prefix", "");

        // Add the web contexts to jetty
        handlers.addHandler(apiManServer);

        /* *************
         * Mock Gateway (to test publishing of APIs from dt to rt)
         * ************* */
        ServletContextHandler mockGatewayServer = new ServletContextHandler(ServletContextHandler.SESSIONS);
        mockGatewayServer.setSecurityHandler(createSecurityHandler());
        mockGatewayServer.setContextPath("/mock-gateway");
        ServletHolder mockGatewayServlet = new ServletHolder(new MockGatewayServlet());
        mockGatewayServer.addServlet(mockGatewayServlet, "/*");

        // Add the web contexts to jetty
        handlers.addHandler(mockGatewayServer);
    }
 
Example 12
Source File: BasicAuthTest.java    From apiman with Apache License 2.0 4 votes vote down vote up
/**
 * With thanks to assistance of http://stackoverflow.com/b/20056601/2766538
 * @throws Exception any exception
 */
@Before
public void setupJetty() throws Exception {
    ContextHandlerCollection handlers = new ContextHandlerCollection();

    ServletContextHandler sch = new ServletContextHandler(ServletContextHandler.SESSIONS);
    sch.setSecurityHandler(createSecurityHandler());
    sch.setContextPath("/echo");
    ServletHolder mockEchoServlet = new ServletHolder(new EchoServlet());
    sch.addServlet(mockEchoServlet, "/*");
    sch.addFilter(AuthenticationFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST));

    handlers.addHandler(sch);

    SslContextFactory sslContextFactory = new SslContextFactory();
    sslContextFactory.setTrustStorePath(getResourcePath("common_ts.jks"));
    sslContextFactory.setTrustStorePassword("password");
    sslContextFactory.setKeyStorePath(getResourcePath("service_ks.jks"));
    sslContextFactory.setKeyStorePassword("password");
    sslContextFactory.setKeyManagerPassword("password");
    sslContextFactory.setNeedClientAuth(false);
    sslContextFactory.setWantClientAuth(false);

    // Create the server.
    int serverPort = 8008;
    server = new Server(serverPort);
    server.setStopAtShutdown(true);

    HttpConfiguration http_config = new HttpConfiguration();
    http_config.setSecureScheme("https");
    HttpConfiguration https_config = new HttpConfiguration(http_config);
    https_config.addCustomizer(new SecureRequestCustomizer());
    ServerConnector sslConnector = new ServerConnector(server,
            new SslConnectionFactory(sslContextFactory, "http/1.1"),
            new HttpConnectionFactory(https_config));
    sslConnector.setPort(8009);
    server.addConnector(sslConnector);

    server.setHandler(handlers);
    server.start();

    globalConfig.put(TLSOptions.TLS_DEVMODE, "true");
}
 
Example 13
Source File: ManagerApiMicroService.java    From apiman with Apache License 2.0 2 votes vote down vote up
/**
 * @param apiManServer
 * @throws Exception
 */
protected void addSecurityHandler(ServletContextHandler apiManServer) throws Exception {
    apiManServer.setSecurityHandler(createSecurityHandler());
}
 
Example 14
Source File: GatewayMicroService.java    From apiman with Apache License 2.0 2 votes vote down vote up
/**
 * @param apiManServer
 * @throws Exception
 */
protected void addSecurityHandler(ServletContextHandler apiManServer) throws Exception {
    apiManServer.setSecurityHandler(createSecurityHandler());
}