Skip to content

Instantly share code, notes, and snippets.

@mediavrog
Forked from tdrozdowski/CORS_step1.scala
Last active August 29, 2015 14:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mediavrog/8887d2f8f8a1350a1533 to your computer and use it in GitHub Desktop.
Save mediavrog/8887d2f8f8a1350a1533 to your computer and use it in GitHub Desktop.
// 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