org.eclipse.jetty.security.SecurityHandler Java Examples

The following examples show how to use org.eclipse.jetty.security.SecurityHandler. 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: SecurityModuleIntTest.java    From crnk-framework with Apache License 2.0 6 votes vote down vote up
protected TestContainerFactory getTestContainerFactory() throws TestContainerException {
    final TestContainerFactory testContainerFactory = super.getTestContainerFactory();

    return new TestContainerFactory() {

        @Override
        public TestContainer create(URI baseUri, DeploymentContext deploymentContext) {
            TestContainer container = testContainerFactory.create(baseUri, deploymentContext);
            try {
                Field field = container.getClass().getDeclaredField("server");
                field.setAccessible(true);
                Server server = (Server) field.get(container);

                Handler handler = server.getHandler();
                SecurityHandler securityHandler = identityManager.getSecurityHandler();
                if (securityHandler.getHandler() == null) {
                    securityHandler.setHandler(handler);
                }
                server.setHandler(securityHandler);
            } catch (Exception e) {
                throw new IllegalStateException(e);
            }
            return container;
        }
    };
}
 
Example #2
Source File: AbstractJettyAppServerTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void testDetectingOIDC() throws Exception {
    // given
    URL webXml = AbstractJettyAppServerTest.class.getResource("/web-oidc.xml");
    WebArchive archive = ShrinkWrap.create(WebArchive.class,"archive.war")
            .addAsWebInfResource(webXml, "web.xml");

    JettyAppServer server = new JettyAppServer();

    // when
    Authenticator installedAuthenticator = null;
    try {
        server.start();
        server.deploy(archive);

        installedAuthenticator = server.getServer()
                .getBean(DeploymentManager.class).getApps().iterator().next()
                .getContextHandler().getChildHandlerByClass(SecurityHandler.class).getAuthenticator();
    } finally {
        server.stop();
    }

    // assert
    Assert.assertTrue(installedAuthenticator instanceof KeycloakJettyAuthenticator);
}
 
Example #3
Source File: AbstractJettyAppServerTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void testDetectingSAML() throws Exception {
    // given
    URL webXml = AbstractJettyAppServerTest.class.getResource("/web-saml.xml");
    WebArchive archive = ShrinkWrap.create(WebArchive.class,"archive.war")
            .addAsWebInfResource(webXml, "web.xml");

    JettyAppServer server = new JettyAppServer();

    // when
    Authenticator installedAuthenticator = null;
    try {
        server.start();
        server.deploy(archive);

        installedAuthenticator = server.getServer()
                .getBean(DeploymentManager.class).getApps().iterator().next()
                .getContextHandler().getChildHandlerByClass(SecurityHandler.class).getAuthenticator();
    } finally {
        server.stop();
    }

    // assert
    Assert.assertTrue(installedAuthenticator instanceof KeycloakSamlAuthenticator);
}
 
Example #4
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 #5
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 #6
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 #7
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 #8
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 #9
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 #10
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 #11
Source File: ServerRuntime.java    From EDDI with Apache License 2.0 6 votes vote down vote up
public ServerRuntime(Options options,
                     GuiceResteasyBootstrapServletContextListener resteasyContextListener,
                     SwaggerServletContextListener swaggerContextListener,
                     HttpServletDispatcher httpServletDispatcher,
                     SecurityHandler securityHandler,
                     ThreadPoolExecutor threadPoolExecutor,
                     MongoLoginService mongoLoginService,
                     AdapterConfig keycloakAdapterConfig,
                     MeterRegistry meterRegistry,
                     @Named("system.environment") String environment,
                     @Named("systemRuntime.resourceDir") String resourceDir) {
    this.options = options;
    this.resteasyContextListener = resteasyContextListener;
    this.swaggerContextListener = swaggerContextListener;
    this.httpServletDispatcher = httpServletDispatcher;
    this.securityHandler = securityHandler;
    this.threadPoolExecutor = threadPoolExecutor;
    this.mongoLoginService = mongoLoginService;
    this.keycloakAdapterConfig = keycloakAdapterConfig;
    this.meterRegistry = meterRegistry;
    this.environment = environment;
    this.resourceDir = resourceDir;
    RegisterBuiltin.register(ResteasyProviderFactory.getInstance());
}
 
Example #12
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 #13
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 #14
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 #15
Source File: WebServiceServerConverter.java    From citrus-admin with Apache License 2.0 5 votes vote down vote up
@Override
protected Map<String, Class<?>> getOptionTypeMappings() {
    Map<String, Class<?>> mappings = super.getOptionTypeMappings();
    mappings.put("securityHandler", SecurityHandler.class);
    mappings.put("servletHandler", ServletHandler.class);
    mappings.put("connector", Connector.class);
    return mappings;
}
 
Example #16
Source File: WebSocketServerConverter.java    From citrus-admin with Apache License 2.0 5 votes vote down vote up
@Override
protected Map<String, Class<?>> getOptionTypeMappings() {
    Map<String, Class<?>> mappings = super.getOptionTypeMappings();
    mappings.put("securityHandler", SecurityHandler.class);
    mappings.put("servletHandler", ServletHandler.class);
    mappings.put("connector", Connector.class);
    return mappings;
}
 
Example #17
Source File: HttpServerConverter.java    From citrus-admin with Apache License 2.0 5 votes vote down vote up
@Override
protected Map<String, Class<?>> getOptionTypeMappings() {
    Map<String, Class<?>> mappings = super.getOptionTypeMappings();
    mappings.put("securityHandler", SecurityHandler.class);
    mappings.put("servletHandler", ServletHandler.class);
    mappings.put("connector", Connector.class);
    return mappings;
}
 
Example #18
Source File: AbstractJettyMixin.java    From attic-polygene-java with Apache License 2.0 4 votes vote down vote up
protected SecurityHandler buildSecurityHandler()
{
    return null;
}
 
Example #19
Source File: HttpReceiverServerPush.java    From datacollector with Apache License 2.0 4 votes vote down vote up
public static SecurityHandler getSpnegoAuthHandler(HttpSourceConfigs httpCourceConf, Stage.Context context) throws StageException {
  String domainRealm = httpCourceConf.getSpnegoConfigBean().getKerberosRealm();
  String principal = httpCourceConf.getSpnegoConfigBean().getSpnegoPrincipal();
  String keytab = httpCourceConf.getSpnegoConfigBean().getSpnegoKeytabFilePath();

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

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

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

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

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

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

  return csh;
}
 
Example #20
Source File: WebContextWithExtraConfigurations.java    From logsniffer with GNU Lesser General Public License v3.0 4 votes vote down vote up
public WebContextWithExtraConfigurations(final SessionHandler sessionHandler, final SecurityHandler securityHandler,
		final ServletHandler servletHandler, final ErrorHandler errorHandler) {
	super(sessionHandler, securityHandler, servletHandler, errorHandler);
}
 
Example #21
Source File: ServerRuntimeModule.java    From EDDI with Apache License 2.0 4 votes vote down vote up
@Provides
@Singleton
public IServerRuntime provideServerRuntime(@Named("system.environment") String environment,
                                           @Named("systemRuntime.resourceDir") String resourceDir,
                                           @Named("webServer.applicationConfigurationClass") String applicationConfigurationClass,
                                           @Named("webServer.host") String host,
                                           @Named("webServer.httpPort") Integer httpPort,
                                           @Named("webServer.httpsPort") Integer httpsPort,
                                           @Named("webServer.keyStorePassword") String keyStorePassword,
                                           @Named("webServer.keyStorePath") String keyStorePath,
                                           @Named("webServer.defaultPath") String defaultPath,
                                           @Named("webServer.responseDelayInMillis") Long responseDelayInMillis,
                                           @Named("webServer.virtualHosts") String virtualHosts,
                                           @Named("webServer.useCrossSiteScriptingHeaderParam") Boolean useCrossSiteScriptingHeaderParam,
                                           @Named("webServer.idleTime") Long idleTime,
                                           @Named("webServer.outputBufferSize") Integer outputBufferSize,
                                           @Named("webServer.securityHandlerType") String securityHandlerType,
                                           Provider<BasicSecurityHandler> basicSecurityHandlerProvider,
                                           Provider<KeycloakSecurityHandler> keycloakSecurityHandlerProvider,
                                           GuiceResteasyBootstrapServletContextListener contextListener,
                                           SwaggerServletContextListener swaggerContextListener,
                                           ThreadPoolExecutor threadPoolExecutor,
                                           HttpServletDispatcher httpServletDispatcher,
                                           MongoLoginService mongoLoginService,
                                           AdapterConfig keycloakAdapterConfig,
                                           MeterRegistry meterRegistry)
        throws ClassNotFoundException {

    ServerRuntime.Options options = new ServerRuntime.Options();
    options.applicationConfiguration = Class.forName(applicationConfigurationClass);
    options.loginService = mongoLoginService;
    options.host = host;
    options.httpPort = httpPort;
    options.httpsPort = httpsPort;
    options.keyStorePassword = keyStorePassword;
    options.keyStorePath = StringUtilities.joinStrings(File.separator,
            System.getProperty("user.dir"), "resources",
            keyStorePath);
    options.defaultPath = defaultPath;
    options.responseDelayInMillis = responseDelayInMillis;
    options.virtualHosts = virtualHosts.split(";");
    options.useCrossSiteScripting = useCrossSiteScriptingHeaderParam;
    options.idleTime = idleTime;
    options.outputBufferSize = outputBufferSize;
    options.securityHandlerType = securityHandlerType;

    SecurityHandler securityHandler = null;
    if (AUTHENTICATION_BASIC_AUTH.equals(securityHandlerType)) {
        securityHandler = basicSecurityHandlerProvider.get();
    } else if (AUTHENTICATION_KEYCLOAK.equals(securityHandlerType)) {
        securityHandler = keycloakSecurityHandlerProvider.get();
    }

    return new ServerRuntime(options, contextListener, swaggerContextListener, httpServletDispatcher,
            securityHandler, threadPoolExecutor, mongoLoginService, keycloakAdapterConfig, meterRegistry, environment, resourceDir);
}
 
Example #22
Source File: InMemoryIdentityManager.java    From crnk-framework with Apache License 2.0 4 votes vote down vote up
public SecurityHandler getSecurityHandler() {
	return securityHandler;
}