@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" + "/*"); }
@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()); } }
public static Optional<List<AuthFilter>> getAuthFilters(final TrellisConfiguration config) { // Authentication final List<AuthFilter> filters = new ArrayList<>(); final AuthConfiguration auth = config.getAuth(); if (auth.getJwt().getEnabled()) { filters.add(new OAuthCredentialAuthFilter.Builder<Principal>() .setAuthenticator(new JwtAuthenticator(auth.getJwt().getKey(), auth.getJwt().getBase64Encoded())) .setPrefix("Bearer") .buildAuthFilter()); } if (auth.getBasic().getEnabled()) { filters.add(new BasicCredentialAuthFilter.Builder<Principal>() .setAuthenticator(new BasicAuthenticator(auth.getBasic().getUsersFile())) .setRealm("Trellis Basic Authentication") .buildAuthFilter()); } if (auth.getAnon().getEnabled()) { filters.add(new AnonymousAuthFilter.Builder() .setAuthenticator(new AnonymousAuthenticator()) .buildAuthFilter()); } if (filters.isEmpty()) { return empty(); } return of(filters); }
@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(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); }
@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(ServerConfiguration configuration, Environment environment) throws Exception { final DBIFactory factory = new DBIFactory(); final DBI jdbi = factory.build(environment, configuration.getDataSourceFactory(), "sapData"); ObjectMapper objectMapper = environment.getObjectMapper(); SapConfiguration sapConfiguration = configuration.getSapConfig(); JobConfiguration jobConfiguration = configuration.getJobConfig(); NiPingServiceBinder niPingServiceBinder = new NiPingServiceBinder(jdbi, objectMapper, sapConfiguration, jobConfiguration); ServiceLocator serviceLocator = ServiceLocatorUtilities.bind(niPingServiceBinder); SapBasicAuthenticator sapBasicAuthenticator = ServiceLocatorUtilities.getService(serviceLocator, SapBasicAuthenticator.class .getName()); SapOAuthenticator sapOAuthenticator = ServiceLocatorUtilities.getService(serviceLocator, SapOAuthenticator.class.getName()); final BasicCredentialAuthFilter basicAuthFilter = new BasicCredentialAuthFilter.Builder<BasicAuthUser>() .setAuthenticator(sapBasicAuthenticator) .buildAuthFilter(); final AuthFilter oAuthFilter = new OAuthCredentialAuthFilter.Builder<OAuthUser>() .setAuthenticator(sapOAuthenticator) .setPrefix("Bearer") .buildAuthFilter(); final PolymorphicAuthDynamicFeature feature = new PolymorphicAuthDynamicFeature<UserPrincipal>(ImmutableMap.of(BasicAuthUser .class, basicAuthFilter, OAuthUser.class, oAuthFilter)); final AbstractBinder binder = new PolymorphicAuthValueFactoryProvider.Binder<>(ImmutableSet.of(BasicAuthUser.class, OAuthUser .class)); environment.jersey().register(new AuthFilterDynamicBinding()); environment.jersey().register(feature); environment.jersey().register(binder); environment.jersey().register(niPingServiceBinder); environment.jersey().packages("com.cloudwise.sap.niping.auth"); environment.jersey().packages("com.cloudwise.sap.niping.service"); environment.jersey().packages("com.cloudwise.sap.niping.dao"); environment.jersey().packages("com.cloudwise.sap.niping.common.vo.converter"); environment.jersey().packages("com.cloudwise.sap.niping.resource"); environment.jersey().register(SessionFactoryProvider.class); environment.servlets().setSessionHandler(new SessionHandler()); }
@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()); }