@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)); }
@SuppressWarnings("unchecked") public ChainedAuthTestResourceConfig() { super(true, new MetricRegistry()); final Authorizer<Principal> authorizer = AuthUtil.getTestAuthorizer(ADMIN_USER, ADMIN_ROLE); final AuthFilter<BasicCredentials, Principal> basicAuthFilter = new BasicCredentialAuthFilter.Builder<>() .setAuthenticator(AuthUtil.getBasicAuthenticator(ImmutableList.of(ADMIN_USER, ORDINARY_USER))) .setAuthorizer(authorizer) .buildAuthFilter(); final AuthFilter<String, Principal> oAuthFilter = new OAuthCredentialAuthFilter.Builder<>() .setAuthenticator(AuthUtil.getSingleUserOAuthAuthenticator(BEARER_USER, ADMIN_USER)) .setPrefix(BEARER_PREFIX) .setAuthorizer(authorizer) .buildAuthFilter(); register(new AuthValueFactoryProvider.Binder(Principal.class)); register(new AuthDynamicFeature(new ChainedAuthFilter<>(buildHandlerList(basicAuthFilter, oAuthFilter)))); register(RolesAllowedDynamicFeature.class); register(AuthResource.class); }
@Override public void run(HelloWorldConfiguration configuration, Environment environment) { final PersonDAO dao = new PersonDAO(hibernateBundle.getSessionFactory()); final Template template = configuration.buildTemplate(); environment.healthChecks().register("template", new TemplateHealthCheck(template)); environment.jersey().register(DateRequiredFeature.class); environment.jersey().register(new AuthDynamicFeature(new BasicCredentialAuthFilter.Builder<User>() .setAuthenticator(new ExampleAuthenticator()) .setAuthorizer(new ExampleAuthorizer()) .setRealm("SUPER SECRET STUFF") .buildAuthFilter())); environment.jersey().register(new AuthValueFactoryProvider.Binder<>(User.class)); environment.jersey().register(RolesAllowedDynamicFeature.class); environment.jersey().register(new HelloWorldResource(template)); environment.jersey().register(new ViewResource()); environment.jersey().register(new ProtectedResource()); environment.jersey().register(new PeopleResource(dao)); environment.jersey().register(new PersonResource(dao)); environment.jersey().register(new FilteredResource()); }
@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(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); }
@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, "/*"); }
public AbstractAuthResourceConfig() { super(true, new MetricRegistry()); register(new AuthDynamicFeature(getAuthFilter())); register(new AuthValueFactoryProvider.Binder<>(getPrincipalClass())); register(RolesAllowedDynamicFeature.class); }
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())); }
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(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()); }