Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trouble-shooting CORS in Play Framework 2.4.x

I have a java play framework 2.4.x web app providing a JSON/HTTP API. When I run my front-end HTML/JS file:///Users/nize/tmp/index.html calling the API on http://localhost:9000 chrome shows

XMLHttpRequest cannot load http://localhost:9000. 
No 'Access-Control-Allow-Origin' header is present 
on the requested resource. Origin 'null' is therefore 
not allowed access. The response had HTTP status code 403.

I have configured the web app as per the instructions given in Play Framework 2.4.x CORS Documentation:

  • Update to build.sbt
  • Added the class Filters.javato the root of the project (also tried /app)
  • Added the following stanza to the application.conf:
    play.filters.cors {
      allowedOrigins = ["*","http://localhost"]
      #allowedHttpMethods = ["GET", "POST"]
      #allowedHttpHeaders = ["Accept"]
      #preflightMaxAge = 3 days
    }
    

What am I missing?

Edit: The symptoms look identical or similar to Other very similar stackoverflow post. That problem was solved by reconfiguring Cisco AnyConnect VPN which was installed on the computer. I, however, don't have that software installed.

like image 915
nize Avatar asked Aug 12 '15 21:08

nize


4 Answers

I had the same problem while following the same documentation.

Problem is with this CORS filter that you have used:

allowedOrigins = ["*","http://localhost"]

If you want to allow all origins use:

allowedOrigins = null

Follow the same for allowedHttpMethods

This is as per the documentation

To quote:

The allowed origins. If null, all origins are allowed.

allowedOrigins = null

Hope this helps!

like image 109
Radium Avatar answered Nov 13 '22 19:11

Radium


First add/edit these lines(configurations) into your conf/application.conf

 play.filters.cors {
  # allow all paths
  pathPrefixes = ["/"]
  # allow all origins (You can specify if you want)
  allowedOrigins = null
  allowedHttpMethods = ["GET", "POST", "PUT", "DELETE"]
  # allow all headers
  allowedHttpHeaders = null
 }   

(Note that lines starting with '#' are commented lines.)

Then go to build.sbt and add this line.

libraryDependencies += filters

Finally make a Java Class named 'Filters.java' and include this to the root directory(/app).

import play.api.mvc.EssentialFilter;
import play.filters.cors.CORSFilter;
import play.http.HttpFilters;

import javax.inject.Inject;

public class Filters implements HttpFilters {

    @Inject
    CORSFilter corsFilter;

    public EssentialFilter[] filters() {
        return new EssentialFilter[] { corsFilter };
    }
}

You can refer official documentation for more information.

like image 26
Supun Wijerathne Avatar answered Nov 13 '22 19:11

Supun Wijerathne


I think the CORS filter in Play does not work! I followed step by step as but somehow I always got HTTP-403 in the browser (Chrome and Firefox) in Ajax calls. Problem is I don't even get stacktrace on server side. I think DefaultHttpErrorHandler in the CORS filter somehow gulp that. In the response "Access-Control-Allow-Origin" header was missing so I just manually added that.

class Filters @Inject() (corsFilter: CORSFilter, log: LoggingFilter) extends HttpFilters {
  def filters = {
    // CORS filter does not work
    //Seq(corsFilter, log)
    Seq(log)
  }
}

This is the logging filter (Credit: Play! framework)

class LoggingFilter extends Filter {

  def apply(nextFilter: RequestHeader => Future[Result])(requestHeader: RequestHeader): Future[Result] = {

    val startTime = System.currentTimeMillis

    nextFilter(requestHeader).map { result =>

      val endTime = System.currentTimeMillis
      val requestTime = endTime - startTime

      Logger.info(s"${requestHeader.method} ${requestHeader.uri} " +
        s"took ${requestTime}ms and returned ${result.header.status}")

      result.withHeaders(
        "Request-Time" -> requestTime.toString,
        "Access-Control-Allow-Origin" -> "*"   // Added this header
      )
    }
  }
}
like image 28
Richeek Avatar answered Nov 13 '22 18:11

Richeek


I was experiencing a similar issue, I was getting 403's on requests. I solved a the problem by removing the:

allowedHttpHeaders=["Accept"] 

that they use in their example configuration. I'm still not clear what the security implications of that are, however, so YMMV.

like image 35
Patrick White Avatar answered Nov 13 '22 19:11

Patrick White