Allow cross-origin domain sharing
Not sure what 2.x means, but in 1.2.5 I do it. The Access-Control-Allow-Headers header is optional if you have custom headers. You can change * Allow-Origin to match the domains you want to allow.
@Before
static void CORS() {
if(request.headers.containsKey("origin")){
response.headers.put("Access-Control-Allow-Origin", new Header("Access-Control-Allow-Origin", "*"));
response.headers.put("Access-Control-Allow-Headers", new Header("Access-Control-Allow-Headers", "my-custom-header, my-second-custom-header"));
}
}
If you have non-standard methods (GET / POST) or using custom headers, most of the user agents will have an OPF call before submitting, so what I do is add this to the routes file:
#This catches the preflight CORS calls
OPTIONS /{path} Application.options
and this is in my controller:
/**
* Cross Origin Request Sharing calls are going to have a pre-flight option call because we use the "non simple headers"
* This method catches those, (headers handling is done in the CORS() method)
*/
public static void options() {}
source to share
Using Scala language a nice and simple PlayFramework solution can use the following ActionBuilder
import play.api.mvc._
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global
// An Actionbuilder for CORS - Cross Origin Resource Sharing
object CorsAction extends ActionBuilder[Request] {
def invokeBlock[A](request: Request[A], block: (Request[A]) ⇒ Future[SimpleResult]): Future[SimpleResult] = {
block(request).map { result =>
request.headers.get("Origin") match {
case Some(o) => result.withHeaders("Access-Control-Allow-Origin" -> o)
case None => result
}
}
}
}
ActionBuilder overrides the invokeBlock method to match the result generated by your application controller action (wrapped in a Future object in Play> = 2.1) to the same result with an additional "Access-Control-Allow-Origin" if the request came with an "Origin" header field ...
The above action builder can be used simply like this:
object MyController extends Controller {
def myAction = CorsAction {
Ok("whatever HTML or JSON you want")
// it will be certainly processed by your browser
}
}
source to share