Last active
August 29, 2015 14:16
-
-
Save tobnee/35a5d4ac350227dc4952 to your computer and use it in GitHub Desktop.
Simple CORS in Play Framework
This file contains hidden or 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
import play.api.mvc._ | |
import play.mvc.Http.HeaderNames | |
import scala.concurrent.Future | |
object EnableCORS extends Filter { | |
implicit def ec = play.api.libs.concurrent.Akka.system(play.api.Play.current).dispatcher | |
def apply(f: (RequestHeader) => Future[Result])(rh: RequestHeader): Future[Result] = { | |
val result = f(rh) | |
result.map(_.withHeaders(HeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN -> "*")) | |
} | |
} |
This file contains hidden or 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
import filter.EnableCORS | |
import play.api.mvc | |
import play.api.mvc.{RequestHeader, Result, WithFilters} | |
import scala.concurrent.Future | |
object Global extends WithFilters(EnableCORS) { | |
override def onHandlerNotFound(request: RequestHeader): Future[Result] = { | |
request.method match { | |
case "OPTIONS" if request.headers.get("Origin").isDefined => preflightResponse | |
case _ => super.onHandlerNotFound(request) | |
} | |
} | |
def preflightResponse: Future[Result] = { | |
Future.successful(mvc.Results.Ok.withHeaders( | |
"Access-Control-Allow-Methods" -> "POST, GET, OPTIONS, PUT, DELETE", | |
"Access-Control-Max-Age" -> "3600", | |
"Access-Control-Allow-Headers" -> "Location, Origin, X-Requested-With, Content-Type, Accept, Authorization, X-Auth-Token", | |
"Access-Control-Allow-Credentials" -> "true", | |
"Access-Control-Allow-Origin" -> "*" | |
)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment