@Override public boolean configure(final FeatureContext featureContext) { final UserRepository userRepo = CDI.current().select(UserRepository.class).get(); final Authenticator<String, User> authenticator = new GoogleAuthenticator( authConfig.getClientId(), userRepo, authConfig.getHostedDomain() ); final Authenticator<String, User> cachingAuthenticator = new CachingAuthenticator<>( metricRegistry, authenticator, authConfig.getAuthenticationCachePolicy() ); featureContext.register(new AuthDynamicFeature( new OAuthCredentialAuthFilter.Builder<User>() .setAuthenticator(cachingAuthenticator) .setPrefix("Bearer") .buildAuthFilter())); featureContext.register(new AuthValueFactoryProvider.Binder<>(User.class)); return true; }
@Override public void run(PublicAuthConfiguration conf, Environment environment) throws Exception { DataSourceFactory dataSourceFactory = conf.getDataSourceFactory(); jdbi = new DBIFactory().build(environment, dataSourceFactory, "postgresql"); initialiseMetrics(conf, environment); TokenService tokenService = new TokenService(conf.getTokensConfiguration()); environment.jersey().register(new AuthDynamicFeature( new OAuthCredentialAuthFilter.Builder<Token>() .setAuthenticator(new TokenAuthenticator(tokenService)) .setPrefix("Bearer") .buildAuthFilter())); environment.jersey().register(new AuthValueFactoryProvider.Binder<>(Token.class)); environment.jersey().register(new PublicAuthResource(new AuthTokenDao(jdbi), tokenService)); environment.jersey().register(new HealthCheckResource(environment)); environment.jersey().register(new ValidationExceptionMapper()); environment.jersey().register(new TokenNotFoundExceptionMapper()); environment.healthChecks().register("database", new DatabaseHealthCheck(conf,environment)); environment.servlets().addFilter("LoggingFilter", new LoggingFilter()) .addMappingForUrlPatterns(of(REQUEST), true, "/v1" + "/*"); }
@Override public void run(final AuthriteServiceConfiguration configuration, final Environment environment) { final DBIFactory factory = new DBIFactory(); final DBI dbi = factory.build(environment, configuration.getDatabase(), "h2"); final JWTConfiguration jwtConfiguration = configuration.getJwt(); final JwtTokenManager jwtTokenManager = jwtConfiguration.buildTokenManager(); final PasswordManagementConfiguration passwordManagement = configuration.getPasswordManagement(); final UsersService usersService = new UsersService(dbi, jwtTokenManager, passwordManagement); final UsersResource usersResource = new UsersResource(usersService, jwtConfiguration); environment.jersey().register(usersResource); final PlayersResource playersResource = new PlayersResource(dbi); environment.jersey().register(playersResource); environment.jersey().register(new AuthDynamicFeature(jwtConfiguration.buildAuthFilter())); environment.jersey().register(RolesAllowedDynamicFeature.class); //Required to use @Auth to inject a custom Principal type into your resource environment.jersey().register(new AuthValueFactoryProvider.Binder<>(User.class)); }
/** * * @param environment The Dropwizard environment * @param authorizer A specific authorizer to use instead of the default PermitAllAuthorizer. See * http://www.dropwizard.io/0.9.1/docs/manual/auth.html for more details */ public void registerAuthenticator(Environment environment, Authorizer<Peer> authorizer) { Preconditions.checkNotNull(environment, "Illegal call to registerAuthenticator with a null Environment object"); Authenticator<BasicCredentials, Peer> authenticator; if (this.cachePolicy != null) { authenticator = createCachingAuthenticator(environment.metrics()); } else { authenticator = createAuthenticator(); } environment.jersey().register(new AuthDynamicFeature( new BasicCredentialAuthFilter.Builder<Peer>() .setAuthenticator(authenticator) .setAuthorizer(authorizer) .setRealm(this.realm) .buildAuthFilter())); environment.jersey().register(RolesAllowedDynamicFeature.class); environment.jersey().register(new AuthValueFactoryProvider.Binder<>(Peer.class)); }
@VisibleForTesting void registerUserAuth(UserInfoConfiguration configuration, Environment environment) { JwtVerifier jwtVerifier = configuration.getSecurity().getJwtVerification().newInstanceFromConfig(); environment.jersey().register(new AuthDynamicFeature( new OAuthCredentialAuthFilter.Builder<User>() .setAuthenticator(new OAuth2Authenticator(jwtVerifier)) .setAuthorizer(new OAuth2Authorizer()) .setPrefix("Bearer") .buildAuthFilter() )); // Enable the resource protection annotations: @RolesAllowed, @PermitAll & @DenyAll environment.jersey().register(RolesAllowedDynamicFeature.class); // Enable the @Auth annotation for binding authenticated users to resource method parameters environment.jersey().register(new AuthValueFactoryProvider.Binder<>(User.class)); }
@Override public void run(CoreServiceConfig t, Environment e) throws Exception { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(CoreOAuth2ServiceLoader.class); ctx.registerShutdownHook(); ctx.start(); e.jersey().register(new JacksonMessageBodyProvider(new GPJacksonSupport().getDefaultMapper())); e.jersey().register(new OAuth2ExceptionProvider()); e.jersey().register(new AuthDynamicFeature( new OAuthCredentialAuthFilter.Builder<GPAuthenticatedPrincipal>() .setAuthenticator(new CoreOAuthAuthenticator(t)) .setPrefix("Bearer") .buildAuthFilter())); e.jersey().register(RolesAllowedDynamicFeature.class); e.jersey().register(new AuthValueFactoryProvider.Binder<>(Principal.class)); e.healthChecks().register("service-health-check", new CoreServiceHealthCheck()); Map<String, Object> resources = ctx.getBeansWithAnnotation(Path.class); for (Map.Entry<String, Object> entry : resources.entrySet()) { e.jersey().register(entry.getValue()); } }
private static void setupLdapAuth(LdapConfiguration ldapConfiguration, Environment environment) { final LdapAuthenticator ldapAuthenticator = new LdapAuthenticator(ldapConfiguration); final CachingAuthenticator<BasicCredentials, User> cachingAuthenticator = new CachingAuthenticator<>( environment.metrics(), TenacityAuthenticator.wrap( new ResourceAuthenticator(ldapAuthenticator), BreakerboxDependencyKey.BRKRBX_LDAP_AUTH), ldapConfiguration.getCachePolicy() ); environment.jersey().register(new AuthDynamicFeature( new BasicCredentialAuthFilter.Builder<User>() .setAuthenticator(cachingAuthenticator) .setRealm("breakerbox") .buildAuthFilter())); environment.jersey().register(new AuthValueFactoryProvider.Binder<>(User.class)); }
@Override public void run(ExampleAppConfiguration configuration, Environment environment) throws Exception { final LdapConfiguration ldapConfiguration = configuration.getLdapConfiguration(); Authenticator<BasicCredentials, User> ldapAuthenticator = new CachingAuthenticator<>( environment.metrics(), new ResourceAuthenticator(new LdapAuthenticator(ldapConfiguration)), ldapConfiguration.getCachePolicy()); environment.jersey().register(new AuthDynamicFeature( new BasicCredentialAuthFilter.Builder<User>() .setAuthenticator(ldapAuthenticator) .setRealm("LDAP") .buildAuthFilter())); environment.jersey().register(new AuthValueFactoryProvider.Binder<>(User.class)); environment.healthChecks().register("ldap", new LdapHealthCheck<>( new ResourceAuthenticator(new LdapCanAuthenticate(ldapConfiguration)))); }
@Override public void run(ApiConfig configuration, Environment environment) throws Exception { LOGGER.info("api started up"); injector = guiceBundle.getInjector(); JerseyEnvironment jersey = environment.jersey(); register(environment.lifecycle(), REFLECTIONS.getSubTypesOf(Managed.class)); // registers NbdServer // injector.getInstance(SessionFactory.class); //init DB installCorsFilter(environment); //init all Singletons semi-eagerly REFLECTIONS.getTypesAnnotatedWith(Singleton.class).forEach(injector::getInstance); final Set<Class<?>> resources = REFLECTIONS.getTypesAnnotatedWith(Path.class); register(jersey, resources); jersey.register(new LoggingExceptionMapper<Throwable>() { @Override protected String formatErrorMessage(long id, Throwable exception) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); exception.printStackTrace(pw); return sw.toString(); } }); jersey.register(new JsonProcessingExceptionMapper(true)); jersey.register(new EarlyEofExceptionMapper()); final TrivialAuthenticator instance = injector.getInstance(TrivialAuthenticator.class); environment.jersey().register(new AuthDynamicFeature( new BasicCredentialAuthFilter.Builder<Principal>() .setAuthenticator(instance) .setAuthorizer((principal, role) -> false) .buildAuthFilter())); environment.jersey().register(RolesAllowedDynamicFeature.class); }
@Override public void run(UserServiceConfiguration userServiceConfiguration, Environment environment) throws Exception { dbClient = userServiceConfiguration.getDbConfig().build(environment); log.info("Connected to db: " + dbClient.getConnectString()); /* * Setup basic authentication against DB table. */ environment.jersey().register(new AuthDynamicFeature( new BasicCredentialAuthFilter.Builder<PrincipalUser>() .setAuthenticator(new SimpleAuthenticator(dbClient)) .setRealm("amigo_user") .buildAuthFilter())); environment.jersey().register(new AuthValueFactoryProvider.Binder<>(PrincipalUser.class)); environment.healthChecks().register("database", new DBHealthCheck(dbClient)); /* * Register resources with jersey. */ final UserResource userResource = new UserResource(dbClient); /* * Setup jersey environment. */ environment.jersey().setUrlPattern(EndpointUtils.ENDPOINT_ROOT + "/*"); environment.jersey().register(userResource); log.info("Done with all initializations for user service"); }
@Override public void run(final SecureTodoConfiguration configuration, final Environment environment) { final DBIFactory dbiFactory = new DBIFactory(); final DBI todoJdbi = dbiFactory.build(environment, configuration.getTodoDbDataSourceFactory(), "todoDb"); final TodoUserDAO todoUserDao = todoJdbi.onDemand(TodoUserDAO.class); final TodoItemDAO todoItemDao = todoJdbi.onDemand(TodoItemDAO.class); final AccessControlContextFactory accessControlContextFactory = configuration.getAccessControlContextFactory(); accessControlContextFactory.initialize(environment, configuration.getOaccDbDataSourceFactory(), "oacc"); environment.jersey().register(new TodoUserResource(new TodoUserService(todoUserDao, accessControlContextFactory))); environment.jersey().register(new TodoItemResource(new TodoItemService(todoItemDao))); environment.jersey().register(new AuthDynamicFeature( new BasicCredentialAuthFilter.Builder<OaccPrincipal>() .setAuthenticator(new OaccBasicAuthenticator(accessControlContextFactory)) .setRealm("OACC Basic Authentication") .buildAuthFilter())); // to use @Auth to inject a custom Principal type into a resource: environment.jersey().register(new AuthValueFactoryProvider.Binder<>(OaccPrincipal.class)); environment.jersey().register(new AuthorizationExceptionMapper(environment.metrics())); environment.jersey().register(new IllegalArgumentExceptionMapper(environment.metrics())); environment.jersey().register(new InvalidCredentialsExceptionMapper(environment.metrics())); environment.jersey().register(new NotAuthenticatedExceptionMapper(environment.metrics())); }
@Override public void run(Configuration configuration, Environment environment) { environment.jersey().register(new LoginResource()); environment.jersey().register(new UserResource()); environment.jersey().register(new AuthDynamicFeature( new OAuthCredentialAuthFilter.Builder<PrincipalImpl>() .setAuthenticator(new TestOAuthAuthenticator()).setPrefix("Bearer") .buildAuthFilter())); environment.jersey().register(RolesAllowedDynamicFeature.class); environment.jersey().register(new AuthValueFactoryProvider.Binder<>(PrincipalImpl.class)); //TODO move this cleanup into the tests environment.lifecycle().manage(new Managed() { @Override public void start() { } @Override public void stop() { flushRedis(); } private void flushRedis() { try (StatefulRedisConnection<String, String> connection = redisClient.connect()) { connection.sync().flushdb(); } redisClient.shutdownAsync(); } }); }
@Override public void run(SystemApiConfiguration config, Environment environment) throws Exception { this.environment = environment; if (config.forwardHttps()) { addHttpsForward(environment.getApplicationContext()); } environment.jersey().register(RolesAllowedDynamicFeature.class); final BasicCredentialAuthFilter<UserConfiguration> userBasicCredentialAuthFilter = new BasicCredentialAuthFilter.Builder<UserConfiguration>() .setAuthenticator(new BasicAuthenticator(config.getUser())) .setRealm("System-Api") .setAuthorizer(new BasicAuthorizer(config.getUser())) .buildAuthFilter(); SystemInfo systemInfo = new SystemInfo(); HardwareAbstractionLayer hal = systemInfo.getHardware(); OperatingSystem os = systemInfo.getOperatingSystem(); environment.jersey().register(new AuthDynamicFeature(userBasicCredentialAuthFilter)); environment.jersey().register(new AuthValueFactoryProvider.Binder(UserConfiguration.class)); SpeedMeasurementManager speedMeasurementManager = new SpeedMeasurementManager(Executors.newScheduledThreadPool(5), Clock.systemUTC(), 5); InfoProvider provider = new InfoProviderFactory(hal, os, SystemInfo.getCurrentPlatformEnum(), config, speedMeasurementManager).provide(); environment.lifecycle().manage(speedMeasurementManager); environment.jersey().register(new SystemResource(provider)); environment.jersey().register(new DiskStoresResource(provider)); environment.jersey().register(new GpuResource(provider)); environment.jersey().register(new MemoryResource(provider)); environment.jersey().register(new NetworkInterfacesResource(provider)); environment.jersey().register(new PowerSourcesResource(provider)); environment.jersey().register(new ProcessesResource(provider)); environment.jersey().register(new CpuResource(provider)); environment.jersey().register(new SensorsResource(provider)); environment.jersey().register(new MotherboardResource(provider)); environment.jersey().register(new MetaInfoResource(getVersionFromManifest(), getEndpoints(environment), os.getProcessId())); }
@Override public void run(PublicApiConfig config, Environment environment) throws Exception { final Client client = RestClientFactory.buildClient(config.getRestClientConfig()); ObjectMapper objectMapper = environment.getObjectMapper(); configureObjectMapper(config, objectMapper); environment.healthChecks().register("ping", new Ping()); environment.jersey().register(new HealthCheckResource(environment)); environment.jersey().register(new PaymentsResource(config.getBaseUrl(), client, config.getConnectorUrl(), config.getConnectorDDUrl(), objectMapper)); environment.jersey().register(new PaymentRefundsResource(config.getBaseUrl(), client, config.getConnectorUrl())); environment.jersey().register(new RequestDeniedResource()); RateLimiter rateLimiter = new RateLimiter(config.getRateLimiterConfig().getRate(), config.getRateLimiterConfig().getPerMillis()); environment.servlets().addFilter("AuthorizationValidationFilter", new AuthorizationValidationFilter(config.getApiKeyHmacSecret())) .addMappingForUrlPatterns(of(REQUEST), true, API_VERSION_PATH + "/*"); environment.servlets().addFilter("RateLimiterFilter", new RateLimiterFilter(rateLimiter, objectMapper)) .addMappingForUrlPatterns(of(REQUEST), true, API_VERSION_PATH + "/*"); environment.servlets().addFilter("LoggingFilter", new LoggingFilter()) .addMappingForUrlPatterns(of(REQUEST), true, API_VERSION_PATH + "/*"); environment.jersey().register(new AuthDynamicFeature( new OAuthCredentialAuthFilter.Builder<Account>() .setAuthenticator(new AccountAuthenticator(client, config.getPublicAuthUrl())) .setPrefix("Bearer") .buildAuthFilter())); environment.jersey().register(new AuthValueFactoryProvider.Binder<>(Account.class)); attachExceptionMappersTo(environment.jersey()); initialiseMetrics(config, environment); }
private void setupAuthentication(ApiServerConfig cfg, Environment env) throws Exception { final Client client = new RestClientBuilder(env, cfg).build(getName()); // Health check for oauth2 server presence final OAuth2HealthCheck healthCheck = new OAuth2HealthCheck(cfg.getOauth2Config(), client); env.healthChecks().register("Oauth2 server", healthCheck); // Setting up the oauth2 authenticator CookieEncrypter cookieEncrypter = new CookieEncrypter(cfg.getOauth2Config().getCookieSecretKey()); boolean https = ((DefaultServerFactory)cfg.getServerFactory()).getApplicationConnectors().get(0) instanceof HttpsConnectorFactory; cookieEncrypter.setSecureFlag(https); OAuth2Authenticator authenticator = new OAuth2Authenticator(cfg.getOauth2Config(), client); // Using cache authenticator CachingAuthenticator<OAuth2Credentials, User> cachingAuthenticator = new CachingAuthenticator<OAuth2Credentials, User>(env.metrics(), authenticator, cfg.getCacheSpec()); final OAuth2AuthFilter<User> oAuth2AuthFilter = new OAuth2AuthFilter.Builder<OAuth2Credentials, User, OAuth2AuthFilter<User>, CachingAuthenticator<OAuth2Credentials, User>>() .setAuthenticator(cachingAuthenticator) .setCookieEncrypter(cookieEncrypter) .build(); env.jersey().register(new AuthDynamicFeature(oAuth2AuthFilter)); env.jersey().register(RolesAllowedDynamicFeature.class); env.jersey().register(new AuthValueFactoryProvider.Binder<User>(User.class)); // Register the oauth2 resource that handles client authentication final OAuth2Resource or = new OAuth2Resource(client, cfg.getOauth2Config(), cookieEncrypter); env.jersey().register(or); }
private void registerBasicAuth(Environment environment, String htusers) { if(isNotBlank(htusers)) { environment.jersey().register(new AuthDynamicFeature( new BasicCredentialAuthFilter.Builder<BasicUserPrincipal>() .setAuthenticator(new HtUserAuthenticator(htusers)) .setRealm("All") .buildAuthFilter())); } }
@Override public void run(T configuration, Environment environment) throws Exception { /* setup the authenticator in front of the requests to allow for pre-auth integration */ // tag::authenticator[] KeycloakJettyAuthenticator keycloak = new KeycloakDropwizardAuthenticator(); keycloak.setAdapterConfig(getKeycloakConfiguration(configuration)); ConstraintSecurityHandler securityHandler = new ConstraintSecurityHandler(); environment.getApplicationContext().setSecurityHandler(securityHandler); environment.getApplicationContext().getSecurityHandler().setAuthenticator(keycloak); // end::authenticator[] // tag::authfactory[] environment.jersey().register(new AuthDynamicFeature( createAuthFactory(configuration))); // To use @RolesAllowed annotations environment.jersey().register(RolesAllowedDynamicFeature.class); // To use @Auth to inject a custom Principal type into your resource environment.jersey().register(new AuthValueFactoryProvider.Binder<>(getUserClass())); // end::authfactory[] if (getKeycloakConfiguration(configuration).isBearerOnly()) { // no session needed } else if (getKeycloakConfiguration(configuration).getTokenStore() != null && getKeycloakConfiguration(configuration).getTokenStore().toLowerCase(Locale.ENGLISH) .equals(TokenStore.COOKIE.toString().toLowerCase(Locale.ENGLISH))) { // no session needed } else { // allow (stateful) sessions in Dropwizard environment.jersey().register(HttpSessionFactory.class); environment.servlets().setSessionHandler(new SessionHandler()); } }
@Override protected void configure() { environment.jersey().register(new AuthDynamicFeature(new GitLabAuthFilter.Builder() .setAuthenticator(new GitLabAuthenticator(configuration.getPassword())) .setUnauthorizedHandler((s, s1) -> Response.status(Response.Status.UNAUTHORIZED).build()) .setRealm("GitLab HOOK") .buildAuthFilter())); environment.jersey().register(RolesAllowedDynamicFeature.class); environment.jersey().register(new AuthValueFactoryProvider.Binder<>(Principal.class)); }
public AuthTestResourceConfig() { super(true, new MetricRegistry()); register(new AuthDynamicFeature(new GitLabAuthFilter.Builder() .setAuthenticator(new GitLabAuthenticator(PASSWORD)) .setUnauthorizedHandler((s, s1) -> Response.status(Response.Status.UNAUTHORIZED).build()) .setRealm("GitLab HOOK") .buildAuthFilter())); register(new AuthValueFactoryProvider.Binder<>(Principal.class)); register(RolesAllowedDynamicFeature.class); register(AuthResource.class); }
@Override public void run(MonradConfiguration config, Environment environment) throws Exception { System.setProperty("spring.profiles.active", config.getProfile()); if (config.getProfile().equals(MonradProfile.PRODUCTION)) { Production.setNeo4jPath(config.getNeo4jPath()); } AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(net.olemartin.spring.Bootstrap.class); Map<String, Object> beans = context.getBeansWithAnnotation(Resource.class); context.getBean(UserService.class).createUser("olemartin", "okki1234", "Ole-Martin"); context.getBean(UserService.class).createUser("selbekk", "scratcharoo", "Kristoffer"); for (Object o : beans.values()) { environment.jersey().register(o); } environment.jersey().register(GsonJSONProvider.class); environment.jersey().setUrlPattern("/rest/*"); environment.jersey().register(new AuthDynamicFeature( new BasicCredentialAuthFilter.Builder<User>() .setAuthenticator(context.getBean(ChessAuthenticator.class)) .setRealm("SUPER SECRET STUFF") .buildAuthFilter())); environment.jersey().register(new AuthValueFactoryProvider.Binder<>(User.class)); ServletRegistration.Dynamic websocket = environment.servlets().addServlet("websocket", context.getBean(ChangeNotification.class)); websocket.setAsyncSupported(true); websocket.addMapping("/push/*"); // CORS support final FilterRegistration.Dynamic cors = environment.servlets().addFilter("CORS", CrossOriginFilter.class); // Configure CORS parameters cors.setInitParameter("allowedOrigins", "*"); // TODO: This probably needs a more strict setting at some point cors.setInitParameter("allowedHeaders", "Authorization,X-Requested-With,Content-Type,Accept,Origin"); cors.setInitParameter("allowedMethods", "OPTIONS,GET,PUT,POST,DELETE,HEAD"); // Add URL mapping cors.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*"); }
private static void setupNullAuth(Environment environment) { environment.jersey().register(new AuthDynamicFeature( new NullAuthFilter.Builder<User>() .setAuthenticator(new NullAuthenticator()) .setRealm("null") .buildAuthFilter())); environment.jersey().register(new AuthValueFactoryProvider.Binder<>(User.class)); }
@Override public void run(Object configuration, Environment environment) throws Exception { environment.jersey().register(OAuth2AccessTokenResource.class); environment.jersey().register(OAuth2AuthorizationRequestFactory.getBinder()); environment.jersey().register(RolesAllowedDynamicFeature.class); environment.jersey().register(new AuthValueFactoryProvider.Binder<>(User.class)); environment.jersey().register(new AuthDynamicFeature( new OAuthCredentialAuthFilter.Builder<User>() .setAuthenticator(new UserAuthenticator(ebeanBundle.getEbeanServer())) .setAuthorizer(new UserAuthorizer()) .setPrefix("Bearer") .buildAuthFilter())); }
@Override public void run(Configuration configuration, Environment environment) throws Exception { mockAuthenticator = mock(Authenticator.class); tenacityAuthenticator = TenacityAuthenticator.wrap(mockAuthenticator, DependencyKey.TENACITY_AUTH_TIMEOUT); environment.jersey().register(new AuthDynamicFeature( new BasicCredentialAuthFilter.Builder<>() .setAuthenticator(tenacityAuthenticator) .setRealm("test-realm") .buildAuthFilter())); environment.jersey().register(tenacityExceptionMapper); environment.jersey().register(tenacityContainerExceptionMapper); environment.jersey().register(new AuthErrorResource()); }
private static void configureAuthentication(Environment environment, JwtVerificationFilter<User> jwtVerificationFilter) { environment.jersey().register(new AuthDynamicFeature(jwtVerificationFilter)); environment.jersey().register(new AuthValueFactoryProvider.Binder<>(User.class)); environment.jersey().register(RolesAllowedDynamicFeature.class); }
@Override public void run(RufusConfiguration conf, Environment env) throws Exception { final DBIFactory factory = new DBIFactory(); final DBI jdbi = factory.build(env, conf.getDataSourceFactory(), DB_SOURCE); final UserDao userDao = jdbi.onDemand(UserDao.class); final ArticleDao articleDao = jdbi.onDemand(ArticleDao.class); final FeedProcessorImpl processor = FeedProcessorImpl.newInstance(articleDao); final FeedParser parser = new FeedParser(articleDao, processor); final JwtConsumer jwtConsumer = new JwtConsumerBuilder() .setAllowedClockSkewInSeconds(30) .setRequireExpirationTime() .setRequireSubject() .setVerificationKey(new HmacKey(VERIFICATION_KEY)) .setRelaxVerificationKeyValidation() .build(); final CachingJwtAuthenticator<User> cachingJwtAuthenticator = new CachingJwtAuthenticator<>( env.metrics(), new JwtAuthenticator(userDao), conf.getAuthenticationCachePolicy() ); env.jersey().register(new ArticleResource(userDao, articleDao, processor, parser)); env.jersey().register( new UserResource( new BasicAuthenticator(userDao), new TokenGenerator(VERIFICATION_KEY), userDao, articleDao ) ); //route source env.jersey().setUrlPattern(ROOT_PATH); env.jersey().register(new AuthValueFactoryProvider.Binder<>(User.class)); env.jersey().register(new AuthDynamicFeature( new JwtAuthFilter.Builder<User>() .setJwtConsumer(jwtConsumer) .setRealm(REALM) .setPrefix(BEARER) .setAuthenticator(cachingJwtAuthenticator) .buildAuthFilter() )); }
@Override public void run(EyeballsConfiguration eyeballsConfiguration, Environment environment) throws Exception { Security.addProvider(new BouncyCastleProvider()); createUnderylingStorageDirectories(eyeballsConfiguration); if (eyeballsConfiguration.getUseAuth()) { environment.jersey().register(new AuthDynamicFeature( new BasicCredentialAuthFilter.Builder<BasicAuthenticator.EyeballUser>() .setAuthenticator(new BasicAuthenticator(eyeballsConfiguration)) .setRealm("Eyeballs Motion Detection Server") .buildAuthFilter())); } DB db = buildMapDb(eyeballsConfiguration); BTreeMap<String, MotionEvent> motionEventStore = db.createTreeMap("motionEventStore") .valueSerializer(new LocalEventSerializer()) .makeOrGet(); Webcam webcam = Webcam.getDefault(); if (webcam == null) { throw new RuntimeException("No webcam present, or not available to the current user."); } PictureTakingService pictureTakingService = new PictureTakingService(webcam); webcam.addWebcamListener(pictureTakingService); Dimension[] dimensions = (Dimension[]) Arrays.stream(WebcamResolution.values()) .map(WebcamResolution::getSize) .collect(Collectors.toList()) .toArray(); webcam.setCustomViewSizes(dimensions); webcam.setViewSize(new Dimension(eyeballsConfiguration.getImageWidth(), eyeballsConfiguration.getImageHeight())); webcam.open(); MotionEventProcessor.Builder processorBuilder = new MotionEventProcessor.Builder(); if (eyeballsConfiguration.getUseSftp()) { processorBuilder.addMotionEventConsumer(new SftpMotionEventConsumer(eyeballsConfiguration)); } if (eyeballsConfiguration.getUseDropbox()) { processorBuilder.addMotionEventConsumer(new DropboxMotionEventConsumer(eyeballsConfiguration)); } if (eyeballsConfiguration.getUseLocalPersistence()) { LocalFSMotionEventConsumer localFSMotionEventConsumer = new LocalFSMotionEventConsumer(db, eyeballsConfiguration, motionEventStore); processorBuilder.addMotionEventConsumer(localFSMotionEventConsumer); processorBuilder.motionEventPersitence(localFSMotionEventConsumer); } if (eyeballsConfiguration.getUseDropboxPersistence()) { processorBuilder.motionEventPersitence(new DropBoxMotionEventPersistence(eyeballsConfiguration, motionEventStore)); } processorBuilder.motionEventStore(motionEventStore); MotionEventProcessor motionEventProcessor = processorBuilder.build(); MotionDetectionService motionDetectionService = new MotionDetectionService(eyeballsConfiguration, new SaveMotionDetectedListener(motionEventProcessor, eyeballsConfiguration)); motionDetectionService.startAndWait(); EyeballsResource eyeballsResource = new EyeballsResource(webcam, motionEventProcessor, pictureTakingService); environment.jersey().register(eyeballsResource); }
@Override public void run(MqttHttpConfiguration configuration, Environment environment) throws Exception { // validator logger.debug("Initializing validator ..."); Validator validator = new Validator(configuration); // storage SyncStorage storage = (SyncStorage) Class.forName(storageConfig.getString("storage.sync.class")).newInstance(); environment.lifecycle().manage(new Managed() { @Override public void start() throws Exception { logger.debug("Initializing storage storage ..."); storage.init(storageConfig); } @Override public void stop() throws Exception { logger.debug("Destroying storage storage ..."); storage.destroy(); } }); // authenticator Authenticator authenticator = (Authenticator) Class.forName(authenticatorConfig.getString("authenticator.class")).newInstance(); environment.lifecycle().manage(new Managed() { @Override public void start() throws Exception { logger.debug("Initializing authenticator ..."); authenticator.init(authenticatorConfig); } @Override public void stop() throws Exception { logger.debug("Destroying authenticator ..."); authenticator.destroy(); } }); // cluster Cluster cluster = (Cluster) Class.forName(clusterConfig.getString("cluster.class")).newInstance(); environment.lifecycle().manage(new Managed() { @Override public void start() throws Exception { logger.debug("Initializing cluster ..."); cluster.init(clusterConfig, null); } @Override public void stop() throws Exception { logger.debug("Destroying cluster ..."); cluster.destroy(); } }); // OAuth environment.jersey().register(new AuthDynamicFeature( new OAuthCredentialAuthFilter.Builder<UserPrincipal>() .setAuthenticator(new OAuthAuthenticator(authenticator)) .setAuthorizer(new PermitAllAuthorizer<>()) .setPrefix("Bearer") .buildAuthFilter())); environment.jersey().register(RolesAllowedDynamicFeature.class); environment.jersey().register(new AuthValueFactoryProvider.Binder<>(UserPrincipal.class)); // register resources environment.jersey().register(new MqttPublishResource(configuration.getServerId(), validator, storage, cluster, authenticator)); environment.jersey().register(new MqttSubscribeResource(configuration.getServerId(), validator, storage, cluster, authenticator)); environment.jersey().register(new MqttUnsubscribeResource(configuration.getServerId(), validator, storage, cluster, authenticator)); // config jackson environment.getObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); environment.getObjectMapper().configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); environment.getObjectMapper().configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false); environment.getObjectMapper().setSerializationInclusion(JsonInclude.Include.NON_NULL); }
@Override public void run(AppConfiguration configuration, Environment environment) { // password encoder final PasswordEncoder passwordEncoder = new PasswordEncoder(); // DAO final CategoryDAO categoryDAO = new CategoryDAO(hibernate.getSessionFactory(), configuration); final BudgetDAO budgetDAO = new BudgetDAO(hibernate.getSessionFactory(), configuration); final BudgetTypeDAO budgetTypeDAO = new BudgetTypeDAO(hibernate.getSessionFactory()); final UserDAO userDAO = new UserDAO(hibernate.getSessionFactory()); final TransactionDAO transactionDAO = new TransactionDAO(hibernate.getSessionFactory()); final RecurringDAO recurringDAO = new RecurringDAO(hibernate.getSessionFactory()); final AuthTokenDAO authTokenDAO = new AuthTokenDAO(hibernate.getSessionFactory()); // service final FinanceService financeService = new FinanceService(userDAO, budgetDAO, budgetTypeDAO, categoryDAO, transactionDAO, recurringDAO, authTokenDAO, passwordEncoder); // jobs final RecurringJob recurringJob = new UnitOfWorkAwareProxyFactory(hibernate).create(RecurringJob.class, FinanceService.class, financeService); // resource environment.jersey().register(new UserResource(financeService)); environment.jersey().register(new CategoryResource(financeService)); environment.jersey().register(new BudgetResource(financeService)); environment.jersey().register(new TransactionResource(financeService)); environment.jersey().register(new RecurringResource(financeService)); environment.jersey().register(new ReportResource(financeService)); // health check environment.jersey().register(new HealthCheckResource(environment.healthChecks())); // managed environment.lifecycle().manage(new MigrationManaged(configuration)); environment.lifecycle().manage(new JobsManaged(recurringJob)); // auth TokenAuthenticator tokenAuthenticator = new UnitOfWorkAwareProxyFactory(hibernate).create(TokenAuthenticator.class, FinanceService.class, financeService); final OAuthCredentialAuthFilter<User> authFilter = new OAuthCredentialAuthFilter.Builder<User>() .setAuthenticator(tokenAuthenticator) .setPrefix("Bearer") .setAuthorizer(new DefaultAuthorizer()) .setUnauthorizedHandler(new DefaultUnauthorizedHandler()) .buildAuthFilter(); environment.jersey().register(RolesAllowedDynamicFeature.class); environment.jersey().register(new AuthDynamicFeature(authFilter)); environment.jersey().register(new AuthValueFactoryProvider.Binder(User.class)); // filters FilterRegistration.Dynamic urlRewriteFilter = environment.servlets().addFilter("rewriteFilter", UrlRewriteFilter.class); urlRewriteFilter.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD), false, "/*"); urlRewriteFilter.setInitParameter("confPath", "urlrewrite.xml"); // only enable for dev // FilterRegistration.Dynamic filterSlow = environment.servlets().addFilter("slowFilter", SlowNetworkFilter.class); // filterSlow.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD), false, "/*"); // exception mapper environment.jersey().register(new NotFoundExceptionMapper()); environment.jersey().register(new DataConstraintExceptionMapper()); environment.jersey().register(new ConstraintViolationExceptionMapper()); environment.jersey().register(new SQLConstraintViolationExceptionMapper()); }