Created
April 1, 2013 11:11
-
-
Save danielreuterwall/5284369 to your computer and use it in GitHub Desktop.
Action composition to enable Cors from your Play API.
This file contains 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
package controllers; | |
import java.lang.annotation.ElementType; | |
import java.lang.annotation.Retention; | |
import java.lang.annotation.RetentionPolicy; | |
import java.lang.annotation.Target; | |
import play.mvc.Action; | |
import play.mvc.Http.Response; | |
import play.mvc.With; | |
import play.mvc.Http.Context; | |
import play.mvc.Result; | |
public class CorsConstraints { | |
/** | |
* Wraps the annotated action in an <code>CorsAction</code>. | |
*/ | |
@With(CorsAction.class) | |
@Target({ ElementType.TYPE, ElementType.METHOD }) | |
@Retention(RetentionPolicy.RUNTIME) | |
public @interface Cors { | |
String value() default "*"; | |
} | |
public static class CorsAction extends Action<Cors> { | |
public Result call(Context context) throws Throwable{ | |
Response response = context.response(); | |
response.setHeader("Access-Control-Allow-Origin",configuration.value()); | |
//Handle preflight requests | |
if(context.request().method().equals("OPTIONS")) { | |
response.setHeader("Access-Control-Allow-Methods", "POST"); | |
response.setHeader("Access-Control-Max-Age", "3600"); | |
response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); | |
return ok(); | |
} | |
response.setHeader("Access-Control-Allow-Headers","X-Requested-With"); | |
return delegate.call(context); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment