允许跨域域共享

时间:2013-02-11 19:30:29

标签: playframework playframework-2.1

我想检查如何在Play Framework 2.1(Java)中启用跨域域共享。我没有看到有关如何执行此操作的任何文档。

2 个答案:

答案 0 :(得分:2)

不确定这是如何转换为2.x的,但在1.2.5中,我所做的就是这个。如果您有非标准标头,则Access-Control-Allow-Headers是可选的。您可以将Allow-Origin的*更改为仅匹配您要允许的域。

@Before
static void CORS() {
    if(request.headers.containsKey("origin")){
        response.headers.put("Access-Control-Allow-Origin", new Header("Access-Control-Allow-Origin", "*"));
        response.headers.put("Access-Control-Allow-Headers", new Header("Access-Control-Allow-Headers", "my-custom-header, my-second-custom-header"));
    }
}

如果你有非标准方法(GET / POST)或使用自定义标题,大多数用户代理将进行预检OPTIONS调用,所以我要做的就是将它添加到我的路由文件中:

#This catches the preflight CORS calls
OPTIONS /{path}                                 Application.options

这在我的控制器中:

/**
 * Cross Origin Request Sharing calls are going to have a pre-flight option call because we use the "non simple headers"
 * This method catches those, (headers handling is done in the CORS() method)
 */
public static void options() {}

答案 1 :(得分:2)

使用Scala语言,一个漂亮而简单的PlayFramework解决方案可以使用以下ActionBuilder

import play.api.mvc._
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global

// An Actionbuilder for CORS - Cross Origin Resource Sharing  
object CorsAction extends ActionBuilder[Request] {

  def invokeBlock[A](request: Request[A], block: (Request[A]) ⇒ Future[SimpleResult]): Future[SimpleResult] = {
    block(request).map { result =>
      request.headers.get("Origin") match {
        case Some(o) => result.withHeaders("Access-Control-Allow-Origin" -> o)
        case None => result
      }
    }
  }
}

ActionBuilder会覆盖invokeBlock方法,目的是将应用程序控制器操作创建的结果(由Play> = 2.1中的Future对象包装)映射到具有附加“Access-Control-Allow-Origin”的相同结果中“如果请求附带”Origin“标题字段,则为标题字段。

上述操作构建器可以简单地使用如下:

object MyController extends Controller {

  def myAction = CorsAction {
     Ok("whatever HTML or JSON you want")
     // it will be certainly processed by your browser
  }
}