播放2.3.X在doFilter中添加CACHE_CONTROL标头时,安全标头已消失

时间:2015-04-23 20:36:15

标签: scala http-headers playframework-2.3

My Global.scala:

object Global extends WithFilters(SecurityHeadersFilter(), new GzipFilter())
              with GlobalSettings {

  override def doFilter(action: EssentialAction) = EssentialAction { request =>
    action(request).map(_.withHeaders(
      CACHE_CONTROL -> "no-cache, no-store, must-revalidate, private",
      PRAGMA -> "no-cache"
    ))
  }
}

如果我尝试使用CACHE_CONTROL覆盖doFilter,则所有安全标头(X-Frame-Options,X-Content-Type-Options,...)都将消失。如何同时启用安全标头和CACHE_CONTROL?

2 个答案:

答案 0 :(得分:0)

嗯......我不确定其他任何事情......但是你的标题丢失了,因为你要覆盖它们。

要修复标题的覆盖,您可以按照以下方式更改此内容,

object Global extends WithFilters(SecurityHeadersFilter(), new GzipFilter())
          with GlobalSettings {

  override def doFilter(action: EssentialAction) = EssentialAction { request =>
    action(request).map( x =>
      // get the ResponseHeader
      val originalResponseHeader = x.header
      // get Headers from the ResponseHeader
      val originalHeaders = originalResponseHeader.headers
      // create a map of extra headers
      val extraHeaders = Map(
        CACHE_CONTROL -> "no-cache, no-store, must-revalidate, private",
        PRAGMA -> "no-cache"
      )
      // add extra headers to existing headers
      val finalHeaders = originalHeaders ++ extraHeaders
      // convert map to list
      val finalHeadersList = finalHeaders.toList
      // return with final headers
      x.withHeaders( finalHeadersList : _* )
    } )
  }
}

答案 1 :(得分:0)

这就是我最终要做的事情:

object CacheCtrlHeadersFilter extends EssentialFilter {
  def apply(action: EssentialAction) = new EssentialAction {
    def apply(requestHeader: RequestHeader) = {
      action(requestHeader).map { result =>
        result.withHeaders(
            CACHE_CONTROL -> "no-cache, no-store, must-revalidate, private",
            PRAGMA -> "no-cache"
          )
      }
    }
  }
}

object Global extends WithFilters(
  SecurityHeadersFilter(),
  CacheCtrlHeadersFilter,
  new GzipFilter()) with GlobalSettings {
}