Documentation

You are viewing the documentation for the 2.5.17 release in the 2.5.x series of releases. The latest stable release series is 3.0.x.

§Cross-Origin Resource Sharing

Play provides a filter that implements Cross-Origin Resource Sharing (CORS).

CORS is a protocol that allows web applications to make requests from the browser across different domains. A full specification can be found here.

§Enabling the CORS filter

To enable the CORS filter, add the Play filters project to your libraryDependencies in build.sbt:

libraryDependencies += filters

Now add the CORS filter to your filters, which is typically done by creating a Filters class in the root of your project:

Scala
import javax.inject.Inject

import play.api.http.DefaultHttpFilters
import play.filters.cors.CORSFilter

class Filters @Inject() (corsFilter: CORSFilter)
  extends DefaultHttpFilters(corsFilter)
Java
import play.mvc.EssentialFilter;
import play.filters.cors.CORSFilter;
import play.http.DefaultHttpFilters;

import javax.inject.Inject;

public class Filters extends DefaultHttpFilters {
    @Inject public Filters(CORSFilter corsFilter) {
        super(corsFilter);
    }
}

The Filters class can either be in the root package, or if it has another name or is in another package, needs to be configured using play.http.filters in application.conf:

play.http.filters = "filters.MyFilters"

§Configuring the CORS filter

The filter can be configured from application.conf. For a full listing of configuration options, see the Play filters reference.conf.

The available options include:

For example:

play.filters.cors {
  pathPrefixes = ["/some/path", ...]
  allowedOrigins = ["http://www.example.com", ...]
  allowedHttpMethods = ["GET", "POST"]
  allowedHttpHeaders = ["Accept"]
  preflightMaxAge = 3 days
}

Next: Configuring allowed hosts