加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

scala – 我可以为路由中的所有入口点创建默认的OPTIONS方法指令

发布时间:2020-12-16 18:27:40 所属栏目:安全 来源:网络整理
导读:我不想明确写: options { ... } 对于我的喷涂路线中的每个入口点/路径.我想编写一些通用代码,为所有路径添加OPTIONS支持.它应该查看路由并从中提取支持的方法. 我无法粘贴任何代码,因为我不知道如何在Spray中处理它. 我这样做的原因是我想提供一个符合HATEO
我不想明确写:

options { ... }

对于我的喷涂路线中的每个入口点/路径.我想编写一些通用代码,为所有路径添加OPTIONS支持.它应该查看路由并从中提取支持的方法.

我无法粘贴任何代码,因为我不知道如何在Spray中处理它.

我这样做的原因是我想提供一个符合HATEOAS原则的自我发现的API.

解决方法

以下指令将能够捕获被拒绝的请求,检查它是否是一个选项请求,并返回:

> CORS标头,支持CORS(此指令删除所有cors保护,请注意!!!!!)
>允许标头,为对等方提供可用方法列表

尝试了解以下代码段并在必要时进行调整.您应该更愿意提供尽可能多的信息,但如果您只想返回允许的方法,我建议您删除其余的:).

import spray.http.{AllOrigins,HttpMethods,HttpMethod,HttpResponse}
import spray.http.HttpHeaders._
import spray.http.HttpMethods._
import spray.routing._

/**
 * A mixin to provide support for providing CORS headers as appropriate
 */
trait CorsSupport {
  this: HttpService =>

  private val allowOriginHeader = `Access-Control-Allow-Origin`(AllOrigins)
  private val optionsCorsHeaders = List(
    `Access-Control-Allow-Headers`(
      "Origin,X-Requested-With,Content-Type,Accept,Accept-Encoding,Accept-Language,Host," +
      "Referer,User-Agent"
    ),`Access-Control-Max-Age`(60 * 60 * 24 * 20)  // cache pre-flight response for 20 days
  )

  def cors[T]: Directive0 = mapRequestContext {
    context => context.withRouteResponseHandling {
      // If an OPTIONS request was rejected as 405,complete the request by responding with the
      // defined CORS details and the allowed options grabbed from the rejection
      case Rejected(reasons) if (
        context.request.method == HttpMethods.OPTIONS &&
        reasons.exists(_.isInstanceOf[MethodRejection])
      ) => {
        val allowedMethods = reasons.collect { case r: MethodRejection => r.supported }
        context.complete(HttpResponse().withHeaders(
          `Access-Control-Allow-Methods`(OPTIONS,allowedMethods :_*) ::
          allowOriginHeader ::
          optionsCorsHeaders
        ))
      }
    } withHttpResponseHeadersMapped { headers => allowOriginHeader :: headers }
  }
}

像这样使用它:

val routes: Route =
  cors {
    path("hello") {
      get {
        complete {
          "GET"
        }
      } ~
      put {
        complete {
          "PUT"
        }
      }
    }
  }

资源:https://github.com/giftig/mediaman/blob/22b95a807f6e7bb64d695583f4b856588c223fc1/src/main/scala/com/programmingcentre/utils/utils/CorsSupport.scala

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读