@Override public void run(@Nonnull final GraphiakConfiguration configuration, @Nonnull final Environment environment) throws Exception { // Enable CORS final FilterRegistration.Dynamic cors = environment.servlets() .addFilter("cors", CrossOriginFilter.class); cors.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*"); // get Riak client final RiakClient client = configuration.getRiak().build(); final MetricStore store = new MetricStore(client); environment.lifecycle().manage(new MetricStoreManager(store)); // Configure the Netty TCP server configuration.getNetty().build(environment, store); // Resources environment.jersey().register(new DashboardResource()); environment.jersey().register(new MetricsResource(store)); environment.jersey().register(new EventsResource()); environment.jersey().register(new PingResource()); environment.jersey().register(new VersionResource()); }
@Override public void run(BlogConfiguration blogConfiguration, Environment environment) throws Exception { final BlogDao blogDao = new BlogDao(hibernate.getSessionFactory()); // Register all resources here. environment.jersey().register(new BlogResources(blogDao)); environment.jersey().register(new UploadResources()); environment.jersey().register(new UnitTestResources()); // Register MultiPartFeature.class to support mime type "multipart/form-data." environment.jersey().getResourceConfig().register(MultiPartFeature.class); // All Filter // CORS enable Dynamic filter = environment.servlets().addFilter("CORS", CrossOriginFilter.class); filter.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), false, "/*"); filter.setInitParameter(CrossOriginFilter.ALLOWED_METHODS_PARAM, "GET,PUT,POST,DELETE,OPTIONS"); filter.setInitParameter(CrossOriginFilter.ALLOWED_ORIGINS_PARAM, "*"); filter.setInitParameter(CrossOriginFilter.ACCESS_CONTROL_ALLOW_ORIGIN_HEADER, "*"); filter.setInitParameter("allowedHeaders", "Content-Type,Authorization,X-Requested-With,Content-Length,Accept,Origin"); filter.setInitParameter("allowCredentials", "true"); }
@Override public void run(HelloWorldConfiguration configuration, Environment environment) throws Exception { // Enable CORS to allow GraphiQL on a separate port to reach the API final FilterRegistration.Dynamic cors = environment.servlets() .addFilter("cors", CrossOriginFilter.class); cors.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*"); final HelloWorldResource resource = new HelloWorldResource( configuration.getTemplate(), configuration.getDefaultName()); environment.jersey().register(resource); }
@Override public void run(AppConfiguration configuration, Environment environment) throws Exception { /* Configure WebSockets */ ServerEndpointConfig serverEndpointConfig = ServerEndpointConfig.Builder.create(WebCrawlerEndpoint.class, "/webCrawler").build(); serverEndpointConfig.getUserProperties().put("config", configuration.webCrawler); websocketBundle.addEndpoint(serverEndpointConfig); final FilterRegistration.Dynamic cors = environment.servlets().addFilter("CORS", CrossOriginFilter.class); /* Configure CORS parameters */ cors.setInitParameter("allowedOrigins", "*"); cors.setInitParameter("allowedHeaders", "*"); cors.setInitParameter("allowedMethods", "OPTIONS,GET,PUT,POST,DELETE,HEAD"); cors.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*"); environment.healthChecks().register("dummy", new DummyHealthCheck()); }
@Override public void run(AppConfiguration configuration, Environment environment) throws Exception { SessionFactory sessionFactory = hibernate.getSessionFactory(); MemoDAO memoDAO = new MemoDAO(sessionFactory); ConnectionFactory connectionFactory = QueueHelper.getQueue(configuration.getQueueConfig()); environment.healthChecks().register("RabbitMQHealthCheck", new QueueHealthCheck(connectionFactory)); environment.jersey().register(new MemoResource(configuration.getQueueConfig(), memoDAO)); // CORS Settings to allow cross origin requests FilterRegistration.Dynamic filter = environment.servlets().addFilter("CORS", CrossOriginFilter.class); filter.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*"); filter.setInitParameter(CrossOriginFilter.ALLOWED_METHODS_PARAM, "GET,PUT,POST,DELETE,OPTIONS"); filter.setInitParameter(CrossOriginFilter.ALLOWED_ORIGINS_PARAM, "*"); filter.setInitParameter(CrossOriginFilter.ACCESS_CONTROL_ALLOW_ORIGIN_HEADER, "*"); filter.setInitParameter("allowedHeaders", "Content-Type,Authorization,X-Requested-With,Content-Length,Accept,Origin"); filter.setInitParameter("allowCredentials", "true"); }
@Test public void testCrossOriginFilterAddedWhenOn() throws Exception { // setup CometdComponent component = context.getComponent("cometd", CometdComponent.class); Server server = new Server(); when(endpoint.isCrossOriginFilterOn()).thenReturn(true); when(endpoint.getFilterPath()).thenReturn(FILTER_PATH); when(endpoint.getAllowedOrigins()).thenReturn(ALLOWED_ORIGINS); // act component.createServletForConnector(server, connector, endpoint); // assert ServletContextHandler handler = (ServletContextHandler) server.getHandler(); assertEquals(1, handler.getServletHandler().getFilters().length); FilterHolder filterHolder = handler.getServletHandler().getFilters()[0]; Filter filter = filterHolder.getFilter(); assertTrue(filter instanceof CrossOriginFilter); }
public int run() throws Exception { org.eclipse.jetty.server.Server server = new org.eclipse.jetty.server.Server(port); HandlerList handlerList = new HandlerList(); ServletContextHandler servletContextHandler = new ServletContextHandler(); FilterHolder cof = new FilterHolder(new CrossOriginFilter()); cof.setInitParameter( CrossOriginFilter.EXPOSED_HEADERS_PARAM, "Date"); servletContextHandler.addFilter(cof, "/*", EnumSet.of(DispatcherType.INCLUDE, DispatcherType.REQUEST)); servletContextHandler.addServlet(new ServletHolder(new SmoothStreamingServlet(dataDir)), "/*"); ResourceHandler resourceHandler = new ResourceHandler(); resourceHandler.setBaseResource(Resource.newClassPathResource("supportfiles")); handlerList.addHandler(resourceHandler); handlerList.addHandler(servletContextHandler); server.setHandler(handlerList); server.start(); server.dumpStdErr(); server.join(); return 0; }
/** * Initializes the Jersey Servlet. */ private void initJerseyServlet() { servletContext = new ServletContextHandler(ServletContextHandler.SESSIONS); servletContext.setContextPath("/"); // This is used for allowing access to different domains/ports. FilterHolder filterHolder = new FilterHolder(CrossOriginFilter.class); filterHolder.setInitParameter("allowedOrigins", "*"); filterHolder.setInitParameter("allowedMethods", "GET, POST"); servletContext.addFilter(filterHolder, "/*", null); jerseyServlet = servletContext.addServlet(org.glassfish.jersey.servlet.ServletContainer.class, "/*"); jerseyServlet.setInitOrder(0); // Tell the Jersey Servlet which REST class to load. jerseyServlet.setInitParameter("jersey.config.server.provider.classnames", ProvisioningAction.class.getCanonicalName()); }
@Provides(type = Type.SET) ContextConfigurator provideCrossOriginFilter(final Configuration conf) { return new ContextConfigurator() { @Override public void init(ServletContextHandler context) { FilterHolder crossOriginFilter = new FilterHolder(CrossOriginFilter.class); Map<String, String> params = new HashMap<>(); params.put(CrossOriginFilter.ALLOWED_ORIGINS_PARAM, conf.get(CORSConstants.HTTP_ACCESS_CONTROL_ALLOW_ORIGIN, CORSConstants.HTTP_ACCESS_CONTROL_ALLOW_ORIGIN_DEFAULT)); params.put(CrossOriginFilter.ALLOWED_METHODS_PARAM, conf.get(CORSConstants.HTTP_ACCESS_CONTROL_ALLOW_METHODS, CORSConstants.HTTP_ACCESS_CONTROL_ALLOW_METHODS_DEFAULT)); params.put(CrossOriginFilter.ALLOWED_HEADERS_PARAM, conf.get(CORSConstants.HTTP_ACCESS_CONTROL_ALLOW_HEADERS, CORSConstants.HTTP_ACCESS_CONTROL_ALLOW_HEADERS_DEFAULT)); crossOriginFilter.setInitParameters(params); context.addFilter(crossOriginFilter, "/*", EnumSet.of(DispatcherType.REQUEST)); } }; }
private void testCORSGetRequest(String userInfoURI) throws Exception { HttpAuthenticationFeature authenticationFeature = HttpAuthenticationFeature.basic("admin", "admin"); Response response = ClientBuilder.newClient() .target(userInfoURI) .register(authenticationFeature) .request() .header("Origin", "http://example.com") .header("Access-Control-Request-Method", "GET") .get(); Assert.assertEquals(200, response.getStatus()); MultivaluedMap<String, Object> responseHeader = response.getHeaders(); List<Object> allowOriginHeader = responseHeader.get(CrossOriginFilter.ACCESS_CONTROL_ALLOW_ORIGIN_HEADER); Assert.assertNotNull(allowOriginHeader); Assert.assertEquals(1, allowOriginHeader.size()); Assert.assertEquals("http://example.com", allowOriginHeader.get(0)); }
@Override public void run(StripeChargeDropwizardConfiguration configuration, Environment environment) { final FilterRegistration.Dynamic cors = environment.servlets().addFilter("CORS", CrossOriginFilter.class); // Configure CORS parameters cors.setInitParameter("allowedOrigins", configuration.getCoreAllowedOrigin()); cors.setInitParameter("allowedHeaders", "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, "/*"); final ChargeResource resource = new ChargeResource(configuration.getStripeSecretKey()); final StripeAPIHealthCheck healthCheck = new StripeAPIHealthCheck(); environment.healthChecks().register("stripeApi", healthCheck); environment.jersey().register(resource); }
@Override public void run(AgonConfiguration configuration, Environment environment) throws Exception { guiceBundle.getInjector().getInstance(ActionListEventListener.class); // CORS support FilterRegistration.Dynamic filter = environment.servlets().addFilter("Cross Origin Filter", CrossOriginFilter.class); filter.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*"); filter.setInitParameter(CrossOriginFilter.ALLOWED_ORIGINS_PARAM, "*"); filter.setInitParameter(CrossOriginFilter.ALLOWED_HEADERS_PARAM, "Authorization,X-Requested-With,Content-Type,Accept,Origin"); filter.setInitParameter(CrossOriginFilter.ALLOWED_METHODS_PARAM, "OPTIONS,GET,PUT,POST,DELETE,HEAD"); environment.jersey().register(ActionResource.class); environment.jersey().register(BadgeResource.class); environment.jersey().register(EventResource.class); environment.jersey().register(EventTypeResource.class); environment.jersey().register(OAuthResource.class); environment.jersey().register(new RateLimitExceededExceptionMapper()); swaggerDropwizard.onRun(configuration, environment, "localhost"); }
protected void execute1(String component) throws Exception { System.out.println("Starting codeine "+component+" at version " + CodeineVersion.get()); injector = Guice.createInjector(getModules(component)); FilterHolder guiceFilter = new FilterHolder(injector.getInstance(GuiceFilter.class)); ServletContextHandler handler = createServletContextHandler(); handler.setContextPath("/"); FilterHolder crossHolder = new FilterHolder(new CrossOriginFilter()); crossHolder.setInitParameter(CrossOriginFilter.ALLOWED_METHODS_PARAM, "GET, POST, PUT, DELETE"); crossHolder.setInitParameter(CrossOriginFilter.ALLOWED_HEADERS_PARAM, "X-Requested-With,Origin,Content-Type,Accept,api_token"); handler.addFilter(crossHolder, "/api/*", EnumSet.allOf(DispatcherType.class)); handler.addFilter(crossHolder, "/api-with-token/*", EnumSet.allOf(DispatcherType.class)); handler.addFilter(guiceFilter, "/*", EnumSet.allOf(DispatcherType.class)); createAdditionalServlets(handler); ContextHandlerCollection contexts = createFileServerContexts(); contexts.addHandler(handler); int port = startServer(contexts); log.info("jetty started on port " + port); injector.getInstance(CodeineRuntimeInfo.class).setPort(port); execute(); }
@Before public void setUp() { when(mongoConfiguration.getLocateDatabase()).thenReturn("locate"); when(mongoConfiguration.getCredentialsDatabase()).thenReturn("locate"); when(mongoConfiguration.getHosts()).thenReturn("localhost"); when(mongoConfiguration.getPort()).thenReturn(27017); when(configuration.getMongoConfiguration()).thenReturn(mongoConfiguration); when(filterBuilder.setInitParam(anyString(), anyString())).thenReturn(filterBuilder); when(environment.addFilter(CrossOriginFilter.class, "*")).thenReturn(filterBuilder); when(environment.getJerseyResourceConfig()).thenReturn(resourceConfig); when(environment.getObjectMapperFactory()).thenReturn(objectMapperFactory); when(resourceConfig.getSingletons()).thenReturn(Collections.EMPTY_SET); }
public JettyCrosServer() throws Exception { server = new Server(80); HandlerList handlers = new HandlerList(); ResourceHandler resource_handler = new ResourceHandler(); resource_handler.setDirectoriesListed(true); resource_handler.setWelcomeFiles(new String[] { "index.html" }); resource_handler.setBaseResource(Resource.newClassPathResource("web")); ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS); context.setContextPath("/"); context.setInitParameter("maxInterval", "1000"); context.setInitParameter("logLevel", "2"); handlers.setHandlers(new Handler[] { resource_handler, context}); server.setHandler(handlers); FilterHolder filterHolder = new FilterHolder(new CrossOriginFilter()); filterHolder.getInitParameters().put(CrossOriginFilter.ALLOWED_HEADERS_PARAM, "X-Requested-With,Content-Type,Accept,Origin,Authorization"); context.addFilter(filterHolder, "/*", EnumSet.allOf(DispatcherType.class)); context.addServlet(new ServletHolder(new JsonServlet()), "/t.json"); context.addServlet(new ServletHolder(new DefaultServlet()), "/*"); }
private void testHandlesCrossOriginRequest(String domains, boolean wantHandled) throws Exception { final CrossOriginHandler victim = new CrossOriginHandler(domains, "GET,POST,HEAD", "X-Requested-With,Content-Type,Accept,Origin", "1800", "true", ""); final MockJettyRequest req = mock(MockJettyRequest.class); final MockJettyResponse res = mock(MockJettyResponse.class); when(req.getMethod()).thenReturn("OPTIONS"); when(req.getHeader("Origin")).thenReturn("betfair.com"); when(req.getHeader(CrossOriginFilter.ACCESS_CONTROL_REQUEST_METHOD_HEADER)).thenReturn("PUT"); when(req.getHeaders("Connection")).thenReturn(Collections.<String>emptyEnumeration()); victim.handle("/", req, req, res); // this is always called verify(req, times(1)).setHandled(eq(true)); if (wantHandled) { verify(req, never()).setHandled(eq(false)); } else { verify(req, times(1)).setHandled(eq(false)); } }
private void installCorsFilter(Environment environment) { FilterRegistration.Dynamic filter = environment.servlets().addFilter("CORSFilter", CrossOriginFilter.class); filter.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), false, environment.getApplicationContext().getContextPath() + "*"); filter.setInitParameter(CrossOriginFilter.ALLOWED_METHODS_PARAM, "GET,PUT,POST,OPTIONS"); filter.setInitParameter(CrossOriginFilter.ALLOWED_ORIGINS_PARAM, "*"); filter.setInitParameter(CrossOriginFilter.ALLOWED_HEADERS_PARAM, "Origin, Content-Type, Accept, Authorization"); filter.setInitParameter(CrossOriginFilter.ALLOW_CREDENTIALS_PARAM, "true"); }
private FilterHolder configureCors() { final FilterHolder filter = new FilterHolder(new CrossOriginFilter()); filter.setInitParameter(ALLOWED_ORIGINS_PARAM, "*"); filter.setInitParameter(ACCESS_CONTROL_ALLOW_CREDENTIALS_HEADER, valueOf(TRUE)); filter.setInitParameter(ALLOWED_METHODS_PARAM, on(",").join(HttpMethod.values())); filter.setInitParameter(ALLOWED_HEADERS_PARAM, on(",").join(X_PING_OTHER, ORIGIN, X_REQUESTED_WITH, CONTENT_TYPE, ACCEPT)); filter.setInitParameter(PREFLIGHT_MAX_AGE_PARAM, PREFLIGHT_MAX_AGE_VALUE); filter.setInitParameter(ALLOW_CREDENTIALS_PARAM, valueOf(TRUE)); return filter; }
@Override public void run(final DeviceUsageTrackerConfig configuration, final Environment environment) { ConfigurationHolder.set(configuration); environment.jersey().register(DeviceResource.class); environment.jersey().register(UserResource.class); environment.jersey().register(ProfileResource.class); environment.jersey().register(ClaimResource.class); environment.jersey().register(DeviceSlackResource.class); environment.jersey().register(DeviceClaimResource.class); // JSON property naming environment.getObjectMapper().setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE); environment.jersey().register(new CustomExceptionMapper()); // Enable CORS headers final FilterRegistration.Dynamic cors = environment.servlets() .addFilter("CORS", CrossOriginFilter.class); // Configure CORS parameters cors.setInitParameter(CrossOriginFilter.ALLOWED_ORIGINS_PARAM, "*"); cors.setInitParameter(CrossOriginFilter.ALLOWED_HEADERS_PARAM, "X-Requested-With,Content-Type,Accept,Origin,Authorization"); cors.setInitParameter(CrossOriginFilter.ALLOWED_METHODS_PARAM, "OPTIONS,GET,PUT,POST,DELETE,HEAD"); // Add URL mapping cors.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*"); // Auth environment.jersey().register( new AuthenticatorFeature(environment.metrics(), configuration.getAuthConfig())); }
protected void configureCORS() { FilterHolder holder = new FilterHolder(new CrossOriginFilter()); holder.setInitParameter("allowedOrigins", "*"); // TODO - restrict this holder.setInitParameter("allowedMethods", "GET,POST,PUT,DELETE,HEAD,OPTIONS"); holder.setInitParameter("allowedCredentials", "true"); this.handler.addFilterWithMapping(holder, "/*", EnumSet.of(DispatcherType.REQUEST)); }
@Override public void run(AppConfig configuration, Environment environment) throws IOException { // Enable CORS headers final FilterRegistration.Dynamic cors = environment.servlets().addFilter("CORS", CrossOriginFilter.class); // Configure CORS parameters cors.setInitParameter("allowedOrigins", "*"); cors.setInitParameter("allowedHeaders", "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, "/*"); Quadtree quadtree = new Quadtree(); URL world = this.getClass().getResource("tz_world.shp"); new TZShapeReader(quadtree).read(world); TimeZoneService timeZoneService = new TimeZoneService(quadtree); environment.jersey().register(timeZoneService); // // healthChecks // environment.healthChecks().register("app-health-check", new AppHealthCheck()); // // // filter // environment.servlets().addFilter("ip-filter", new IPFilter(configuration.getIPWhiteList(), configuration.getIPBlackList())).addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*"); }
private static void configureCors(Environment env) { final FilterRegistration.Dynamic cors = env.servlets().addFilter("CORS", CrossOriginFilter.class); cors.setInitParameter(CrossOriginFilter.ALLOWED_ORIGINS_PARAM, "*"); cors.setInitParameter(CrossOriginFilter.ALLOWED_HEADERS_PARAM, "X-Requested-With,Content-Type,Accept,Origin,Authorization"); cors.setInitParameter(CrossOriginFilter.ALLOWED_METHODS_PARAM, "OPTIONS,GET,PUT,POST,DELETE,HEAD"); cors.setInitParameter(CrossOriginFilter.ALLOW_CREDENTIALS_PARAM, "true"); // Add URL mapping cors.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*"); }
@Override public void run(final ApiConfiguration configuration, final Environment environment) throws Exception { environment.jersey().register(new SSEController()); // Enable CORS headers; https://gist.github.com/yunspace/07d80a9ac32901f1e149 final FilterRegistration.Dynamic filter = environment.servlets().addFilter("CORS", CrossOriginFilter.class); filter.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), false, environment.getApplicationContext().getContextPath() + "*"); filter.setInitParameter(ALLOWED_METHODS_PARAM, "GET,PUT,POST,OPTIONS"); filter.setInitParameter(ALLOWED_ORIGINS_PARAM, "*"); filter.setInitParameter(ALLOWED_HEADERS_PARAM, "X-Requested-With,Content-Type,Accept,Origin,Authorization"); filter.setInitParameter(ALLOW_CREDENTIALS_PARAM, "true"); }
@Override public void run(BlockExplorerConfiguration configuration, Environment environment) throws Exception { BCSAPI api = hyperLedgerBundle.getBCSAPI(); final FilterRegistration.Dynamic cors = environment.servlets().addFilter("CORS", CrossOriginFilter.class); // Configure CORS parameters cors.setInitParameter("allowedOrigins", "*"); cors.setInitParameter("allowedHeaders", "*"); cors.setInitParameter("allowedMethods", "OPTIONS,GET,PUT,POST,DELETE,HEAD"); // Add URL mapping cors.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*"); environment.jersey().register(new ExplorerResource(api)); }
@Override public void run(final SingularityConfiguration config, final Environment environment) { if (!config.isEnableCorsFilter()) { return; } final Filter corsFilter = new CrossOriginFilter(); final FilterConfig corsFilterConfig = new FilterConfig() { @Override public String getFilterName() { return FILTER_NAME; } @Override public ServletContext getServletContext() { return null; } @Override public String getInitParameter(final String name) { return null; } @Override public Enumeration<String> getInitParameterNames() { return Iterators.asEnumeration(Collections.<String>emptyIterator()); } }; try { corsFilter.init(corsFilterConfig); } catch (final Exception e) { throw Throwables.propagate(e); } environment.servlets().addFilter(FILTER_NAME, corsFilter).addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), false, "/*"); }
private void initCorsFilter(ServletContextHandler context) { FilterHolder corsFilter = context.addFilter(CrossOriginFilter.class, REST_PATH, EnumSet.of(DispatcherType.REQUEST)); corsFilter.setInitParameter(CrossOriginFilter.ALLOWED_ORIGINS_PARAM, "*"); corsFilter.setInitParameter(CrossOriginFilter.ACCESS_CONTROL_ALLOW_ORIGIN_HEADER, "*"); corsFilter.setInitParameter(CrossOriginFilter.ALLOWED_METHODS_PARAM, "DELETE,GET,POST,PUT"); corsFilter.setInitParameter(CrossOriginFilter.ALLOWED_HEADERS_PARAM, "X-Requested-With,Content-Type,Accept,Origin"); }
private void configureSwagger(Environment environment) { BeanConfig config = new BeanConfig(); config.setTitle("Inventory Item API"); config.setVersion("1.0.0"); config.setResourcePackage(InventoryItemResource.class.getPackage().getName()); config.setScan(true); FilterRegistration.Dynamic filter = environment.servlets().addFilter("CORSFilter", CrossOriginFilter.class); filter.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), false, environment.getApplicationContext().getContextPath() + "swagger.json"); filter.setInitParameter(ALLOWED_METHODS_PARAM, "GET,OPTIONS"); filter.setInitParameter(ALLOWED_HEADERS_PARAM, "Origin, Content-Type, Accept"); filter.setInitParameter(ALLOWED_ORIGINS_PARAM, "*"); filter.setInitParameter(ALLOW_CREDENTIALS_PARAM, "true"); }
public static void main(String[] args) throws Exception { ResourceConfig config = new DefaultResourceConfig(ResourceNominatim.class, ObjectMapperContextResolver.class); org.eclipse.jetty.server.Server server = new org.eclipse.jetty.server.Server(8080); ServletContextHandler context = new ServletContextHandler(server, "/"); FilterHolder cof = new FilterHolder(new CrossOriginFilter()); cof.setInitParameter(ALLOWED_HEADERS_PARAM, "*"); context.addFilter(cof, "/*", EnumSet.allOf(DispatcherType.class)); context.addServlet(new ServletHolder(new ServletContainer(config)), "/*"); server.start(); server.join(); }
@Override public void run(Environment environment) { MutableServletContextHandler applicationContext = environment.getApplicationContext(); FilterHolder filterHolder = applicationContext .addFilter(CrossOriginFilter.class, "/*", EnumSet.allOf(DispatcherType.class)); filterHolder.setInitParameter(CrossOriginFilter.ALLOWED_ORIGINS_PARAM, "*"); filterHolder.setInitParameter(CrossOriginFilter.ALLOWED_HEADERS_PARAM, "X-Requested-With,Content-Type,Accept,Origin"); filterHolder.setInitParameter(CrossOriginFilter.ALLOWED_METHODS_PARAM, "GET,HEAD"); filterHolder.setInitParameter(CrossOriginFilter.ALLOW_CREDENTIALS_PARAM, "false"); }
private void enableCORS(Environment environment) { // Enable CORS headers final FilterRegistration.Dynamic cors = environment.servlets().addFilter("CORS", CrossOriginFilter.class); // Configure CORS parameters cors.setInitParameter(CrossOriginFilter.ALLOWED_ORIGINS_PARAM, "*"); cors.setInitParameter(CrossOriginFilter.ALLOWED_HEADERS_PARAM, "X-Requested-With,Authorization,Content-Type,Accept,Origin"); cors.setInitParameter(CrossOriginFilter.ALLOWED_METHODS_PARAM, "OPTIONS,GET,PUT,POST,DELETE,HEAD"); // Add URL mapping cors.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*"); }
private void applyCrossOriginFiltering(WebsocketEndpoint endpoint, ServletContextHandler context) { if (endpoint.isCrossOriginFilterOn()) { FilterHolder filterHolder = new FilterHolder(); CrossOriginFilter filter = new CrossOriginFilter(); filterHolder.setFilter(filter); filterHolder.setInitParameter("allowedOrigins", endpoint.getAllowedOrigins()); context.addFilter(filterHolder, endpoint.getFilterPath(), EnumSet.allOf(DispatcherType.class)); } }
private void applyCrossOriginFiltering(CometdEndpoint endpoint, ServletContextHandler context) { if (endpoint.isCrossOriginFilterOn()) { FilterHolder filterHolder = new FilterHolder(); CrossOriginFilter filter = new CrossOriginFilter(); filterHolder.setFilter(filter); filterHolder.setInitParameter("allowedOrigins", endpoint.getAllowedOrigins()); context.addFilter(filterHolder, endpoint.getFilterPath(), EnumSet.allOf(DispatcherType.class)); } }
private void addCrossOriginFilter(ContextHandler handler) throws ServletException { FilterRegistration reg = handler.getServletContext().addFilter("CrossOriginFilter", CrossOriginFilter.class); reg.addMappingForServletNames(null, false, "*"); reg.setInitParameter(CrossOriginFilter.ALLOWED_ORIGINS_PARAM, configurationService.getProperty(CONFIG_XORIGIN_ORIGINS)); reg.setInitParameter(CrossOriginFilter.ALLOWED_METHODS_PARAM, configurationService.getProperty(CONFIG_XORIGIN_METHODS)); reg.setInitParameter(CrossOriginFilter.ALLOWED_HEADERS_PARAM, configurationService.getProperty(CONFIG_XORIGIN_HEADERS)); reg.setInitParameter(CrossOriginFilter.PREFLIGHT_MAX_AGE_PARAM, configurationService.getProperty(CONFIG_XORIGIN_MAX_AGE)); reg.setInitParameter(CrossOriginFilter.ALLOW_CREDENTIALS_PARAM, configurationService.getProperty(CONFIG_XORIGIN_CREDENTIALS)); }
private static boolean isPreFlightRequest(Request request) { if(HttpMethods.OPTIONS.equalsIgnoreCase(request.getMethod())) { // If the origin does not match allowed the filter will skip anyway so don't bother checking it. if(request.getHeader(ORIGIN_HEADER) != null && request.getHeader(CrossOriginFilter.ACCESS_CONTROL_REQUEST_METHOD_HEADER) != null) { return true; } } return false; }
@Override public void contextInitialized(ServletContextEvent sce) { ServletContext ctx = sce.getServletContext(); Dynamic servlet = ctx.addServlet("jersey", ServletContainer.class); servlet.addMapping("/*"); servlet.setInitParameter("jersey.config.server.provider.classnames", TestServiceImpl.class.getName()); FilterRegistration.Dynamic filter = ctx.addFilter("origin", CrossOriginFilter.class); filter.setInitParameter("allowedMethods", "GET,POST,PUT,DELETE"); filter.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*"); }
public static void startServer() throws Exception { Thread t = new Thread() { @Override public void run() { try { ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS); context.setContextPath("/"); Server server = new Server(8080); server.setHandler(context); ServletHolder jerseyServlet = context.addServlet(ServletContainer.class, "/*"); jerseyServlet.setInitOrder(0); jerseyServlet.setInitParameter("jersey.config.server.provider.classnames", RESTHandler.class.getCanonicalName()); FilterHolder filter = new FilterHolder(); filter.setInitParameter("allowedOrigins", "*"); filter.setInitParameter("allowedMethods", "POST,GET,OPTIONS,PUT,DELETE,HEAD"); filter.setInitParameter("allowedHeaders", "X-PINGOTHER, Origin, X-Requested-With, Content-Type, Accept"); filter.setInitParameter("preflightMaxAge", "728000"); filter.setInitParameter("allowCredentials", "true"); CrossOriginFilter corsFilter = new CrossOriginFilter(); filter.setFilter(corsFilter); context.addFilter(filter, "/*", EnumSet.of(DispatcherType.REQUEST)); server.start(); server.join(); } catch (Exception e) { Debug.log("Error starting uiserver: " + e); } } }; t.start(); }
private void checkCorsFilter(SoaConfiguration configuration, ServletEnvironment servlets) { if ( configuration.isAddCorsFilter() ) { // from http://jitterted.com/tidbits/2014/09/12/cors-for-dropwizard-0-7-x/ FilterRegistration.Dynamic filter = servlets.addFilter("CORS", CrossOriginFilter.class); filter.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*"); filter.setInitParameter(CrossOriginFilter.ALLOWED_METHODS_PARAM, "GET,PUT,POST,DELETE,OPTIONS"); filter.setInitParameter(CrossOriginFilter.ALLOWED_ORIGINS_PARAM, "*"); filter.setInitParameter(CrossOriginFilter.ACCESS_CONTROL_ALLOW_ORIGIN_HEADER, "*"); filter.setInitParameter("allowedHeaders", "Content-Type,Authorization,X-Requested-With,Content-Length,Accept,Origin"); filter.setInitParameter("allowCredentials", "true"); } }
@Override public void run(final BackendConfiguration configuration, final Environment environment) throws Exception { final FilterRegistration.Dynamic crossOriginFilterRegistration = environment.servlets() .addFilter("cors-filter", CrossOriginFilter.class); crossOriginFilterRegistration.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), true, "/*"); crossOriginFilterRegistration.setInitParameter(CrossOriginFilter.ALLOWED_METHODS_PARAM, "GET,POST,PUT,PATCH,DELETE"); configuration.getMetrics().configure(environment.lifecycle(), environment.metrics()); environment.jersey().register(new EntityNotFoundExceptionMapper()); }