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

The following examples show how to use org.eclipse.jetty.security.ConstraintSecurityHandler#addConstraintMapping() . 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: JettySecurity.java    From camelinaction2 with Apache License 2.0 6 votes vote down vote up
@Produces
@Named("securityHandler")
public static ConstraintSecurityHandler createSecurityHandler() {
    Constraint constraint = new Constraint("BASIC", "customer");
    constraint.setAuthenticate(true);

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

    ConstraintSecurityHandler handler = new ConstraintSecurityHandler();
    handler.addConstraintMapping(mapping);
    handler.setAuthenticator(new BasicAuthenticator());
    handler.setLoginService(new HashLoginService("RiderAutoParts", "src/main/resources/users.properties"));

    return handler;
}
 
Example 2
Source File: InMemoryIdentityManager.java    From crnk-framework with Apache License 2.0 6 votes vote down vote up
public InMemoryIdentityManager() {
	loginService = new HashLoginService();
	loginService.setName(realm);

	securityHandler = new ConstraintSecurityHandler();
	securityHandler.setAuthenticator(new BasicAuthenticator());
	securityHandler.setRealmName(realm);
	securityHandler.setLoginService(loginService);

	Constraint constraint = new Constraint();
	constraint.setName(Constraint.__BASIC_AUTH);
	//		constraint.setRoles(new String[] { "getRole", "postRole", "allRole" });
	constraint.setRoles(new String[]{Constraint.ANY_AUTH, "getRole", "postRole", "allRole"});
	constraint.setAuthenticate(true);

	ConstraintMapping cm = new ConstraintMapping();
	cm.setConstraint(constraint);
	cm.setPathSpec("/*");
	securityHandler.addConstraintMapping(cm);
}
 
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: SecureJettyMixin.java    From attic-polygene-java with Apache License 2.0 6 votes vote down vote up
@Override
protected SecurityHandler buildSecurityHandler()
{
    if( constraintServices != null )
    {
        ConstraintSecurityHandler securityHandler = new ConstraintSecurityHandler();
        for( ConstraintService eachConstraintService : constraintServices )
        {
            ConstraintMapping csMapping = eachConstraintService.buildConstraintMapping();
            if( csMapping != null )
            {
                securityHandler.addConstraintMapping( csMapping );
            }
        }
        if( !securityHandler.getConstraintMappings().isEmpty() )
        {
            return securityHandler;
        }
    }
    return super.buildSecurityHandler();
}
 
Example 5
Source File: GerritRestClientTest.java    From gerrit-rest-java-client with Apache License 2.0 6 votes vote down vote up
private static SecurityHandler basicAuth(String username, String password, String realm) {
    HashLoginService loginService = new HashLoginService();
    loginService.putUser(username, Credential.getCredential(password), new String[]{"user"});
    loginService.setName(realm);

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

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

    ConstraintSecurityHandler csh = new ConstraintSecurityHandler();
    csh.setAuthenticator(new BasicAuthenticator());
    csh.setRealmName("realm");
    csh.addConstraintMapping(constraintMapping);
    csh.setLoginService(loginService);
    return csh;
}
 
Example 6
Source File: StandaloneAdminWeb.java    From chipster with MIT License 5 votes vote down vote up
public static void main(String args[]) throws Exception {
	org.eclipse.jetty.server.Server adminServer = new org.eclipse.jetty.server.Server();
	ServerConnector connector = new ServerConnector(adminServer);
	connector.setPort(8083);
	adminServer.setConnectors(new Connector[]{ connector });
	
	Constraint constraint = new Constraint();
	constraint.setName(Constraint.__BASIC_AUTH);
	constraint.setRoles(new String[] {"admin_role"});
	constraint.setAuthenticate(true);
	
	ConstraintMapping cm = new ConstraintMapping();
	cm.setConstraint(constraint);
	cm.setPathSpec("/*");
	
	HashLoginService loginService = new HashLoginService("Please enter Chipster Admin username and password");
	loginService.update("chipster", 
			new Password("chipster"), 
			new String[] {"admin_role"});
	
	ConstraintSecurityHandler sh = new ConstraintSecurityHandler();
	sh.setLoginService(loginService);
	sh.addConstraintMapping(cm);
	
	WebAppContext context = new WebAppContext();
	File war = new File("../chipster/dist/admin-web.war");
	//File war = new File("webapps/admin-web.war");
	context.setWar(war.getAbsolutePath());
	System.out.println(war.getAbsolutePath());
       context.setContextPath("/");
			
       context.setHandler(sh);
	HandlerCollection handlers = new HandlerCollection();
	handlers.setHandlers(new Handler[] {context, new DefaultHandler()});
			
	adminServer.setHandler(handlers);
       adminServer.start();
}
 
Example 7
Source File: Application.java    From rest-utils with Apache License 2.0 5 votes vote down vote up
protected ConstraintSecurityHandler createSecurityHandler() {
  final String realm = config.getString(RestConfig.AUTHENTICATION_REALM_CONFIG);

  final ConstraintSecurityHandler securityHandler = new ConstraintSecurityHandler();
  securityHandler.addConstraintMapping(createGlobalAuthConstraint());
  securityHandler.setAuthenticator(createAuthenticator());
  securityHandler.setLoginService(createLoginService());
  securityHandler.setIdentityService(createIdentityService());
  securityHandler.setRealmName(realm);
  AuthUtil.createUnsecuredConstraints(config)
          .forEach(securityHandler::addConstraintMapping);

  return securityHandler;
}
 
Example 8
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 9
Source File: AppEngineAuthenticationTest.java    From appengine-java-vm-runtime with Apache License 2.0 5 votes vote down vote up
private void addConstraint(
    ConstraintSecurityHandler handler, String path, String name, String... roles) {
  Constraint constraint = new Constraint();
  constraint.setName(name);
  constraint.setRoles(roles);
  constraint.setAuthenticate(true);
  ConstraintMapping mapping = new ConstraintMapping();
  mapping.setMethod("GET");
  mapping.setPathSpec(path);
  mapping.setConstraint(constraint);
  handler.addConstraintMapping(mapping);
}
 
Example 10
Source File: HttpReceiverServerPush.java    From datacollector with Apache License 2.0 5 votes vote down vote up
public static SecurityHandler getBasicAuthHandler(HttpSourceConfigs httpCourceConf) {
  List<CredentialValueUserPassBean> basicAuthUsers = httpCourceConf.getBasicAuthUsers();

  HashLoginService loginService = new HashLoginService();
  UserStore userStore = new UserStore();

  boolean empty = true;
  for (CredentialValueUserPassBean userPassBean : basicAuthUsers) {
    String username = userPassBean.getUsername();
    String password = userPassBean.get();
    if(StringUtils.isNotEmpty(username) && StringUtils.isNotEmpty(password)) {
      userStore.addUser(username, new Password(password), new String[]{"sdc"});
      empty = false;
    }
  }
  if(empty) {
    return null;
  }

  loginService.setUserStore(userStore);

  Constraint constraint = new Constraint(Constraint.__BASIC_AUTH,"sdc");
  constraint.setAuthenticate(true);

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

  ConstraintSecurityHandler handler = new ConstraintSecurityHandler();
  handler.setAuthenticator(new BasicAuthenticator());
  handler.addConstraintMapping(mapping);
  handler.setLoginService(loginService);

  return handler;
}
 
Example 11
Source File: JettySecurity.java    From camelinaction2 with Apache License 2.0 5 votes vote down vote up
public static ConstraintSecurityHandler createSecurityHandler() {
    Constraint constraint = new Constraint("BASIC", "customer");
    constraint.setAuthenticate(true);

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

    ConstraintSecurityHandler handler = new ConstraintSecurityHandler();
    handler.addConstraintMapping(mapping);
    handler.setAuthenticator(new BasicAuthenticator());
    handler.setLoginService(new HashLoginService("RiderAutoParts", "src/main/resources/users.properties"));

    return handler;
}
 
Example 12
Source File: JettySecurity.java    From camelinaction2 with Apache License 2.0 5 votes vote down vote up
public static ConstraintSecurityHandler createSecurityHandler() {
    Constraint constraint = new Constraint("BASIC", "customer");
    constraint.setAuthenticate(true);

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

    ConstraintSecurityHandler handler = new ConstraintSecurityHandler();
    handler.addConstraintMapping(mapping);
    handler.setAuthenticator(new BasicAuthenticator());
    handler.setLoginService(new HashLoginService("RiderAutoParts", "etc/rest-users.properties"));

    return handler;
}
 
Example 13
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 14
Source File: LotteryApplication.java    From keycloak-dropwizard-integration with Apache License 2.0 4 votes vote down vote up
@Override
public void run(LotteryConfiguration configuration, Environment environment)
        throws ClassNotFoundException, IOException {

    // tag::constraint[]
    ConstraintSecurityHandler securityHandler = new ConstraintSecurityHandler();
    environment.getApplicationContext().setSecurityHandler(securityHandler);
    securityHandler.addRole("user");
    ConstraintMapping constraintMapping = new ConstraintMapping();
    constraintMapping.setPathSpec("/*");
    Constraint constraint = new Constraint();
    // end::constraint[]

    /* if I put false here, there will be deferred authentication. This will
    not work when using oAuth redirects (as they will not make it to the front end).
    The DeferredAuthentication will swallow them.

    This might be different with a bearer token?!
     */
    // tag::constraint[]
    constraint.setAuthenticate(true);
    constraint.setRoles(new String[]{"user"});
    constraintMapping.setConstraint(constraint);
    securityHandler.addConstraintMapping(constraintMapping);
    // end::constraint[]

    // tag::keycloak[]
    KeycloakJettyAuthenticator keycloak = new KeycloakJettyAuthenticator();
    environment.getApplicationContext().getSecurityHandler().setAuthenticator(keycloak);
    keycloak.setAdapterConfig(configuration.getKeycloakConfiguration());
    // end::keycloak[]

    // allow (stateful) sessions in Dropwizard, needed for Keycloak
    environment.jersey().register(HttpSessionFactory.class);
    environment.servlets().setSessionHandler(new SessionHandler());

    // register web resources.
    environment.jersey().register(DrawRessource.class);

    // support annotation @RolesAllowed
    // tag::roles[]
    environment.jersey().register(RolesAllowedDynamicFeature.class);
    // end::roles[]
}
 
Example 15
Source File: JettyServer.java    From selenium with Apache License 2.0 4 votes vote down vote up
public JettyServer(BaseServerOptions options, HttpHandler handler) {
  this.handler = Require.nonNull("Handler", handler);
  int port = options.getPort() == 0 ? PortProber.findFreePort() : options.getPort();

  String host = options.getHostname().orElseGet(() -> {
    try {
      return new NetworkUtils().getNonLoopbackAddressOfThisMachine();
    } catch (WebDriverException ignored) {
      return "localhost";
    }
  });

  try {
    this.url = new URL("http", host, port, "");
  } catch (MalformedURLException e) {
    throw new UncheckedIOException(e);
  }

  Log.setLog(new JavaUtilLog());
  this.server = new org.eclipse.jetty.server.Server(
      new QueuedThreadPool(options.getMaxServerThreads()));

  this.servletContextHandler = new ServletContextHandler(ServletContextHandler.SECURITY);
  ConstraintSecurityHandler
      securityHandler =
      (ConstraintSecurityHandler) servletContextHandler.getSecurityHandler();

  Constraint disableTrace = new Constraint();
  disableTrace.setName("Disable TRACE");
  disableTrace.setAuthenticate(true);
  ConstraintMapping disableTraceMapping = new ConstraintMapping();
  disableTraceMapping.setConstraint(disableTrace);
  disableTraceMapping.setMethod("TRACE");
  disableTraceMapping.setPathSpec("/");
  securityHandler.addConstraintMapping(disableTraceMapping);

  Constraint enableOther = new Constraint();
  enableOther.setName("Enable everything but TRACE");
  ConstraintMapping enableOtherMapping = new ConstraintMapping();
  enableOtherMapping.setConstraint(enableOther);
  enableOtherMapping.setMethodOmissions(new String[]{"TRACE"});
  enableOtherMapping.setPathSpec("/");
  securityHandler.addConstraintMapping(enableOtherMapping);

  // Allow CORS: Whether the Selenium server should allow web browser connections from any host
  if (options.getAllowCORS()) {
    FilterHolder
        filterHolder = servletContextHandler.addFilter(CrossOriginFilter.class, "/*", EnumSet
        .of(DispatcherType.REQUEST));
    filterHolder.setInitParameter("allowedMethods", "GET,POST,PUT,DELETE,HEAD");

    // Warning user
    LOG.warning("You have enabled CORS requests from any host. "
                + "Be careful not to visit sites which could maliciously "
                + "try to start Selenium sessions on your machine");
  }

  server.setHandler(servletContextHandler);

  HttpConfiguration httpConfig = new HttpConfiguration();
  httpConfig.setSecureScheme("https");

  ServerConnector http = new ServerConnector(server, new HttpConnectionFactory(httpConfig));
  options.getHostname().ifPresent(http::setHost);
  http.setPort(getUrl().getPort());

  http.setIdleTimeout(500000);

  server.setConnectors(new Connector[]{http});
}
 
Example 16
Source File: JettyHttpServer.java    From everrest with Eclipse Public License 2.0 4 votes vote down vote up
public void start() throws Exception {
    RequestLogHandler handler = new RequestLogHandler();

    if (context == null) {
        context = new ServletContextHandler(handler, "/", ServletContextHandler.SESSIONS);
    }

    context.setEventListeners(new EventListener[]{new EverrestInitializedListener()});
    ServletHolder servletHolder = new ServletHolder(new EverrestServlet());

    context.addServlet(servletHolder, UNSECURE_PATH_SPEC);
    context.addServlet(servletHolder, SECURE_PATH_SPEC);

    //set up security
    Constraint constraint = new Constraint();
    constraint.setName(Constraint.__BASIC_AUTH);
    constraint.setRoles(new String[]{"cloud-admin", "users", "user", "temp_user"});
    constraint.setAuthenticate(true);

    ConstraintMapping constraintMapping = new ConstraintMapping();
    constraintMapping.setConstraint(constraint);
    constraintMapping.setPathSpec(SECURE_PATH_SPEC);

    ConstraintSecurityHandler securityHandler = new ConstraintSecurityHandler();
    securityHandler.addConstraintMapping(constraintMapping);

    HashLoginService loginService = new HashLoginService();

    UserStore userStore = new UserStore();

    userStore.addUser(ADMIN_USER_NAME, new Password(ADMIN_USER_PASSWORD),
                         new String[]{"cloud-admin",
                                      "users",
                                      "user",
                                      "temp_user",
                                      "developer",
                                      "admin",
                                      "workspace/developer",
                                      "workspace/admin",
                                      "account/owner",
                                      "account/member",
                                      "system/admin",
                                      "system/manager"
                         });
    userStore.addUser(MANAGER_USER_NAME, new Password(MANAGER_USER_PASSWORD), new String[]{"cloud-admin",
                                                                                              "user",
                                                                                              "temp_user",
                                                                                              "users"});
    loginService.setUserStore(userStore);

    securityHandler.setLoginService(loginService);
    securityHandler.setAuthenticator(new BasicAuthenticator());

    context.setSecurityHandler(securityHandler);

    server.setHandler(handler);

    server.start();
    ResourceBinder binder =
            (ResourceBinder)context.getServletContext().getAttribute(ResourceBinder.class.getName());
    DependencySupplier dependencies =
            (DependencySupplier)context.getServletContext().getAttribute(DependencySupplier.class.getName());
    GroovyResourcePublisher groovyPublisher = new GroovyResourcePublisher(binder, dependencies);
    context.getServletContext().setAttribute(GroovyResourcePublisher.class.getName(), groovyPublisher);

}
 
Example 17
Source File: Manager.java    From chipster with MIT License 4 votes vote down vote up
private void startAdmin(Configuration configuration) throws IOException,
			Exception {
		org.eclipse.jetty.server.Server adminServer = new org.eclipse.jetty.server.Server();
		ServerConnector connector = new ServerConnector(adminServer);
		connector.setPort(configuration.getInt("manager", "admin-port"));
		adminServer.setConnectors(new Connector[]{ connector });
		
		Constraint constraint = new Constraint();
		constraint.setName(Constraint.__BASIC_AUTH);
		constraint.setRoles(new String[] {ADMIN_ROLE});
		constraint.setAuthenticate(true);
		
		ConstraintMapping cm = new ConstraintMapping();
		cm.setConstraint(constraint);
		cm.setPathSpec("/*");
		
		HashLoginService loginService = new HashLoginService("Please enter Chipster Admin username and password");
		loginService.update(configuration.getString("manager", "admin-username"), 
				new Password(configuration.getString("manager", "admin-password")), 
				new String[] {ADMIN_ROLE});
		
		ConstraintSecurityHandler sh = new ConstraintSecurityHandler();
		sh.setLoginService(loginService);
		sh.addConstraintMapping(cm);
		
		WebAppContext context = new WebAppContext();
		context.setWar(new File(DirectoryLayout.getInstance().getWebappsDir(), "admin-web.war").getAbsolutePath());
        context.setContextPath("/");
		
//        context.setDescriptor(new ClassPathResource("WebContent/WEB-INF/web.xml").getURI().toString());
//        context.setResourceBase(new ClassPathResource("WebContent").getURI().toString());
//        context.setContextPath("/");
//        context.setParentLoaderPriority(true);
				
        context.setHandler(sh);
		HandlerCollection handlers = new HandlerCollection();
		handlers.setHandlers(new Handler[] {context, new DefaultHandler()});
				
		adminServer.setHandler(handlers);
        adminServer.start();
	}