org.eclipse.jetty.util.security.Constraint Java Examples

The following examples show how to use org.eclipse.jetty.util.security.Constraint. 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: AuthUtil.java    From rest-utils with Apache License 2.0 6 votes vote down vote up
/**
 * Build a secure or unsecure constraint using standard RestConfig for a path.
 *
 * @param restConfig the rest app's config.
 * @param authenticate authentication flag.
 * @param pathSpec path for constraint.
 * @return the constraint mapping.
 */
private static ConstraintMapping createConstraint(
    final RestConfig restConfig,
    final boolean authenticate,
    final String pathSpec
) {
  final Constraint constraint = new Constraint();
  constraint.setAuthenticate(authenticate);
  if (authenticate) {
    final List<String> roles = restConfig.getList(RestConfig.AUTHENTICATION_ROLES_CONFIG);
    constraint.setRoles(roles.toArray(new String[0]));
  }

  final ConstraintMapping mapping = new ConstraintMapping();
  mapping.setConstraint(constraint);
  mapping.setMethod("*");
  if (authenticate && AuthUtil.isCorsEnabled(restConfig)) {
    mapping.setMethodOmissions(new String[]{"OPTIONS"});
  }
  mapping.setPathSpec(pathSpec);
  return mapping;
}
 
Example #2
Source File: HttpService.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
/**
 * Enables basic HTTP authentication on the server.
 */
public HttpService basicAuthentication(String username, String password) {
    HashLoginService l = new HashLoginService();
    UserStore userStore = new UserStore();
    userStore.addUser(username, Credential.getCredential(password), new String[]{"user"});
    l.setUserStore(userStore);
    l.setName("test-realm");

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

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

    ConstraintSecurityHandler csh = new ConstraintSecurityHandler();
    csh.setAuthenticator(new BasicAuthenticator());
    csh.setRealmName("test-realm");
    csh.addConstraintMapping(constraintMapping);
    csh.setLoginService(l);

    this.securityHandler = Optional.of(csh);

    return this;
}
 
Example #3
Source File: HttpServer.java    From calcite-avatica with Apache License 2.0 6 votes vote down vote up
/**
 * Configures the <code>connector</code> given the <code>config</code> for using SPNEGO.
 *
 * @param config The configuration
 */
protected ConstraintSecurityHandler configureSpnego(Server server,
    AvaticaServerConfiguration config) {
  final String realm = Objects.requireNonNull(config.getKerberosRealm());
  final String principal = Objects.requireNonNull(config.getKerberosPrincipal());

  // A customization of SpnegoLoginService to explicitly set the server's principal, otherwise
  // we would have to require a custom file to set the server's principal.
  PropertyBasedSpnegoLoginService spnegoLoginService =
      new PropertyBasedSpnegoLoginService(realm, principal);

  // Roles are "realms" for Kerberos/SPNEGO
  final String[] allowedRealms = getAllowedRealms(realm, config);

  return configureCommonAuthentication(Constraint.__SPNEGO_AUTH,
      allowedRealms, new AvaticaSpnegoAuthenticator(), realm, spnegoLoginService);
}
 
Example #4
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 #5
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 #6
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 #7
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 #8
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 #9
Source File: ApplicationTest.java    From rest-utils with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateSecurityHandlerWithSpecificRoles() {
  final Map<String, Object> config = ImmutableMap.of(
      RestConfig.AUTHENTICATION_METHOD_CONFIG, RestConfig.AUTHENTICATION_METHOD_BASIC,
      RestConfig.AUTHENTICATION_REALM_CONFIG, REALM,
      RestConfig.AUTHENTICATION_ROLES_CONFIG, "roleA, roleB");

  ConstraintSecurityHandler securityHandler = new TestApp(config).createBasicSecurityHandler();
  assertEquals(securityHandler.getRealmName(), REALM);
  assertFalse(securityHandler.getRoles().isEmpty());
  assertNotNull(securityHandler.getLoginService());
  assertNotNull(securityHandler.getAuthenticator());
  assertEquals(1, securityHandler.getConstraintMappings().size());
  final Constraint constraint = securityHandler.getConstraintMappings().get(0).getConstraint();
  assertFalse(constraint.isAnyRole());
  assertEquals(constraint.getRoles().length, 2);
  assertArrayEquals(constraint.getRoles(), new String[]{"roleA", "roleB"});
}
 
Example #10
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 #11
Source File: DrillHttpSecurityHandlerProvider.java    From Bats with Apache License 2.0 6 votes vote down vote up
/**
 * Return's list of configured mechanisms for HTTP authentication. For backward
 * compatibility if authentication is enabled it will include FORM mechanism by default.
 * @param config - {@link DrillConfig}
 * @return
 */
public static Set<String> getHttpAuthMechanisms(DrillConfig config) {
  final Set<String> configuredMechs = new HashSet<>();
  final boolean authEnabled = config.getBoolean(ExecConstants.USER_AUTHENTICATION_ENABLED);

  if (authEnabled) {
    if (config.hasPath(ExecConstants.HTTP_AUTHENTICATION_MECHANISMS)) {
      configuredMechs.addAll(
          AuthStringUtil.asSet(config.getStringList(ExecConstants.HTTP_AUTHENTICATION_MECHANISMS)));
    } else {
      // For backward compatibility
      configuredMechs.add(Constraint.__FORM_AUTH);
    }
  }
  return configuredMechs;
}
 
Example #12
Source File: PaxWebIntegrationService.java    From keycloak with Apache License 2.0 6 votes vote down vote up
protected void addConstraintMapping(WebContainer service, ConstraintMapping constraintMapping) {
    Constraint constraint = constraintMapping.getConstraint();
    String[] roles = constraint.getRoles();
    // name property is unavailable on constraint object :/

    String name = "Constraint-" + new SecureRandom().nextInt(Integer.MAX_VALUE);

    int dataConstraint = constraint.getDataConstraint();
    String dataConstraintStr;
    switch (dataConstraint) {
        case Constraint.DC_UNSET: dataConstraintStr = null; break;
        case Constraint.DC_NONE: dataConstraintStr = "NONE"; break;
        case Constraint.DC_CONFIDENTIAL: dataConstraintStr = "CONFIDENTIAL"; break;
        case Constraint.DC_INTEGRAL: dataConstraintStr = "INTEGRAL"; break;
        default:
            log.warnv("Unknown data constraint: " + dataConstraint);
            dataConstraintStr = "CONFIDENTIAL";
    }
    List<String> rolesList = Arrays.asList(roles);

    log.debug("Adding security constraint name=" + name + ", url=" + constraintMapping.getPathSpec() + ", dataConstraint=" + dataConstraintStr + ", canAuthenticate="
    + constraint.getAuthenticate() + ", roles=" + rolesList);
    service.registerConstraintMapping(name, constraintMapping.getPathSpec(), null, dataConstraintStr, constraint.getAuthenticate(), rolesList, httpContext);
}
 
Example #13
Source File: BaleenWebApi.java    From baleen with Apache License 2.0 6 votes vote down vote up
private void addServlet(final Servlet servlet, final String path, WebPermission... permissions) {
  servletContextHandler.addServlet(new ServletHolder(servlet), path);
  if (permissions != null && permissions.length > 0) {
    for (WebPermission p : permissions) {
      Constraint constraint = getConstraintForPermission(p);
      ConstraintMapping mapping = new ConstraintMapping();
      mapping.setPathSpec(servletContextHandler.getContextPath() + path);
      mapping.setConstraint(constraint);
      if (p.hasMethod()) {
        mapping.setMethod(p.getMethod().name());
      }
      constraintMappings.add(mapping);
    }
  }

  LOGGER.info("Servlet added on path {}", path);
}
 
Example #14
Source File: PaxWebIntegrationService.java    From keycloak with Apache License 2.0 6 votes vote down vote up
protected void addConstraintMapping(WebContainer service, ConstraintMapping constraintMapping) {
    Constraint constraint = constraintMapping.getConstraint();
    String[] roles = constraint.getRoles();
    // name property is unavailable on constraint object :/

    String name = "Constraint-" + new SecureRandom().nextInt(Integer.MAX_VALUE);

    int dataConstraint = constraint.getDataConstraint();
    String dataConstraintStr;
    switch (dataConstraint) {
        case Constraint.DC_UNSET: dataConstraintStr = null; break;
        case Constraint.DC_NONE: dataConstraintStr = "NONE"; break;
        case Constraint.DC_CONFIDENTIAL: dataConstraintStr = "CONFIDENTIAL"; break;
        case Constraint.DC_INTEGRAL: dataConstraintStr = "INTEGRAL"; break;
        default:
            log.warnv("Unknown data constraint: " + dataConstraint);
            dataConstraintStr = "CONFIDENTIAL";
    }
    List<String> rolesList = Arrays.asList(roles);

    log.debug("Adding security constraint name=" + name + ", url=" + constraintMapping.getPathSpec() + ", dataConstraint=" + dataConstraintStr + ", canAuthenticate="
    + constraint.getAuthenticate() + ", roles=" + rolesList);
    service.registerConstraintMapping(name, constraintMapping.getPathSpec(), null, dataConstraintStr, constraint.getAuthenticate(), rolesList, httpContext);
}
 
Example #15
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 #16
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 #17
Source File: BaleenWebApi.java    From baleen with Apache License 2.0 5 votes vote down vote up
private Constraint getConstraintForPermission(WebPermission permission) {

    Constraint constraint = new Constraint();
    constraint.setName(permission.getName());
    if (permission.hasRoles()) {
      constraint.setRoles(permission.getRoles());
    }
    constraint.setAuthenticate(permission.isAuthenticated());
    return constraint;
  }
 
Example #18
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 #19
Source File: HttpServer.java    From sensorhub with Mozilla Public License 2.0 5 votes vote down vote up
public void addServletSecurity(String pathSpec, String... roles)
{
    if (securityHandler != null)
    {
        Constraint constraint = new Constraint();
        constraint.setName(Constraint.__DIGEST_AUTH);
        constraint.setRoles(roles);
        constraint.setAuthenticate(true);         
        ConstraintMapping cm = new ConstraintMapping();
        cm.setConstraint(constraint);
        cm.setPathSpec(pathSpec);
        securityHandler.addConstraintMapping(cm);
    }
}
 
Example #20
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 #21
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 #22
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 #23
Source File: PaxWebIntegrationService.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public boolean addConstraintMapping(HttpContext httpContext, WebContainer service, Object cm) {
    if (cm instanceof ConstraintMapping) {
        ConstraintMapping constraintMapping = (ConstraintMapping) cm;
        Constraint constraint = constraintMapping.getConstraint();
        String[] roles = constraint.getRoles();
        // name property is unavailable on constraint object :/

        String name = "Constraint-" + new SecureRandom().nextInt(Integer.MAX_VALUE);

        int dataConstraint = constraint.getDataConstraint();
        String dataConstraintStr;
        switch (dataConstraint) {
            case Constraint.DC_UNSET:
                dataConstraintStr = null;
                break;
            case Constraint.DC_NONE:
                dataConstraintStr = "NONE";
                break;
            case Constraint.DC_CONFIDENTIAL:
                dataConstraintStr = "CONFIDENTIAL";
                break;
            case Constraint.DC_INTEGRAL:
                dataConstraintStr = "INTEGRAL";
                break;
            default:
                log.warnv("Unknown data constraint: " + dataConstraint);
                dataConstraintStr = "CONFIDENTIAL";
        }
        List<String> rolesList = Arrays.asList(roles);

        log.debug("Adding security constraint name=" + name + ", url=" + constraintMapping.getPathSpec() + ", dataConstraint=" + dataConstraintStr + ", canAuthenticate="
                + constraint.getAuthenticate() + ", roles=" + rolesList);
        service.registerConstraintMapping(name, constraintMapping.getPathSpec(), null, dataConstraintStr, constraint.getAuthenticate(), rolesList, httpContext);
        return true;
    }
    return false;
}
 
Example #24
Source File: PaxWebIntegrationService.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public boolean addConstraintMapping(HttpContext httpContext, WebContainer service, Object cm) {
    if (cm instanceof ConstraintMapping) {
        ConstraintMapping constraintMapping = (ConstraintMapping) cm;
        Constraint constraint = constraintMapping.getConstraint();
        String[] roles = constraint.getRoles();
        // name property is unavailable on constraint object :/

        String name = "Constraint-" + new SecureRandom().nextInt(Integer.MAX_VALUE);

        int dataConstraint = constraint.getDataConstraint();
        String dataConstraintStr;
        switch (dataConstraint) {
            case Constraint.DC_UNSET:
                dataConstraintStr = null;
                break;
            case Constraint.DC_NONE:
                dataConstraintStr = "NONE";
                break;
            case Constraint.DC_CONFIDENTIAL:
                dataConstraintStr = "CONFIDENTIAL";
                break;
            case Constraint.DC_INTEGRAL:
                dataConstraintStr = "INTEGRAL";
                break;
            default:
                log.warnv("Unknown data constraint: " + dataConstraint);
                dataConstraintStr = "CONFIDENTIAL";
        }
        List<String> rolesList = Arrays.asList(roles);

        log.debug("Adding security constraint name=" + name + ", url=" + constraintMapping.getPathSpec() + ", dataConstraint=" + dataConstraintStr + ", canAuthenticate="
                + constraint.getAuthenticate() + ", roles=" + rolesList);
        service.registerConstraintMapping(name, constraintMapping.getPathSpec(), null, dataConstraintStr, constraint.getAuthenticate(), rolesList, httpContext);
        return true;
    }
    return false;
}
 
Example #25
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 #26
Source File: HttpServerExtension.java    From kareldb with Apache License 2.0 5 votes vote down vote up
@Override
protected ConstraintSecurityHandler configureBasicAuthentication(Server server,
                                                                 AvaticaServerConfiguration config) {
    LOG.info("Configuring basic auth");
    final String[] allowedRoles = config.getAllowedRoles();
    final String realm = config.getHashLoginServiceRealm();

    JAASLoginService loginService = new JAASLoginService(realm);
    server.addBean(loginService);

    return configureCommonAuthentication(Constraint.__BASIC_AUTH,
        allowedRoles, new BasicAuthenticator(), null, loginService);
}
 
Example #27
Source File: HttpServerExtension.java    From kareldb with Apache License 2.0 5 votes vote down vote up
@Override
protected ConstraintSecurityHandler configureDigestAuthentication(Server server,
                                                                  AvaticaServerConfiguration config) {
    LOG.info("Configuring digest auth");
    final String[] allowedRoles = config.getAllowedRoles();
    final String realm = config.getHashLoginServiceRealm();

    JAASLoginService loginService = new JAASLoginService(realm);
    server.addBean(loginService);

    return configureCommonAuthentication(Constraint.__DIGEST_AUTH,
        allowedRoles, new DigestAuthenticator(), null, loginService);
}
 
Example #28
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 #29
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 #30
Source File: AuthenticationIntegrationTest.java    From cruise-control with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public List<ConstraintMapping> constraintMappings() {
  ConstraintMapping mapping = new ConstraintMapping();
  Constraint constraint = new Constraint();
  constraint.setAuthenticate(true);
  constraint.setName(Constraint.__BASIC_AUTH);
  constraint.setRoles(new String[] { ADMIN_ROLE });
  mapping.setConstraint(constraint);
  mapping.setPathSpec(ANY_PATH);

  return Collections.singletonList(mapping);
}