-
-
Save dat-vikash/f4c96c2af44f57470343 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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")) | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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