Play Framework CORS configuration and Ionic (WkWebview)

(Matthew Wiley) #1


I’ve been struggling to correctly configure CORS with my Play server for an Ionic app. When I run my app on an iOS device or simulator, I get “preflight response is not successful” errors. However, Android and browser settings work fine (including Chrome, FF, Safari and IE).

I initially tried an “open” policy as below, but did not have any luck.

cors {
	pathPrefixes = ["/"]
        allowedOrigins = null
        allowedHttpMethods = null
        allowedHttpHeaders = null
        exposedHeaders = ["Access-Control-Allow-Origin"]
        preflightMaxAge = 3 days

After reading I developed a configuration to match the following checklist:

  • Adding localhost:8080 as an origin
  • Whitelisting methods
  • Whitelisting headers
  • CORS preflight request (OPTION)

Thus I changed my configuration to:

   pathPrefixes = ["/"]
   allowedOrigins = ["http://localhost:8080"]
   allowedHttpMethods = ["GET", "POST", "PUT", "OPTIONS", "HEAD"]
   allowedHttpHeaders = ["Accept", "Content-Type", "Referer", "X-Requested-With", "X-Auth-Token"]
   exposedHeaders = ["Access-Control-Allow-Origin"]
   preflightMaxAge = 3 days

However I still get the preflight error as before, which leads me to believe I have not implemented CORS correctly in regards to the checklist.

Does this configuration correctly address the CORS checklist from above? Has anyone deployed an Ionic app with a Play Framework backend that successfully handles CORS for WkWebview?

Any help is appreciated! Thanks in advance :slight_smile:

(Marcos Pereira) #2

Hey @mwiley63,

What headers are returned for the prefight request? Can you run a curl command to inspect that? The configuration looks correct, so it would be good to inspect the return and confirm the server is returning what you expect.

Also, which version of Play are you using?

(Adam Lane) #3

Have you tried this?

play.filters.cors.serveForbiddenOrigins = true

Some background…
Your question reminded me of an issue I opened years ago, it could be the same:

You may also want to read this:

Many years ago play would disallow the file:// origin that Ionic sends and there was no way to properly configure it. The only solution was to disable play cors completely and do your own cors filter or cors route. This is what I did to avoid the problem during testing (app never made it to production):


OPTIONS        /*all       controllers.Application.preflight(all)

hacked preflight in Application.scala

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, X-Auth-Token, X-Api-Key")

Hopefully those links help you find an appropriate solution. If you do happen to need to write your own filter, I have this in my notes: