Categories

  • articles

Tags

  • java

How to add Cross-origin resource sharing (CORS) filter to a embedded Jetty server. Jetty comes with a CORS filter that is easy to use. Add the following to you maven:

<dependency>
	<groupId>org.eclipse.jetty</groupId>
	<artifactId>jetty-servlets</artifactId>
	<version>${jetty.version}</version>
</dependency>

Then just add the following filter to your server:

public static void main(String[] args) throws Exception {
	Server server = new Server(8089);
	ServletHandler handler = new ServletHandler();

	FilterHolder filter = new FilterHolder();
	filter.setInitParameter("allowedOrigins", "http://localhost:8080,http://localhost:8089");
	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);

	FilterMapping filterMapping = createFilterMapping("/*", filter);
	handler.addFilter(filter, filterMapping);

	server.setHandler(handler);
	handler.addServletWithMapping(JsonServlet.class, "/*");

	server.start();
	server.join();
}

Where the following filter init parameters are:

allowedOrigins a comma separated list of origins that are allowed to access the resources. Default value is: * (all origins)

allowedMethods a comma separated list of HTTP methods that are allowed to be used when accessing the resources. Default value is: GET,POST,HEAD

allowedHeaders a comma separated list of HTTP headers that are allowed to be specified when accessing the resources. Default value is: X-Requested-With,Content-Type,Accept,Origin

preflightMaxAge the number of seconds that preflight requests can be cached by the client. Default value is 1800 seconds (30 minutes)

allowCredentials a boolean indicating if the resource allows requests with credentials. Default value is: true