Skip to content

Instantly share code, notes, and snippets.

@tdrozdowski
Last active December 27, 2015 19:49
Show Gist options
  • Save tdrozdowski/7379656 to your computer and use it in GitHub Desktop.
Save tdrozdowski/7379656 to your computer and use it in GitHub Desktop.
Adding CORS Support via Filter to PlayFramework 2.2.1
// Create the Global class in your /app folder root package:
import play.api.{GlobalSettings, Play}
import play.api.Play.current
import play.api.mvc._
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global
/**
* Created by terry on 10/19/13.
*/
object Global extends WithFilters(Cors) with GlobalSettings
object Cors extends Filter {
lazy val config = Play.configuration
lazy private val allowedOrigins = config.getString("auth.cors.host").getOrElse("http://localhost:8000")
def apply(f: (RequestHeader) => Future[SimpleResult])(rh: RequestHeader): Future[SimpleResult] = {
val result = f(rh)
val origin = rh.headers.get("Origin")
val defaultAllowed = "http://localhost:8000"
val hostsAllowed = allowedOrigins.split(", ").toList
val allowedOrigin = if (origin.isDefined && hostsAllowed.contains(origin.get)) origin.get else defaultAllowed
// NOTE - the header Access-Control-Allow-Origin won't allow a list of origins - it must be one and only one, so we had to do some magic above...
result.map(_.withHeaders("Access-Control-Allow-Origin" -> allowedOrigin, "Access-Control-Expose-Headers" -> "WWW-Authenticate, Server-Authorization"))
}
}
// add an OPTIONS handler to a controller - Application will do for now
def options(url: String) = Action {
Ok(Json.obj("results" -> "success")).withHeaders(
"Access-Control-Allow-Methods" -> "GET, POST, PUT, DELETE, OPTIONS",
"Access-Control-Allow-Headers" -> "Content-Type, X-Requested-With, Accept, Authorization, User-Agent",
"Access-Control-Max-Age" -> (60 * 60 * 24).toString
)
}
// update your routes - list as final route
OPTIONS /*url controllers.Application.options(url)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment