玩2.3.X安全header在doFilter中添加CACHE_CONTROLheader时没有了

Play 2.3.X Security headers are gone when adding CACHE_CONTROL header in doFilter

我的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,所有安全性 headers(X-Frame-Options、X-Content-Type-Options、...)都将消失。如何同时启用安全 headers 和 CACHE_CONTROL?

嗯...我不确定其他任何事情...但是您的 headers 丢失了,因为您正在覆盖它们。

要修复 headers 的覆盖问题,您可以按如下方式进行更改,

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 : _* )
    } )
  }
}

这就是我最终做的事情:

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 {
}