/** * * @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)); }
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 AuthFilter<?, Principal> createAuthFilter(AuthenticationBootstrap bootstrap) { return new BasicCredentialAuthFilter.Builder<>() .setAuthenticator(new BasicAuthenticator(bootstrap.getUserDAO())) .setAuthorizer(new PermitAllAuthorizer()) .setRealm(realm) .buildAuthFilter(); }
@Override public AuthFilter<?, Principal> createAuthFilter(AuthenticationBootstrap bootstrap) { return new BasicCredentialAuthFilter.Builder<>() .setAuthenticator(new SpecificUsernamePwAuthenticator(username, password)) .setAuthorizer(new PermitAllAuthorizer()) .buildAuthFilter(); }
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 filter(ContainerRequestContext requestContext) throws IOException { RegisterContext registerContext = registerContextProvider.get(); BasicCredentialAuthFilter<RegisterAuthenticator.User> delegateFilter = new BasicCredentialAuthFilter.Builder<RegisterAuthenticator.User>() .setAuthenticator(registerContext.getAuthenticator()) .buildAuthFilter(); delegateFilter.filter(requestContext); }
@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())); }
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(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, "/*"); }
@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()); }
@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(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); }