org.eclipse.jetty.security.ConstraintSecurityHandler Java Examples

The following examples show how to use org.eclipse.jetty.security.ConstraintSecurityHandler. 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
private HandlerList configureHandlers() {
  final HandlerList handlerList = new HandlerList();
  Handler avaticaHandler = handler;

  // Wrap the provided handler for security if we made one
  if (null != config) {
    ConstraintSecurityHandler securityHandler = getSecurityHandler();
    securityHandler.setHandler(handler);
    avaticaHandler = securityHandler;
  }

  handlerList.setHandlers(new Handler[] {avaticaHandler, new DefaultHandler()});

  server.setHandler(handlerList);
  return handlerList;
}
 
Example #2
Source File: VmRuntimeWebAppContext.java    From appengine-java-vm-runtime with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new VmRuntimeWebAppContext.
 */
public VmRuntimeWebAppContext() {
  this.serverInfo = VmRuntimeUtils.getServerInfo();
  _scontext = new VmRuntimeServletContext();

  // Configure the Jetty SecurityHandler to understand our method of authentication
  // (via the UserService). Only the default ConstraintSecurityHandler is supported.
  AppEngineAuthentication.configureSecurityHandler(
      (ConstraintSecurityHandler) getSecurityHandler(), this);

  setMaxFormContentSize(MAX_RESPONSE_SIZE);
  setConfigurationClasses(preconfigurationClasses);
  // See http://www.eclipse.org/jetty/documentation/current/configuring-webapps.html#webapp-context-attributes
  // We also want the Jetty container libs to be scanned for annotations.
  setAttribute("org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern", ".*\\.jar");
  metadataCache = new VmMetadataCache();
  wallclockTimer = new VmTimer();
  ApiProxy.setDelegate(new VmApiProxyDelegate());
}
 
Example #3
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 #4
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 #5
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 #6
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 #7
Source File: CustomAuthHttpServerTest.java    From calcite-avatica with Apache License 2.0 6 votes vote down vote up
@Override public void customize(Server server) {
  HttpServer avaticaServer = getAvaticaServer();

  HandlerFactory factory = new HandlerFactory();
  Handler avaticaHandler = factory.getHandler(service,
          Driver.Serialization.PROTOBUF, null, configuration);

  if (isBasicAuth) {
    ConstraintSecurityHandler securityHandler =
            avaticaServer.configureBasicAuthentication(server, configuration);
    securityHandler.setHandler(avaticaHandler);
    avaticaHandler = securityHandler;
  }

  HandlerList handlerList = new HandlerList();
  handlerList.setHandlers(new Handler[] { avaticaHandler, new DefaultHandler()});
  server.setHandler(handlerList);
}
 
Example #8
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 #9
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 #10
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 #11
Source File: HttpServer.java    From calcite-avatica with Apache License 2.0 6 votes vote down vote up
private ConstraintSecurityHandler getSecurityHandler() {
  ConstraintSecurityHandler securityHandler = null;
  switch (config.getAuthenticationType()) {
  case SPNEGO:
    // Get the Handler for SPNEGO authentication
    securityHandler = configureSpnego(server, this.config);
    break;
  case BASIC:
    securityHandler = configureBasicAuthentication(server, config);
    break;
  case DIGEST:
    securityHandler = configureDigestAuthentication(server, config);
    break;
  default:
    // Pass
    break;
  }
  return securityHandler;
}
 
Example #12
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 #13
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 #14
Source File: ApplicationTest.java    From rest-utils with Apache License 2.0 6 votes vote down vote up
@Test
public void testSetUnsecurePathConstraintsWithUnSecure() {
  final Map<String, Object> config = ImmutableMap.of(
      RestConfig.AUTHENTICATION_SKIP_PATHS, "/path/1,/path/2");

  ConstraintSecurityHandler securityHandler = new TestApp(config).createBasicSecurityHandler();

  final List<ConstraintMapping> mappings = securityHandler.getConstraintMappings();
  assertThat(mappings.size(), is(3));
  assertThat(mappings.get(0).getPathSpec(), is("/*"));
  assertThat(mappings.get(0).getConstraint().getAuthenticate(), is(true));
  assertThat(mappings.get(1).getPathSpec(), is("/path/1"));
  assertThat(mappings.get(1).getConstraint().getAuthenticate(), is(false));
  assertThat(mappings.get(2).getPathSpec(), is("/path/2"));
  assertThat(mappings.get(2).getConstraint().getAuthenticate(), is(false));
}
 
Example #15
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 #16
Source File: ManagerApiMicroService.java    From apiman with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a basic auth security handler.
 * @throws Exception
 */
protected SecurityHandler createSecurityHandler() throws Exception {
    HashLoginService l = new HashLoginService();
    // UserStore is now separate store entity and must be added to HashLoginService
    UserStore userStore = new UserStore();
    l.setUserStore(userStore);
    for (User user : Users.getUsers()) {
        userStore.addUser(user.getId(), Credential.getCredential(user.getPassword()), user.getRolesAsArray());
    }
    l.setName("apimanrealm");

    ConstraintSecurityHandler csh = new ConstraintSecurityHandler();
    csh.setAuthenticator(new BasicAuthenticator());
    csh.setRealmName("apimanrealm");
    csh.setLoginService(l);

    return csh;
}
 
Example #17
Source File: Application.java    From cloud-security-xsuaa-integration with Apache License 2.0 6 votes vote down vote up
private static Server createJettyServer() {
	WebAppContext context = new WebAppContext();
	ConstraintSecurityHandler security = new ConstraintSecurityHandler();
	security.setAuthenticator(new JettyTokenAuthenticator(new XsuaaTokenAuthenticator()));
	context.setSecurityHandler(security);
	context.setConfigurations(new Configuration[] {
			new AnnotationConfiguration(), new WebXmlConfiguration(),
			new WebInfConfiguration(), new PlusConfiguration(), new MetaInfConfiguration(),
			new FragmentConfiguration(), new EnvConfiguration() });
	context.setContextPath("/");
	context.setResourceBase("src/main/java/webapp");

	// needed so that annotations from this project are also scanned
	context.setParentLoaderPriority(true);
	URL classes = HelloJavaServlet.class
			.getProtectionDomain()
			.getCodeSource()
			.getLocation();
	context.getMetaData()
			.setWebInfClassesDirs(
					Arrays.asList(Resource.newResource(classes)));

	Server server = new Server(8080);
	server.setHandler(context);
	return server;
}
 
Example #18
Source File: ManagerApiTestServer.java    From apiman with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a basic auth security handler.
 */
private SecurityHandler createSecurityHandler() {
    HashLoginService l = new HashLoginService();
    UserStore userStore = new UserStore();
    l.setUserStore(userStore);

    for (String [] userInfo : TestUsers.USERS) {
        String user = userInfo[0];
        String pwd = userInfo[1];
        String[] roles = new String[] { "apiuser" };
        if (user.startsWith("admin")) {
            roles = new String[] { "apiuser", "apiadmin"};
        }
        userStore.addUser(user, Credential.getCredential(pwd), roles);
    }
    l.setName("apimanrealm");

    ConstraintSecurityHandler csh = new ConstraintSecurityHandler();
    csh.setAuthenticator(new BasicAuthenticator());
    csh.setRealmName("apimanrealm");
    csh.setLoginService(l);

    return csh;
}
 
Example #19
Source File: BasicAuthTest.java    From apiman with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a basic auth security handler.
 */
private static SecurityHandler createSecurityHandler() {
    UserStore userStore = new UserStore();
    String user = "user";
    String pwd = "user123!";
    String[] roles = new String[] { "user" };
    userStore.addUser(user, Credential.getCredential(pwd), roles);

    HashLoginService l = new HashLoginService();
    l.setName("apimanrealm");
    l.setUserStore(userStore);

    ConstraintSecurityHandler csh = new ConstraintSecurityHandler();
    csh.setAuthenticator(new BasicAuthenticator());
    csh.setRealmName("apimanrealm");
    csh.setLoginService(l);

    return csh;
}
 
Example #20
Source File: GatewayMicroService.java    From apiman with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a basic auth security handler.
 */
protected SecurityHandler createSecurityHandler() throws Exception {
    HashLoginService l = new HashLoginService();
    UserStore userStore = new UserStore();
    l.setUserStore(userStore);
    for (User user : Users.getUsers()) {
        userStore.addUser(user.getId(), Credential.getCredential(user.getPassword()), user.getRolesAsArray());
    }
    l.setName("apimanrealm");

    ConstraintSecurityHandler csh = new ConstraintSecurityHandler();
    csh.setAuthenticator(new BasicAuthenticator());
    csh.setRealmName("apimanrealm");
    csh.setLoginService(l);

    return csh;
}
 
Example #21
Source File: ApplicationTest.java    From rest-utils with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateSecurityHandlerWithNoRoles() {
  final Map<String, Object> config = ImmutableMap.of(
      RestConfig.AUTHENTICATION_METHOD_CONFIG, RestConfig.AUTHENTICATION_METHOD_BASIC,
      RestConfig.AUTHENTICATION_REALM_CONFIG, REALM,
      RestConfig.AUTHENTICATION_ROLES_CONFIG, "");

  ConstraintSecurityHandler securityHandler = new TestApp(config).createBasicSecurityHandler();
  assertEquals(securityHandler.getRealmName(), REALM);
  assertTrue(securityHandler.getRoles().isEmpty());
  assertNotNull(securityHandler.getLoginService());
  assertNotNull(securityHandler.getAuthenticator());
  assertEquals(1, securityHandler.getConstraintMappings().size());
  assertFalse(securityHandler.getConstraintMappings().get(0).getConstraint().isAnyRole());
}
 
Example #22
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 #23
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 #24
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 #25
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 #26
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 #27
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 #28
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 #29
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 #30
Source File: ApplicationTest.java    From rest-utils with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateSecurityHandlerWithAllRoles() {
  final Map<String, Object> config = ImmutableMap.of(
      RestConfig.AUTHENTICATION_METHOD_CONFIG, RestConfig.AUTHENTICATION_METHOD_BASIC,
      RestConfig.AUTHENTICATION_REALM_CONFIG, REALM,
      RestConfig.AUTHENTICATION_ROLES_CONFIG, "*");

  ConstraintSecurityHandler securityHandler = new TestApp(config).createBasicSecurityHandler();
  assertEquals(securityHandler.getRealmName(), REALM);
  assertTrue(securityHandler.getRoles().isEmpty());
  assertNotNull(securityHandler.getLoginService());
  assertNotNull(securityHandler.getAuthenticator());
  assertEquals(1, securityHandler.getConstraintMappings().size());
  assertTrue(securityHandler.getConstraintMappings().get(0).getConstraint().isAnyRole());
}