I want to implement a CORS filter in my Play 2.2.x application. So far I have the following:
package filters
import play.api.mvc._
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import play.api.GlobalSettings
class CorsFilter extends EssentialFilter {
def apply(next: EssentialAction) = new EssentialAction {
def apply(requestHeader: RequestHeader) = {
next(requestHeader).map { result =>
result.withHeaders("Access-Control-Allow-Origin" -> "*",
"Access-Control-Expose-Headers" -> "WWW-Authenticate, Server-Authorization",
"Access-Control-Allow-Methods" -> "POST, GET, OPTIONS, PUT, DELETE",
"Access-Control-Allow-Headers" -> "x-requested-with,content-type,Cache-Control,Pragma,Date")
}
}
}
}
object Global extends WithFilters(new CorsFilter) with GlobalSettings
as well as a preflight options action:
def preflight(all: String) = Action {
Ok("").withHeaders("Access-Control-Allow-Origin" -> "*",
"Allow" -> "*",
"Access-Control-Allow-Methods" -> "POST, GET, PUT, DELETE, OPTIONS",
"Access-Control-Allow-Headers" -> "Origin, X-Requested-With, Content-Type, Accept, Referrer, User-Agent");
}
with a route defined:
OPTIONS /*all controllers.Application.preflight(all: String)
What seems to be happening is that CorsFilter code isn't being executed. I have my debugger open and I don't see any of my requests hitting this filter. Why would this be? Is there somewhere else I need to define the filter stuff so that Play can see it?
The GlobalSettings
object needs to be in the default package, so package filters
is causing it to be ignored by Play. I'd suggest moving it to it's own file Global.scala
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With