Enable CORS in Java Play Framework 2.3

1,211 views
Skip to first unread message

Sergio Moreno

unread,
Aug 6, 2014, 12:29:57 AM8/6/14
to play-fr...@googlegroups.com
Hi all!

As the new 2.3 Java version finished the migration of the Response class to Promise<Response> class the following code no longer works.

public class CorsAction extends Action.Simple {

 
public Result call(Context context) throws Throwable{
 
Response response = context.response();
 response
.setHeader("Access-Control-Allow-Origin", "*");
 
//Handle preflight requests
 
if(context.request().method().equals("OPTIONS")) {
   response
.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE");
   response
.setHeader("Access-Control-Max-Age", "3600");
   response
.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization, X-Auth-Token");
   response
.setHeader("Access-Control-Allow-Credentials", "true");
   response
.setHeader("Access-Control-Allow-Origin", "*");
 
return ok()

 
}

 response
.setHeader("Access-Control-Allow-Headers","X-Requested-With, Content-Type, X-Auth-Token");
 
return delegate.call(context);
 
}
}


I am developing an application in Play (Java) 2.3 and I have looked and tried different methods to enable CORS -including adding /OPTIONS methods to the routes file- without success.

I would much appreciate some light on how the new Response implementation would handle this type of interception, because it seems not to have any effects in the headers when implemented in the new Promise<SimpleResponse> class.

Thanks in advance for all the help!!


Will Sargent

unread,
Aug 6, 2014, 1:12:53 AM8/6/14
to play-fr...@googlegroups.com
CORS can be defined using the SecurityHeaders filter.


Will Sargent
Consultant, Professional Services
Typesafe, the company behind Play Framework, Akka and Scala


--
You received this message because you are subscribed to the Google Groups "play-framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email to play-framewor...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Will Sargent

unread,
Aug 6, 2014, 1:21:47 AM8/6/14
to play-fr...@googlegroups.com
Or... not.  I'm thinking of the content security policy.  Apologies, it's been a long day.

It looks like http://empirewindrush.com/tech/2013/12/17/cors-and-play.html should do what you want, although the example is in Scala.

Will Sargent
Consultant, Professional Services
Typesafe, the company behind Play Framework, Akka and Scala


Sergio Moreno

unread,
Aug 6, 2014, 11:44:13 AM8/6/14
to play-fr...@googlegroups.com
Thanks Will!

I used the suggestion from the post you sent (I had the /OPTIONS defined) but I did not use filters in my Global app to intercept the headers. I followed advice here to include a Scala Filter in my Java Global class.

Thanks!!
Reply all
Reply to author
Forward
0 new messages