@Override public void addToJerseyConfig(JerseyConfig jerseyConfig) { jerseyConfig.addBinder(binder -> { binder.bind(this).to(UserTokenFilterAddon.class); binder.bindFactory(UibBrukerInjectionFactory.class).to(UibBruker.class); } ); jerseyConfig.addRegistations(registrator -> registrator .register(RolesAllowedDynamicFeature.class) .register(UserTokenFilter.class) .register(UserTokenBlockingFilter.class) ); if (swaggerImplicitHeaders) { SwaggerExtensions.getExtensions().add(new SwaggerImplicitUserTokenHeader(requireUserTokenByDefault)); } }
@Override public boolean configure(FeatureContext context) { final Configuration configuration = context.getConfiguration(); Boolean disabled = PropertyHelper.getProperty(configuration, RestServerV2.DAC_AUTH_FILTER_DISABLE); // Default is not disabled if (disabled != null && disabled) { return false; } context.register(DACAuthFilter.class); if (!configuration.isRegistered(RolesAllowedDynamicFeature.class)) { context.register(RolesAllowedDynamicFeature.class); } return true; }
@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)); }
/** * Constructor where the magic happens. */ public ALEXApplication() { // REST Resources register(CounterResource.class); register(FileResource.class); register(LearnerResource.class); register(LearnerResultResource.class); register(ProjectResource.class); register(SettingsResource.class); register(SymbolGroupResource.class); register(SymbolResource.class); register(UserResource.class); register(TestResource.class); // Exceptions register(NotFoundExceptionMapper.class); // Other register(MultiPartFeature.class); register(AuthenticationFilter.class); register(RolesAllowedDynamicFeature.class); // allow protecting routes with user roles register(JacksonConfiguration.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)); }
public OntoSoftServer() { // Headers register(AcceptHeaderFilter.class); register(CORSResponseFilter.class); // User roles and authentication register(RolesAllowedDynamicFeature.class); register(UserAuthenticationFilter.class); // Main Resources register(UserResource.class); register(SoftwareResource.class); // OpenAPI documentation register(ApiListingResource.class); register(SwaggerSerializers.class); initializeSwagger(); }
@Override public void run(LotteryConfiguration configuration, Environment environment) throws ClassNotFoundException, IOException { // tag::keycloak[] KeycloakDeployment keycloakDeployment = KeycloakDeploymentBuilder.build(configuration.getKeycloakConfiguration()); JaxrsBearerTokenFilterImpl filter = new DropwizardBearerTokenFilterImpl(keycloakDeployment); environment.jersey().register(filter); // end::keycloak[] environment.jersey().register(new DrawRessource()); // support annotation @RolesAllowed // tag::roles[] environment.jersey().register(RolesAllowedDynamicFeature.class); // end::roles[] }
@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()); } }
@Override public void init(Application<? extends ApplicationConfiguration> application) { ApplicationConfiguration applicationConfiguration = application.getConfiguration(); if (! (applicationConfiguration instanceof SecurityAware)) { return; } SecurityConfiguration configuration = ((SecurityAware) applicationConfiguration).getSecurityConfiguration(); clients.init(); CallbackFilter callbackFilter = new CallbackFilter(clients, configuration); callbackFilter.registerListener(listener); application.addFilter(callbackFilter); application.addFilter(new AuthenticationFilter(clients, configuration)); application.addFilter(new SecurityContextFilter(configuration)); application.getResourceConfig().register(RolesAllowedDynamicFeature.class); }
@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 customize(ResourceConfig config) { // Realm ContextResolver config.register(new ContextResolver<Realm>() { @Override public Realm getContext(Class<?> type) { return realm; } }); // Authentication config.register(AuthenticationFeature.class); // Authorization config.register(RolesAllowedDynamicFeature.class); }
@Override protected Application configure() { final AccountProvider provider = id -> { Account account = null; if ("a1".equals(id)) { account = Account.builder(id).credentials(Credentials.builder().secret("p1").build()).enabled(true) .permission("R1").permission("R2").build(); } else if ("a2".equals(id)) { account = Account.builder(id).credentials(Credentials.builder().secret("p2").build()).enabled(true) .permission("R1").permission("R3").build(); } return Optional.ofNullable(account); }; final Realm realm = Realm.builder().resolver(AuthenticationToken.httpBasicResolver()) .authenticator(Account.authenticator(provider)).withDefaultAuthorizer().build(); return new ResourceConfig() .register(RolesAllowedDynamicFeature.class) .register(new ContextResolver<Realm>() { @Override public Realm getContext(Class<?> type) { return realm; } }).register(ProtectedResource.class).register(SemiProtectedResource.class) .register(PublicResource.class); }
@Override protected Application configure() { final AccountProvider provider = id -> { Account account = null; if ("a1".equals(id)) { account = Account.builder(id).credentials(Credentials.builder().secret("p1").build()).enabled(true) .permission("R1").permission("R2").build(); } else if ("a2".equals(id)) { account = Account.builder(id).credentials(Credentials.builder().secret("p2").build()).enabled(true) .permission("R1").permission("R3").build(); } return Optional.ofNullable(account); }; final Realm realm = Realm.builder().resolver(AuthenticationToken.httpBasicResolver()) .authenticator(Account.authenticator(provider)).withDefaultAuthorizer().build(); return new ResourceConfig()// .register(AuthenticationFeature.class) // using auto-config .register(RolesAllowedDynamicFeature.class).register(new ContextResolver<Realm>() { @Override public Realm getContext(Class<?> type) { return realm; } }).register(ProtectedResource.class).register(SemiProtectedResource.class) .register(PublicResource.class); }
/** * Starts Grizzly HTTP server exposing JAX-RS resources defined in this application. * @return Grizzly HTTP server. */ public static HttpServer startServer(int port) { HashMap properties = new HashMap(); bridgeLog(); // create a resource config that scans for JAX-RS resources and providers // in io.github.javathought.devoxx package final ResourceConfig rc = new ResourceConfig().packages("io.github.javathought.devoxx", "org.glassfish.jersey.examples.jackson"); rc.register(SecurityFilter.class); rc.register(CrossDomainFilter.class); rc.register(SelectableEntityFilteringFeature.class); rc.property(SelectableEntityFilteringFeature.QUERY_PARAM_NAME, "select"); rc.register(JacksonFeature.class); rc.register(RolesAllowedDynamicFeature.class); rc.register(CsrfProtectionFilter.class); rc.register(ApiListingResource.class); rc.register(SwaggerSerializers.class); BeanConfig beanConfig = new BeanConfig(); beanConfig.setVersion("1.0"); beanConfig.setSchemes(new String[]{"http"}); beanConfig.setHost("localhost:8084"); beanConfig.setBasePath("/myapp"); beanConfig.setResourcePackage("io.github.javathought.devoxx.resources"); beanConfig.setPrettyPrint(true); beanConfig.setScan(true); // create and start a new instance of grizzly http server // exposing the Jersey application at BASE_URI return GrizzlyHttpServerFactory.createHttpServer(URI.create(getBaseUri(port)), rc); }
public JerseyConfig() { // register api endpoint register(Hello.class); register(User.class); register(Snippet.class); register(Language.class); //allow to use RolesAllowed annotation register(RolesAllowedDynamicFeature.class); //register mapper // user mapper register(SecurityManager.class); register(AuthenticationMapper.class); register(ForbiddenMapper.class); register(NotAuthorizedMapper.class); // generic mapper register(ExceptMapper.class); register(NotFoundMapper.class); register(NotSupportedMapper.class); register(EntityExistsMapper.class); register(EntityNotFoundMapper.class); register(NotAllowedMapper.class); register(BadRequestMapper.class); register(IllegalArgumentMapper.class); //register request and response filter register(AuthorizationRequestFilter.class); register(TokenResponseFilter.class); }
@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 protected Application configure() { return new ResourceConfig(MockServer.class) .register(RolesAllowedDynamicFeature.class) .register(new MockSecurityFilter(), Priorities.AUTHENTICATION) .register(JerseyClient.createMoxyJsonResolver()); }
public Application() { System.setProperty(JAXBContext.JAXB_CONTEXT_FACTORY, "org.eclipse.persistence.jaxb.JAXBContextFactory"); packages("de.usu.research.hobbit.gui.rest", "de.usu.research.hobbit.gui.rest.securedexamples"); // enable security-annotations, see // https://jersey.java.net/documentation/latest/security.html#annotation-based-security register(RolesAllowedDynamicFeature.class); properties = readProperties(); if (isUsingDevDb()) { LOGGER.info("Using in-memory database for GUI development"); } }
@Override protected Application configure() { return new ResourceConfig(MockServer.class) .register(RolesAllowedDynamicFeature.class) .register(new MockSecurityFilter(), Priorities.AUTHENTICATION) .register(JerseyClient.createMoxyJsonResolver()) .register(GZipEncoder.class) .register(EncodingFilter.class); }
@BeforeEach public void setup() { testService = mock(ArticleService.class); Binder binder = new InstanceBinder.Builder().addInstance(testService, ArticleService.class).build(); container = new JRestlessHandlerContainer<JRestlessContainerRequest>( new ResourceConfig().register(TestResource.class).register(binder).register(RolesAllowedDynamicFeature.class)); container.onStartup(); }
private void startServer() throws IOException { // create a resource config that scans for JAX-RS resources and // providers // in com.datarpm.api package ResourceConfig rc = new ResourceConfig(); Set<String> packagesToScan = new HashSet<>(); packagesToScan.add("com.datarpm.event.server.rest"); rc.packages(packagesToScan.toArray(new String[packagesToScan.size()])); rc.register(GsonMessageBodyHandler.class); rc.register(RolesAllowedDynamicFeature.class); if (authEnabled) rc.register(APIGatewayAuthorizationFilter.class); initializeService(); // create and start a new instance of grizzly http server // exposing the Jersey application at BASE_URI final HttpServer httpServer = GrizzlyHttpServerFactory .createHttpServer(URI.create(serverAccessURL), rc); Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { @Override public void run() { httpServer.shutdownNow(); } }, "Server-Showdown-Thread")); registerWebsocket(); }
public TriggerResourceConfig() { register(RestTriggerResource.class); register(GsonMessageProvider.class); register(VersionFilter.class); register(SecurityFilter.class); register(RolesAllowedDynamicFeature.class); }
private void registerFeatures() { packages("de.learnlib.alex.common.exceptions"); register(MultiPartFeature.class); register(RolesAllowedDynamicFeature.class); // allow protecting routes with user roles register(AuthenticationFilter.class); register(JacksonConfiguration.class); }
public AntiochApplication() { LOG.info("initializing AntiochApplication..."); packages("nl.knaw.huygens.antioch.endpoint", "nl.knaw.huygens.antioch.jersey"); // Bean Validation error messages in the response entity. property(ServerProperties.BV_SEND_ERROR_IN_RESPONSE, true); // Server-side request logging, including entities register(new LoggingFilter(getAnonymousLogger(), true)); // Authentication and Authorization register(AuthenticationRequestFilter.class); register(AuthorizationRequestFilter.class); register(RolesAllowedDynamicFeature.class); register(CORSFilter.class); // Validation configuration register(ValidationConfigurationContextResolver.class); // JSON configuration register(JsonConfiguration.class); // // X-Jersey-Tracing-nnn diagnostic response headers // property(ServerProperties.TRACING, "ALL"); // disable output buffering: no automatic Content-Length header. // property(ServerProperties.OUTBOUND_CONTENT_LENGTH_BUFFER, 0); System.setProperty(AntiochApplication.START_TIME_PROPERTY, Instant.now().toString()); }
@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())); }
public Application(final BookDao bookDao, final UserDao userDao, final Key key) { this.setBookDao(bookDao); this.setUserDao(userDao); this.setKey(key); // Validation. // register(ValidationConfigurationContextResolver.class); // logging register(LoggingFilter.class); // roles security register(RolesAllowedDynamicFeature.class); // jwt filter register(JWTSecurityFilter.class); // turn on Jackson, Moxy isn't that good of a solution. register(JacksonFeature.class); packages("com.sample"); register(new AbstractBinder() { @Override protected void configure() { bind(getBookDao()).to(BookDao.class); bind(getUserDao()).to(UserDao.class); bind(getKey()).to(Key.class); } }); property("jersey.config.beanValidation.enableOutputValidationErrorEntity.server", "true"); property(ServerProperties.BV_SEND_ERROR_IN_RESPONSE, true); }
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 ResourceConfig getResourceConfig(Application application) { ResourceConfig resourceConfig = ResourceConfig.forApplication(application); resourceConfig.register(JacksonFeature.class); resourceConfig.register(RolesAllowedDynamicFeature.class); applicationCustomizers.forEach(c -> c.customize(resourceConfig)); Map<String, Object> props = new HashMap<>(resourceConfig.getProperties()); props.put(ServletProperties.FILTER_FORWARD_ON_404, "true"); resourceConfig.setProperties(props); return resourceConfig; }
@Test public void testThatApplicationRegistersUserAuth() { // Exercise userInfoApplication.registerUserAuth(configuration, environment); // Verify verify(jerseyEnvironment, times(2)).register(any(Object.class)); verify(jerseyEnvironment).register(RolesAllowedDynamicFeature.class); }
@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 public void run(LotteryConfiguration configuration, Environment environment) throws ClassNotFoundException, IOException { // register web resources. environment.jersey().register(new DrawRessource()); // support annotation @RolesAllowed environment.jersey().register(RolesAllowedDynamicFeature.class); }
@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); }
public WhereResourceConfig() { packages("edu.upc.eetac.dsa.group7"); packages("edu.upc.eetac.dsa.group7.auth"); register(RolesAllowedDynamicFeature.class); register(DeclarativeLinkingFeature.class); packages("edu.upc.eetac.dsa.where.cors"); register(JacksonFeature.class); }
public ApiConfig(@Context ServletContext servletContext){ final String outerPath = servletContext.getRealPath(""); System.out.println(outerPath); JavaIOConfig.setReader(new Reader() { @Override public InputStream getContent(String path) throws IOException { return new FileInputStream(outerPath + File.separator + "WEB-INF" + File.separator + "classes" + File.separator + path); } }); packages("rtdc.web.server.servlet;rtdc.web.server.filter"); register(RolesAllowedDynamicFeature.class); register(new AbstractBinder() { @Override protected void configure() { bindFactory(UserFactory.class).to(User.class); bindFactory(AuthTokenFactory.class).to(AuthenticationToken.class); } }); LOGGER.info("API Config loaded."); }
public AbstractAuthResourceConfig() { super(true, new MetricRegistry()); register(new AuthDynamicFeature(getAuthFilter())); register(new AuthValueFactoryProvider.Binder<>(getPrincipalClass())); register(RolesAllowedDynamicFeature.class); }