播放2.0.1并设置Access-Control-Allow-Origin



我有一个Play 2.0.1应用程序,我想使用托管在其他域的Javascript调用。我的Javascript调用失败了:

Origin http://mydomain.com is not allowed by Access-Control-Allow-Origin.

我发现了一些如何在Play 1中设置正确的HTTP头的例子,但没有找到Play 2.0.1的任何东西。在阅读了文档(http://www.playframework.org/documentation/2.0.2/JavaResponse)之后,我尝试了以下方法来让事情正常工作:

public static Result myJsonWebService() {
  ...
  response().setHeader("Access-Control-Allow-Origin", "*");
  return ok(toJson(jsonObject));
}

但是我的JS web服务调用仍然失败。

我需要做什么才能使它工作?

对于Scala的家伙来说,这是我目前使用的实现:

import play.api.mvc._
import scala.concurrent._
import play.api.http.HeaderNames._
/**
 * Action decorator that provide CORS support
 *
 * @author Giovanni Costagliola, Nick McCready
 */
case class WithCors(httpVerbs: String*)(action: EssentialAction) extends EssentialAction with Results {
    def apply(request: RequestHeader) = {
        implicit val executionContext: ExecutionContext = play.api.libs.concurrent.Execution.defaultContext
        val origin = request.headers.get(ORIGIN).getOrElse("*")
        if (request.method == "OPTIONS") { // preflight
            val corsAction = Action {
                request =>
                    Ok("").withHeaders(
                        ACCESS_CONTROL_ALLOW_ORIGIN -> origin,
                        ACCESS_CONTROL_ALLOW_METHODS -> (httpVerbs.toSet + "OPTIONS").mkString(", "),
                        ACCESS_CONTROL_MAX_AGE -> "3600",
                        ACCESS_CONTROL_ALLOW_HEADERS ->  s"$ORIGIN, X-Requested-With, $CONTENT_TYPE, $ACCEPT, $AUTHORIZATION, X-Auth-Token",
                        ACCESS_CONTROL_ALLOW_CREDENTIALS -> "true")
            }
            corsAction(request)
        } else { // actual request
            action(request).map(res => res.withHeaders(
                ACCESS_CONTROL_ALLOW_ORIGIN -> origin,
                ACCESS_CONTROL_ALLOW_CREDENTIALS -> "true"
            ))
        }
    }
}

要使用它,只需按照以下方式修饰你的动作:

def myAction = WithCors("GET", "POST") {
  Action { request =>
    ???
  }
}

这是一些背景信息…

  • 1) http://www.html5rocks.com/en/tutorials/cors/-请注意,你需要阅读关于"不那么简单的请求"的JSon属于这一类。
  • 2) http://stackoverflow.com/questions/9613210/cors-access-control-allow-origin-despite-correct-headers?rq=1
  • 3) http://caniuse.com/#search=cors -详细介绍支持CORS的浏览器
  • 4) http://stackoverflow.com/questions/10748537/access-control-allow-origin-on-playframework (for Play 1 NOT Play 2)

这是我实现的:

由于不那么简单的请求(见上面的1)会在飞行前调用,您需要在routes文件中添加以下内容:

POST /url_to_json_webservice        controllers.myJsonWebServices.myJsonWebService
OPTIONS /url_to_json_webservice     controllers.myJsonWebServices.checkPreFlight

,然后在控制器中设置以下方法:

public static Result checkPreFlight() {
    response().setHeader("Access-Control-Allow-Origin", "*");       // Need to add the correct domain in here!!
    response().setHeader("Access-Control-Allow-Methods", "POST");   // Only allow POST
    response().setHeader("Access-Control-Max-Age", "300");          // Cache response for 5 minutes
    response().setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");         // Ensure this header is also allowed!  
    return ok();
}

注意,我可能设置了比需要更多的头,所以请检查你需要的!!

还记得在返回实际JSon结果的控制器方法的末尾添加以下内容(如我上面的问题):

public static Result myJsonWebService() {
  ...
  response().setHeader("Access-Control-Allow-Origin", "*");
  return ok(toJson(jsonObject));
}

一个很好的方法是扩展Actions:

package actions;
import play.*;
import play.mvc.*;
import play.mvc.Http.Context;
import play.mvc.Http.Response;
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");
        return ok();
    }
    response.setHeader("Access-Control-Allow-Headers","X-Requested-With, Content-Type, X-Auth-Token");
    return delegate.call(context);
}
}

然后在控制器中添加以下行:

@With(CorsAction.class)

那么所有的ok()请求都将使用上面的标头进行响应。

实现为Scala Filter (play 2.2.x):

import scala.concurrent.ExecutionContext.Implicits.global
import play.api.mvc._
import play.api.mvc.Results._
import play.api.http.HeaderNames._
object Cors extends Filter {
  def apply(next: (RequestHeader) => Future[SimpleResult])(request: RequestHeader): Future[SimpleResult] = {
    val origin = request.headers.get(ORIGIN).getOrElse("*")
    if (request.method == "OPTIONS") {
      val response = Ok.withHeaders(
        ACCESS_CONTROL_ALLOW_ORIGIN -> origin,
        ACCESS_CONTROL_ALLOW_METHODS -> "POST, GET, OPTIONS, PUT, DELETE",
        ACCESS_CONTROL_MAX_AGE -> "3600",
        ACCESS_CONTROL_ALLOW_HEADERS -> s"$ORIGIN, X-Requested-With, $CONTENT_TYPE, $ACCEPT, $AUTHORIZATION, X-Auth-Token",
        ACCESS_CONTROL_ALLOW_CREDENTIALS -> "true"
      )
      Future.successful(response)
    } else {
      next(request).map {
        res => res.withHeaders(
          ACCESS_CONTROL_ALLOW_ORIGIN -> origin,
          ACCESS_CONTROL_ALLOW_CREDENTIALS -> "true"
        )
      }
    }
  }
}
object Global extends WithFilters(Cors) {...}

相关内容

  • 没有找到相关文章

最新更新